Skip to content
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 a file watcher for Azure client cert auth #5254

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions azure/scope/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

infrav1 "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1"
"sigs.k8s.io/cluster-api-provider-azure/pkg/ot"
"sigs.k8s.io/cluster-api-provider-azure/util/filewatcher"
"sigs.k8s.io/cluster-api-provider-azure/util/tele"
)

Expand Down Expand Up @@ -145,6 +146,13 @@
if err != nil {
return nil, errors.Wrap(err, "failed to parse certificate data")
}

// Watch the certificate for changes; if the certificate changes, the pod will be restarted
err = filewatcher.WatchFileForChanges(p.Identity.Spec.CertPath)
if err != nil {
return nil, errors.Wrap(err, "failed to watch certificate file")
}

Check warning on line 154 in azure/scope/identity.go

View check run for this annotation

Codecov / codecov/patch

azure/scope/identity.go#L153-L154

Added lines #L153 - L154 were not covered by tests

cred, authErr = azidentity.NewClientCertificateCredential(p.GetTenantID(), p.Identity.Spec.ClientID, certs, key, &azidentity.ClientCertificateCredentialOptions{
ClientOptions: azcore.ClientOptions{
TracingProvider: tracingProvider,
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ require (
github.com/evanphx/json-patch/v5 v5.9.0
github.com/fatih/camelcase v1.0.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/fsnotify/fsnotify v1.7.0
github.com/go-errors/errors v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
Expand Down
84 changes: 84 additions & 0 deletions util/filewatcher/filewatcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
Copyright 2023 The Kubernetes 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 filewatcher

import (
"os"
"path/filepath"
"sync"

"github.com/fsnotify/fsnotify"
"k8s.io/klog/v2"
)

var watchCertificateFileOnce sync.Once

// WatchFileForChanges watches the file, fileToWatch, for changes. If the file contents have changed, the pod this
// function is running on will be restarted.
func WatchFileForChanges(fileToWatch string) error {
var err error

// This starts only one occurrence of the file watcher, which watches the file, fileToWatch.
watchCertificateFileOnce.Do(func() {
klog.V(2).Infof("Starting the file change watcher on file, %s", fileToWatch)

// Update the file path to watch in case this is a symlink
fileToWatch, err = filepath.EvalSymlinks(fileToWatch)
if err != nil {
return
}

Check warning on line 43 in util/filewatcher/filewatcher.go

View check run for this annotation

Codecov / codecov/patch

util/filewatcher/filewatcher.go#L42-L43

Added lines #L42 - L43 were not covered by tests
klog.V(2).Infof("Watching file, %s", fileToWatch)

// Start the file watcher to monitor file changes
go func() {
err := checkForFileChanges(fileToWatch)
klog.Errorf("Error checking for file changes: %v", err)
}()
})
return err
}

// checkForFileChanges starts a new file watcher. If the file is changed, the pod running this function will exit.
func checkForFileChanges(path string) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}

Check warning on line 60 in util/filewatcher/filewatcher.go

View check run for this annotation

Codecov / codecov/patch

util/filewatcher/filewatcher.go#L59-L60

Added lines #L59 - L60 were not covered by tests

go func() {
for {
select {
case event, ok := <-watcher.Events:
if ok && (event.Has(fsnotify.Write) || event.Has(fsnotify.Chmod) || event.Has(fsnotify.Remove)) {
klog.Infof("file, %s, was modified, exiting...", event.Name)
os.Exit(0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there some more graceful way we can handle this? I don't remember off the top of my head what kinds of cleanup things we might be doing now in main (or will need to do in the future), but I'd prefer not to have to worry about that at all 😄.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm open to alternative suggestions. This is just the pattern we were using in a different project for this specific scenario with Azure SDK not being able to hotload the new cert and requiring the pod to restart in order to use the new cert.

Maybe I'm missing it but I don't see any cleanup things in the main.go. Is that where you were referencing or was it someplace else.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Azure SDK doesn't support hotloading a new certificate yet

What exactly does this mean? CAPZ orchestrates reading the cert from disk and using that to create a TokenCredential, and it's already doing that once in every reconciliation. Do successive calls to azidentity.NewClientCertificateCredential with different certificates not produce working creds?

Copy link
Contributor Author

@bryan-cox bryan-cox Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nojnhuh sorry for the delay, I was doing some testing related this I wanted to check first.

So, if we are grabbing the certificate and re-authenticating with Azure, we shouldn't need this filewatcher to reboot the pod. Like:

parsedCertificate, key, err := azidentity.ParseCertificates(certsContent, nil)
	if err != nil {
		return err
	}

	options := &azidentity.ClientCertificateCredentialOptions{
		SendCertificateChain: true,
	}
	creds, err := azidentity.NewClientCertificateCredential(tenantID, options, ... etc.)

However, with #5211 #5283, when something like Secrets Store CSI updates the certificate in the CAPZ pod, that should invalidate the cache right? The invalidated cache would then trigger a re-authentication with Azure with a new certificate?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's what should happen.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you could validate though that would be great!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I'll pull your PR tomorrow and make an image out of it and give it a go.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tl;dr - I'm going to close this PR. I do not think we need it given the caching PRs mentioned previously in this thread.

I created an image off the latest in CAPZ to use in a deployment with a sidecar container to check to see CAPZ didn't error out when the certificates rotated. In my project, I just modified the deployment of CAPZ and added a sidecar container and a shared volume between the two containers. I was able to exec into that pod, see the certificate, manually rotate the certificate in key vault and disable the old certificate, and see the new certificate in the sidecar container.

The CAPZ pod never rebooted, there were no errors in the log, and I was able to successfully scale up my nodepool using the new certificate.

}
case err, ok := <-watcher.Errors:
if ok {
klog.Errorf("file watcher error: %v", err)
}

Check warning on line 73 in util/filewatcher/filewatcher.go

View check run for this annotation

Codecov / codecov/patch

util/filewatcher/filewatcher.go#L65-L73

Added lines #L65 - L73 were not covered by tests
}
}
}()

err = watcher.Add(path)
if err != nil {
return err
}

Check warning on line 81 in util/filewatcher/filewatcher.go

View check run for this annotation

Codecov / codecov/patch

util/filewatcher/filewatcher.go#L80-L81

Added lines #L80 - L81 were not covered by tests

return nil
}