Skip to content
This repository was archived by the owner on Oct 10, 2026. It is now read-only.

Commit 6827d2d

Browse files
committed
feat(tls): present client certificate when tls-auth-clients is enabled
Address review feedback from gemini-code-assist on service/redis/tls.go:22, service/redis/tls.go:37, and operator/redisfailover/service/check.go:38: the operator only loaded the CA bundle from the TLS Secret, so its internal Redis client could connect to a server that ran in non-mutual-TLS mode (tls-auth-clients: no) but had no way to satisfy servers that ran in mutual mode — the handshake would be rejected with no client certificate to validate. BuildTLSConfig now takes optional certPEM/keyPEM PEM blobs and attaches them as tls.Config.Certificates when both are supplied; supplying only one is rejected. tlsConfigFor reads the leaf certificate and key from the same cert-manager Secret (the tls.crt / tls.key entries already populated by the issued Certificate, which carries serverAuth and clientAuth EKUs) when spec.tls.authClients is yes, and fails fast with a descriptive error if either entry is missing or empty. Unit tests cover the new branches: client cert loaded, mismatched cert/key arguments, and malformed cert/key PEMs. Signed-off-by: Arsolitt <[email protected]>
1 parent d6e03db commit 6827d2d

3 files changed

Lines changed: 120 additions & 9 deletions

File tree

‎operator/redisfailover/service/check.go‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,25 @@ func tlsConfigFor(s k8s.Services, rf *redisfailoverv1.RedisFailover) (*tls.Confi
3939
if len(caPEM) == 0 {
4040
return nil, fmt.Errorf("tls: secret %s/%s contains an empty ca.crt", rf.Namespace, secretName)
4141
}
42-
return redis.BuildTLSConfig(caPEM, GetRedisName(rf))
42+
// When the failover runs with tls-auth-clients yes, Redis and
43+
// Sentinel reject any client that does not present a certificate
44+
// signed by the same CA. Load the leaf certificate and its key
45+
// from the standard cert-manager secret keys so the operator's
46+
// internal client can authenticate itself.
47+
var certPEM, keyPEM []byte
48+
if rf.Spec.TLS.AuthClients == redisfailoverv1.TLSAuthClientsYes {
49+
certPEM = secret.Data["tls.crt"]
50+
if len(certPEM) == 0 {
51+
return nil, fmt.Errorf("tls: secret %s/%s does not contain tls.crt (required for authClients=%s)",
52+
rf.Namespace, secretName, redisfailoverv1.TLSAuthClientsYes)
53+
}
54+
keyPEM = secret.Data["tls.key"]
55+
if len(keyPEM) == 0 {
56+
return nil, fmt.Errorf("tls: secret %s/%s does not contain tls.key (required for authClients=%s)",
57+
rf.Namespace, secretName, redisfailoverv1.TLSAuthClientsYes)
58+
}
59+
}
60+
return redis.BuildTLSConfig(caPEM, certPEM, keyPEM, GetRedisName(rf))
4361
}
4462

4563
// RedisFailoverCheck defines the interface able to check the correct status of a redis failover

