Skip to content

Commit efd2902

Browse files
adding certwatcher as external package
Signed-off-by: Chris Hein <[email protected]>
1 parent b5065bd commit efd2902

File tree

5 files changed

+250
-5
lines changed

5 files changed

+250
-5
lines changed

pkg/webhook/internal/certwatcher/certwatcher.go renamed to pkg/certwatcher/certwatcher.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Copyright 2019 The Kubernetes Authors.
2+
Copyright 2021 The Kubernetes Authors.
33
44
Licensed under the Apache License, Version 2.0 (the "License");
55
you may not use this file except in compliance with the License.
@@ -31,7 +31,7 @@ var log = logf.RuntimeLog.WithName("certwatcher")
3131
// changes, it reads and parses both and calls an optional callback with the new
3232
// certificate.
3333
type CertWatcher struct {
34-
sync.Mutex
34+
sync.RWMutex
3535

3636
currentCert *tls.Certificate
3737
watcher *fsnotify.Watcher
@@ -64,8 +64,8 @@ func New(certPath, keyPath string) (*CertWatcher, error) {
6464

6565
// GetCertificate fetches the currently loaded certificate, which may be nil.
6666
func (cw *CertWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
67-
cw.Lock()
68-
defer cw.Unlock()
67+
cw.RLock()
68+
defer cw.RUnlock()
6969
return cw.currentCert, nil
7070
}
7171

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package certwatcher_test
18+
19+
import (
20+
"os"
21+
"testing"
22+
23+
. "github.com/onsi/ginkgo"
24+
. "github.com/onsi/gomega"
25+
"sigs.k8s.io/controller-runtime/pkg/envtest/printer"
26+
logf "sigs.k8s.io/controller-runtime/pkg/log"
27+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
28+
)
29+
30+
var (
31+
certPath = "testdata/tls.crt"
32+
keyPath = "testdata/tls.key"
33+
)
34+
35+
func TestSource(t *testing.T) {
36+
RegisterFailHandler(Fail)
37+
suiteName := "CertWatcher Suite"
38+
RunSpecsWithDefaultAndCustomReporters(t, suiteName, []Reporter{printer.NewlineReporter{}, printer.NewProwReporter(suiteName)})
39+
}
40+
41+
var _ = BeforeSuite(func(done Done) {
42+
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
43+
44+
close(done)
45+
}, 60)
46+
47+
var _ = AfterSuite(func(done Done) {
48+
for _, file := range []string{certPath, keyPath} {
49+
_ = os.Remove(file)
50+
}
51+
close(done)
52+
}, 60)

pkg/certwatcher/certwatcher_test.go

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package certwatcher_test
18+
19+
import (
20+
"context"
21+
"crypto/rand"
22+
"crypto/rsa"
23+
"crypto/x509"
24+
"crypto/x509/pkix"
25+
"encoding/pem"
26+
"math/big"
27+
"net"
28+
"os"
29+
"time"
30+
31+
. "github.com/onsi/ginkgo"
32+
. "github.com/onsi/gomega"
33+
"sigs.k8s.io/controller-runtime/pkg/certwatcher"
34+
)
35+
36+
var _ = Describe("CertWatcher", func() {
37+
var _ = Describe("certwatcher New", func() {
38+
It("should errors without cert/key", func() {
39+
_, err := certwatcher.New("", "")
40+
Expect(err).ToNot(BeNil())
41+
})
42+
})
43+
44+
var _ = Describe("certwatcher Start", func() {
45+
var (
46+
ctx context.Context
47+
ctxCancel context.CancelFunc
48+
watcher *certwatcher.CertWatcher
49+
)
50+
51+
BeforeEach(func() {
52+
ctx, ctxCancel = context.WithCancel(context.Background())
53+
54+
err := writeCerts(certPath, keyPath, "127.0.0.1")
55+
Expect(err).To(BeNil())
56+
57+
Eventually(func() error {
58+
for _, file := range []string{certPath, keyPath} {
59+
_, err := os.ReadFile(file)
60+
if err != nil {
61+
return err
62+
}
63+
continue
64+
}
65+
66+
return nil
67+
}).Should(Succeed())
68+
69+
watcher, _ = certwatcher.New(certPath, keyPath)
70+
})
71+
72+
startWatcher := func() (done <-chan struct{}) {
73+
doneCh := make(chan struct{})
74+
go func() {
75+
defer GinkgoRecover()
76+
defer close(doneCh)
77+
Expect(watcher.Start(ctx)).To(Succeed())
78+
}()
79+
// wait till we read first cert
80+
Eventually(func() error {
81+
err := watcher.ReadCertificate()
82+
return err
83+
}).Should(Succeed())
84+
return doneCh
85+
}
86+
87+
It("should read the initial cert/key", func() {
88+
doneCh := startWatcher()
89+
90+
ctxCancel()
91+
Eventually(doneCh, "4s").Should(BeClosed())
92+
})
93+
94+
It("should reload currentCert when changed", func() {
95+
doneCh := startWatcher()
96+
97+
firstcert, _ := watcher.GetCertificate(nil)
98+
99+
err := writeCerts(certPath, keyPath, "192.168.0.1")
100+
Expect(err).To(BeNil())
101+
102+
Eventually(func() bool {
103+
secondcert, _ := watcher.GetCertificate(nil)
104+
first := firstcert.PrivateKey.(*rsa.PrivateKey)
105+
return first.Equal(secondcert.PrivateKey)
106+
}).ShouldNot(BeTrue())
107+
108+
ctxCancel()
109+
Eventually(doneCh, "4s").Should(BeClosed())
110+
})
111+
})
112+
})
113+
114+
func publicKey(priv interface{}) interface{} {
115+
switch k := priv.(type) {
116+
case *rsa.PrivateKey:
117+
return &k.PublicKey
118+
default:
119+
return nil
120+
}
121+
}
122+
123+
func writeCerts(certPath, keyPath, ip string) error {
124+
var priv interface{}
125+
var err error
126+
priv, err = rsa.GenerateKey(rand.Reader, 2048)
127+
if err != nil {
128+
return err
129+
}
130+
131+
keyUsage := x509.KeyUsageDigitalSignature
132+
if _, isRSA := priv.(*rsa.PrivateKey); isRSA {
133+
keyUsage |= x509.KeyUsageKeyEncipherment
134+
}
135+
136+
var notBefore time.Time
137+
notBefore = time.Now()
138+
139+
notAfter := notBefore.Add(1 * time.Hour)
140+
141+
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
142+
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
143+
if err != nil {
144+
return err
145+
}
146+
147+
template := x509.Certificate{
148+
SerialNumber: serialNumber,
149+
Subject: pkix.Name{
150+
Organization: []string{"Kubernetes"},
151+
},
152+
NotBefore: notBefore,
153+
NotAfter: notAfter,
154+
155+
KeyUsage: keyUsage,
156+
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
157+
BasicConstraintsValid: true,
158+
}
159+
160+
template.IPAddresses = append(template.IPAddresses, net.ParseIP(ip))
161+
162+
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
163+
if err != nil {
164+
return err
165+
}
166+
167+
certOut, err := os.Create(certPath)
168+
if err != nil {
169+
return err
170+
}
171+
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
172+
return err
173+
}
174+
if err := certOut.Close(); err != nil {
175+
return err
176+
}
177+
178+
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
179+
if err != nil {
180+
return err
181+
}
182+
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
183+
if err != nil {
184+
return err
185+
}
186+
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
187+
return err
188+
}
189+
if err := keyOut.Close(); err != nil {
190+
return err
191+
}
192+
return nil
193+
}

pkg/certwatcher/testdata/.gitkeep

Whitespace-only changes.

pkg/webhook/server.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ import (
3131

3232
"github.com/prometheus/client_golang/prometheus"
3333
"github.com/prometheus/client_golang/prometheus/promhttp"
34+
"sigs.k8s.io/controller-runtime/pkg/certwatcher"
3435
"sigs.k8s.io/controller-runtime/pkg/runtime/inject"
35-
"sigs.k8s.io/controller-runtime/pkg/webhook/internal/certwatcher"
3636
"sigs.k8s.io/controller-runtime/pkg/webhook/internal/metrics"
3737
)
3838

0 commit comments

Comments
 (0)