-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add certificate watcher to queue-proxy #14189
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
/* | ||
Copyright 2023 The Knative Authors | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package certificate | ||
|
||
import ( | ||
"crypto/sha256" | ||
"crypto/tls" | ||
"os" | ||
"path" | ||
"sync" | ||
"time" | ||
|
||
"go.uber.org/zap" | ||
) | ||
|
||
// CertWatcher watches certificate and key files and reloads them if they change on disk. | ||
type CertWatcher struct { | ||
certPath string | ||
certChecksum [sha256.Size]byte | ||
keyPath string | ||
keyChecksum [sha256.Size]byte | ||
|
||
certificate *tls.Certificate | ||
|
||
logger *zap.SugaredLogger | ||
ticker *time.Ticker | ||
stop chan struct{} | ||
mux sync.RWMutex | ||
} | ||
|
||
// NewCertWatcher creates a CertWatcher and watches | ||
// the certificate and key files. It reloads the contents on file change. | ||
// Make sure to stop the CertWatcher using Stop() upon destroy. | ||
func NewCertWatcher(certPath, keyPath string, reloadInterval time.Duration, logger *zap.SugaredLogger) (*CertWatcher, error) { | ||
cw := &CertWatcher{ | ||
certPath: certPath, | ||
keyPath: keyPath, | ||
logger: logger, | ||
ticker: time.NewTicker(reloadInterval), | ||
stop: make(chan struct{}), | ||
mux: sync.RWMutex{}, | ||
} | ||
|
||
certDir := path.Dir(cw.certPath) | ||
keyDir := path.Dir(cw.keyPath) | ||
|
||
cw.logger.Info("Starting to watch the following directories for changes", | ||
zap.String("certDir", certDir), zap.String("keyDir", keyDir)) | ||
|
||
// initial load | ||
cw.loadCert() | ||
ReToCode marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
go cw.watch() | ||
|
||
return cw, nil | ||
} | ||
|
||
// Stop shuts down the CertWatcher. Use this with `defer`. | ||
func (cw *CertWatcher) Stop() { | ||
cw.logger.Info("Stopping file watcher") | ||
close(cw.stop) | ||
cw.ticker.Stop() | ||
} | ||
|
||
// GetCertificate returns the server certificate for a client-hello request. | ||
func (cw *CertWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { | ||
cw.mux.RLock() | ||
defer cw.mux.RUnlock() | ||
return cw.certificate, nil | ||
} | ||
|
||
func (cw *CertWatcher) watch() { | ||
for { | ||
select { | ||
case <-cw.stop: | ||
return | ||
|
||
case <-cw.ticker.C: | ||
cw.loadCert() | ||
} | ||
} | ||
} | ||
|
||
func (cw *CertWatcher) loadCert() { | ||
var err error | ||
certFile, err := os.ReadFile(cw.certPath) | ||
if err != nil { | ||
cw.logger.Error("failed to load certificate file", zap.String("certPath", cw.certPath), zap.Error(err)) | ||
return | ||
} | ||
keyFile, err := os.ReadFile(cw.keyPath) | ||
if err != nil { | ||
cw.logger.Error("failed to load key file", zap.String("keyPath", cw.keyPath), zap.Error(err)) | ||
return | ||
} | ||
|
||
certChecksum := sha256.Sum256(certFile) | ||
keyChecksum := sha256.Sum256(keyFile) | ||
|
||
if certChecksum != cw.certChecksum || keyChecksum != cw.keyChecksum { | ||
dprotaso marked this conversation as resolved.
Show resolved
Hide resolved
|
||
keyPair, err := tls.LoadX509KeyPair(cw.certPath, cw.keyPath) | ||
if err != nil { | ||
cw.logger.Error("failed to load and parse certificate", zap.Error(err)) | ||
return | ||
} | ||
|
||
cw.mux.Lock() | ||
defer cw.mux.Unlock() | ||
|
||
cw.certificate = &keyPair | ||
cw.certChecksum = certChecksum | ||
cw.keyChecksum = keyChecksum | ||
|
||
cw.logger.Info("Certificate and/or key have changed on disk and were reloaded.") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
/* | ||
Copyright 2023 The Knative Authors | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package certificate | ||
|
||
import ( | ||
"crypto/tls" | ||
"crypto/x509" | ||
"fmt" | ||
"os" | ||
"testing" | ||
"time" | ||
|
||
"k8s.io/apimachinery/pkg/util/wait" | ||
"knative.dev/networking/pkg/certificates" | ||
ktesting "knative.dev/pkg/logging/testing" | ||
) | ||
|
||
const ( | ||
initialSAN = "initial.knative" | ||
updatedSAN = "updated.knative" | ||
) | ||
|
||
func TestCertificateRotation(t *testing.T) { | ||
// Create initial certificate and key on disk | ||
dir := t.TempDir() | ||
|
||
err := createAndSaveCertificate(initialSAN, dir) | ||
if err != nil { | ||
t.Fatal("failed to create and save initial certificate", err) | ||
} | ||
|
||
// Watch the certificate files | ||
cw, err := NewCertWatcher(dir+"/"+certificates.CertName, dir+"/"+certificates.PrivateKeyName, 1*time.Second, ktesting.TestLogger(t)) | ||
if err != nil { | ||
t.Fatal("failed to create CertWatcher", err) | ||
} | ||
|
||
// CertWatcher should return the expected certificate | ||
c, err := cw.GetCertificate(nil) | ||
if err != nil { | ||
t.Fatal("failed to call GetCertificate on CertWatcher", err) | ||
} | ||
san, err := getSAN(c) | ||
if err != nil { | ||
t.Fatal("failed to parse SAN of certificate", err) | ||
} | ||
if san != initialSAN { | ||
t.Errorf("CertWatcher did not return the expected certificate. want: %s, got: %s", initialSAN, san) | ||
} | ||
|
||
// Update the certificate and key on disk | ||
err = createAndSaveCertificate(updatedSAN, dir) | ||
if err != nil { | ||
t.Fatal("failed to update and save initial certificate", err) | ||
} | ||
|
||
// CertWatcher should return the new certificate | ||
// Give CertWatcher some time to update the certificate | ||
if err := wait.Poll(1*time.Second, 30*time.Second, func() (bool, error) { | ||
c, err = cw.GetCertificate(nil) | ||
if err != nil { | ||
return false, err | ||
} | ||
|
||
san, err = getSAN(c) | ||
if err != nil { | ||
return false, err | ||
} | ||
|
||
if san != updatedSAN { | ||
return false, fmt.Errorf("CertWatcher did not return the expected certificate. want: %s, got: %s", updatedSAN, san) | ||
} | ||
|
||
return true, nil | ||
}); err != nil { | ||
t.Fatal(err) | ||
} | ||
} | ||
|
||
func createAndSaveCertificate(san, dir string) error { | ||
ca, err := certificates.CreateCACerts(1 * time.Hour) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
caCert, caKey, err := ca.Parse() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
cert, err := certificates.CreateCert(caKey, caCert, 1*time.Hour, san) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if err := os.WriteFile(dir+"/"+certificates.CertName, cert.CertBytes(), 0644); err != nil { | ||
return err | ||
} | ||
|
||
return os.WriteFile(dir+"/"+certificates.PrivateKeyName, cert.PrivateKeyBytes(), 0644) | ||
} | ||
|
||
func getSAN(c *tls.Certificate) (string, error) { | ||
parsed, err := x509.ParseCertificate(c.Certificate[0]) | ||
if err != nil { | ||
return "", err | ||
} | ||
return parsed.DNSNames[0], nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
certPath
andkeyPath
are fixed value.We can move the const values (
certPath
andkeyPath)
topkg/queue/certificate
or some common package and drop the arguments and field in the struct?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hm for now CertWatcher pretty generic (and could be used somewhere else). The constants seem to be with other configuration in sharedmain which also need to correspond to the yaml, so I think I'd prefer to let them there. WDYT?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, no problem. Let's keep there.