Skip to content

Commit

Permalink
Addressed a data race condition in the StaticCertManager, and added a…
Browse files Browse the repository at this point in the history
… test to confirm it addressed
  • Loading branch information
kpumuk committed Sep 24, 2024
1 parent 8935623 commit f1df35f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
11 changes: 11 additions & 0 deletions internal/server/cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package server
import (
"crypto/tls"
"log/slog"
"sync"
)

type CertManager interface {
Expand All @@ -14,6 +15,7 @@ type StaticCertManager struct {
tlsCertificateFilePath string
tlsPrivateKeyFilePath string
cert *tls.Certificate
lock sync.RWMutex
}

func NewStaticCertManager(tlsCertificateFilePath, tlsPrivateKeyFilePath string) *StaticCertManager {
Expand All @@ -24,7 +26,16 @@ func NewStaticCertManager(tlsCertificateFilePath, tlsPrivateKeyFilePath string)
}

func (m *StaticCertManager) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
m.lock.RLock()
if m.cert != nil {
defer m.lock.RUnlock()
return m.cert, nil
}
m.lock.RUnlock()

m.lock.Lock()
defer m.lock.Unlock()
if m.cert != nil { // Double-check locking
return m.cert, nil
}

Expand Down
15 changes: 15 additions & 0 deletions internal/server/cert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,21 @@ func TestCertificateLoading(t *testing.T) {
require.NotNil(t, cert)
}

func TestCertificateLoadingRaceCondition(t *testing.T) {
certPath, keyPath, err := prepareTestCertificateFiles()
require.NoError(t, err)
defer os.Remove(certPath)
defer os.Remove(keyPath)

manager := NewStaticCertManager(certPath, keyPath)
go func() {
manager.GetCertificate(&tls.ClientHelloInfo{})
}()
cert, err := manager.GetCertificate(&tls.ClientHelloInfo{})
require.NoError(t, err)
require.NotNil(t, cert)
}

func TestCachesLoadedCertificate(t *testing.T) {
certPath, keyPath, err := prepareTestCertificateFiles()
require.NoError(t, err)
Expand Down

0 comments on commit f1df35f

Please sign in to comment.