Skip to content

Commit

Permalink
Merge pull request #65 from patoarvizu/reload_ca_cert
Browse files Browse the repository at this point in the history
Listen for changes to 'VAULT_CACERT' or 'VAULT_CAPATH' and reload the client
  • Loading branch information
patoarvizu authored Aug 3, 2020
2 parents 4775322 + b7b660e commit f1979ec
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion pkg/controller/kmsvaultsecret/kmsvaultsecret_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"fmt"
"os"
"time"

"github.com/go-logr/logr"
Expand All @@ -12,6 +13,7 @@ import (

k8sv1alpha1 "github.com/patoarvizu/kms-vault-operator/pkg/apis/k8s/v1alpha1"

"github.com/radovskyb/watcher"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -54,6 +56,35 @@ func renewToken(m VaultAuthMethod) error {
return m.login()
}

func watchCertificate() {
logger := log.WithValues("Function", "WatchCertificate")
w := watcher.New()
w.SetMaxEvents(1)
w.FilterOps(watcher.Write)
watchedCACert := os.Getenv("VAULT_CACERT")
if len(watchedCACert) > 0 {
_ = w.Add(watchedCACert)
}
watchedCAPath := os.Getenv("VAULT_CAPATH")
if len(watchedCAPath) > 0 {
_ = w.Add(watchedCAPath)
}
go func() {
for {
select {
case <-w.Event:
logger.Info("Updating CA certificate for client")
err := setVaultClient()
if err != nil {
logger.Error(err, "Error refreshing client")
os.Exit(1)
}
}
}
}()
go w.Start(time.Millisecond * 100)
}

type KVWriter interface {
write(*k8sv1alpha1.KMSVaultSecret, *vaultapi.Client) error
delete(*k8sv1alpha1.KMSVaultSecret, *vaultapi.Client) error
Expand Down Expand Up @@ -97,10 +128,11 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error {
return err
}

vaultClient, err = vaultapi.NewClient(vaultapi.DefaultConfig())
err = setVaultClient()
if err != nil {
return err
}
watchCertificate()

vaultAuthMethod = vaultAuthentication(VaultAuthenticationMethod)
err = vaultAuthMethod.login()
Expand All @@ -111,6 +143,15 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error {
return nil
}

func setVaultClient() error {
c, err := vaultapi.NewClient(vaultapi.DefaultConfig())
if err != nil {
return err
}
vaultClient = c
return nil
}

var _ reconcile.Reconciler = &ReconcileKMSVaultSecret{}

type ReconcileKMSVaultSecret struct {
Expand Down

0 comments on commit f1979ec

Please sign in to comment.