Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
getRootCAs() - add mutex for concurrency safety
Browse files Browse the repository at this point in the history
Signed-off-by: Zbynek Roubalik <zroubalik@gmail.com>
zroubalik committed Dec 18, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent d3751e9 commit 40b766a
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
@@ -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

0 comments on commit 40b766a

Please sign in to comment.