‎service/redis/tls.go‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,15 @@ import (
1717
// DNS name during the TLS handshake, which the certificate's DNS SANs
1818
// cover.
1919
//
20+
// certPEM and keyPEM are optional. When both are non-empty, the config
21+
// also presents them as a client certificate during the TLS handshake,
22+
// which is required when the Redis and Sentinel pods enforce mutual
23+
// TLS (spec.tls.authClients: yes). Supplying only one of the two is an
24+
// error.
25+
//
2026
// Returns (nil, nil) when caPEM is empty: callers treat a nil config as
2127
// "no TLS" and dial in plaintext.
22-
func BuildTLSConfig(caPEM []byte, serverName string) (*tls.Config, error) {
28+
func BuildTLSConfig(caPEM, certPEM, keyPEM []byte, serverName string) (*tls.Config, error) {
2329
if len(caPEM) == 0 {
2430
return nil, nil
2531
}
@@ -30,9 +36,22 @@ func BuildTLSConfig(caPEM []byte, serverName string) (*tls.Config, error) {
3036
if !pool.AppendCertsFromPEM(caPEM) {
3137
return nil, fmt.Errorf("tls: failed to parse CA certificate (no usable certificates found)")
3238
}
33-
return &tls.Config{
39+
cfg := &tls.Config{
3440
RootCAs: pool,
3541
ServerName: serverName,
3642
MinVersion: tls.VersionTLS12,
37-
}, nil
43+
}
44+
hasCert := len(certPEM) > 0
45+
hasKey := len(keyPEM) > 0
46+
if hasCert != hasKey {
47+
return nil, errors.New("tls: client certPEM and keyPEM must be supplied together")
48+
}
49+
if hasCert {
50+
clientCert, err := tls.X509KeyPair(certPEM, keyPEM)
51+
if err != nil {
52+
return nil, fmt.Errorf("tls: loading client certificate: %w", err)
53+
}
54+
cfg.Certificates = []tls.Certificate{clientCert}
55+
}
56+
return cfg, nil
3857
}

‎service/redis/tls_test.go‎

Lines changed: 79 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,33 +14,33 @@ import (
1414
)
1515

1616
func TestBuildTLSConfigNilOnEmptyCA(t *testing.T) {
17-
cfg, err := BuildTLSConfig(nil, "redis.example.com")
17+
cfg, err := BuildTLSConfig(nil, nil, nil, "redis.example.com")
1818
assert.NoError(t, err)
1919
assert.Nil(t, cfg)
2020

21-
cfg, err = BuildTLSConfig([]byte{}, "redis.example.com")
21+
cfg, err = BuildTLSConfig([]byte{}, nil, nil, "redis.example.com")
2222
assert.NoError(t, err)
2323
assert.Nil(t, cfg)
2424
}
2525

2626
func TestBuildTLSConfigRejectsEmptyServerName(t *testing.T) {
2727
ca := selfSignedCAPEM(t)
28-
_, err := BuildTLSConfig(ca, "")
28+
_, err := BuildTLSConfig(ca, nil, nil, "")
2929
if assert.Error(t, err) {
3030
assert.Contains(t, err.Error(), "ServerName must not be empty")
3131
}
3232
}
3333

3434
func TestBuildTLSConfigRejectsInvalidCA(t *testing.T) {
35-
_, err := BuildTLSConfig([]byte("not a pem"), "redis.example.com")
35+
_, err := BuildTLSConfig([]byte("not a pem"), nil, nil, "redis.example.com")
3636
if assert.Error(t, err) {
3737
assert.Contains(t, err.Error(), "no usable certificates")
3838
}
3939
}
4040

4141
func TestBuildTLSConfigSucceeds(t *testing.T) {
4242
ca := selfSignedCAPEM(t)
43-
cfg, err := BuildTLSConfig(ca, "redis.example.com")
43+
cfg, err := BuildTLSConfig(ca, nil, nil, "redis.example.com")
4444
if !assert.NoError(t, err) {
4545
return
4646
}
@@ -50,6 +50,54 @@ func TestBuildTLSConfigSucceeds(t *testing.T) {
5050
assert.Equal(t, "redis.example.com", cfg.ServerName)
5151
assert.NotNil(t, cfg.RootCAs)
5252
assert.Equal(t, uint16(0x0303), cfg.MinVersion, "MinVersion must be TLS 1.2 (0x0303)")
53+
assert.Empty(t, cfg.Certificates, "no client cert expected when certPEM/keyPEM are nil")
54+
}
55+
56+
func TestBuildTLSConfigLoadsClientCertificate(t *testing.T) {
57+
ca := selfSignedCAPEM(t)
58+
clientCert, clientKey := selfSignedClientPEM(t)
59+
60+
cfg, err := BuildTLSConfig(ca, clientCert, clientKey, "redis.example.com")
61+
if !assert.NoError(t, err) {
62+
return
63+
}
64+
if !assert.NotNil(t, cfg) {
65+
return
66+
}
67+
if !assert.Len(t, cfg.Certificates, 1, "client certificate must be loaded into tls.Config") {
68+
return
69+
}
70+
assert.NotNil(t, cfg.Certificates[0].PrivateKey)
71+
assert.NotEmpty(t, cfg.Certificates[0].Certificate)
72+
}
73+
74+
func TestBuildTLSConfigRejectsCertWithoutKey(t *testing.T) {
75+
ca := selfSignedCAPEM(t)
76+
clientCert, _ := selfSignedClientPEM(t)
77+
78+
_, err := BuildTLSConfig(ca, clientCert, nil, "redis.example.com")
79+
if assert.Error(t, err) {
80+
assert.Contains(t, err.Error(), "must be supplied together")
81+
}
82+
}
83+
84+
func TestBuildTLSConfigRejectsKeyWithoutCert(t *testing.T) {
85+
ca := selfSignedCAPEM(t)
86+
_, clientKey := selfSignedClientPEM(t)
87+
88+
_, err := BuildTLSConfig(ca, nil, clientKey, "redis.example.com")
89+
if assert.Error(t, err) {
90+
assert.Contains(t, err.Error(), "must be supplied together")
91+
}
92+
}
93+
94+
func TestBuildTLSConfigRejectsMalformedClientKeyPair(t *testing.T) {
95+
ca := selfSignedCAPEM(t)
96+
97+
_, err := BuildTLSConfig(ca, []byte("not a cert"), []byte("not a key"), "redis.example.com")
98+
if assert.Error(t, err) {
99+
assert.Contains(t, err.Error(), "loading client certificate")
100+
}
53101
}
54102

55103
// selfSignedCAPEM produces a freshly-minted self-signed CA certificate
@@ -75,3 +123,29 @@ func selfSignedCAPEM(t *testing.T) []byte {
75123
}
76124
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
77125
}
126+
127+
// selfSignedClientPEM produces a freshly-minted self-signed leaf
128+
// certificate plus its PKCS#1 private key, both PEM-encoded, for use as
129+
// a client certificate in BuildTLSConfig tests.
130+
func selfSignedClientPEM(t *testing.T) (certPEM, keyPEM []byte) {
131+
t.Helper()
132+
priv, err := rsa.GenerateKey(rand.Reader, 2048)
133+
if err != nil {
134+
t.Fatalf("rsa.GenerateKey: %v", err)
135+
}
136+
tmpl := &x509.Certificate{
137+
SerialNumber: big.NewInt(2),
138+
Subject: pkix.Name{CommonName: "test-client"},
139+
NotBefore: time.Now().Add(-time.Hour),
140+
NotAfter: time.Now().Add(time.Hour),
141+
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
142+
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
143+
}
144+
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
145+
if err != nil {
146+
t.Fatalf("x509.CreateCertificate: %v", err)
147+
}
148+
certPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
149+
keyPEM = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
150+
return certPEM, keyPEM
151+
}

0 commit comments

Comments
 (0)