From 09d4f8cd0fa8e01e897aab52486ba6ece1d50803 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Mon, 28 Nov 2022 01:14:33 -0800 Subject: [PATCH] avoid serializing decryptKey() every 15mins (#16135) if the certs are the same in an environment where the cert files are symlinks (e.g Kubernetes), then we resort to reloading certs every 15mins - we can avoid reload of the kes client instance. Ensure that the price to pay for contending with the lock must happen when necessary. --- internal/kms/kes.go | 41 +++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/internal/kms/kes.go b/internal/kms/kes.go index ce1f0a1621aca..c7c2290d33f5d 100644 --- a/internal/kms/kes.go +++ b/internal/kms/kes.go @@ -18,6 +18,7 @@ package kms import ( + "bytes" "context" "crypto/tls" "crypto/x509" @@ -95,19 +96,35 @@ func NewWithConfig(config Config) (KMS, error) { } go func() { for { + var prevCertificate tls.Certificate select { - case certificate := <-config.ReloadCertEvents: - client := kes.NewClientWithConfig("", &tls.Config{ - MinVersion: tls.VersionTLS12, - Certificates: []tls.Certificate{certificate}, - RootCAs: config.RootCAs, - ClientSessionCache: tls.NewLRUClientSessionCache(tlsClientSessionCacheSize), - }) - client.Endpoints = endpoints - - c.lock.Lock() - c.client = client - c.lock.Unlock() + case certificate, ok := <-config.ReloadCertEvents: + if !ok { + return + } + sameCert := true + for i, b := range certificate.Certificate { + if !bytes.Equal(b, prevCertificate.Certificate[i]) { + sameCert = false + break + } + } + // Do not reload if its the same cert as before. + if !sameCert { + client := kes.NewClientWithConfig("", &tls.Config{ + MinVersion: tls.VersionTLS12, + Certificates: []tls.Certificate{certificate}, + RootCAs: config.RootCAs, + ClientSessionCache: tls.NewLRUClientSessionCache(tlsClientSessionCacheSize), + }) + client.Endpoints = endpoints + + c.lock.Lock() + c.client = client + c.lock.Unlock() + + prevCertificate = certificate + } } } }()