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 bootstrap Authenticator and CSR registration #510

Merged
merged 6 commits into from
May 4, 2022
Merged
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
112 changes: 112 additions & 0 deletions agent/authenticator/authenticator_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright 2022 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package authenticator_test

import (
"context"
"crypto/rsa"
"go/build"
"path/filepath"
"testing"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/agent/authenticator"
certv1 "k8s.io/api/certificates/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/manager"
)

func TestAuthenticator(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Authenticator Suite")
}

var (
hostName = "test-host"
cfg *rest.Config
k8sClient client.Client
k8sManager manager.Manager
bootstrapAuthenticator *authenticator.BootstrapAuthenticator
testEnv *envtest.Environment
ctx context.Context
cancel context.CancelFunc
)

var _ = BeforeSuite(func() {
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
ctx, cancel = context.WithCancel(context.TODO())

testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{
filepath.Join("..", "..", "config", "crd", "bases"),
filepath.Join(build.Default.GOPATH, "pkg", "mod", "sigs.k8s.io", "[email protected]", "config", "crd", "bases"),
},
ErrorIfCRDPathMissing: true,
}

var err error
cfg, err = testEnv.Start()
Expect(err).ToNot(HaveOccurred())
Expect(cfg).ToNot(BeNil())

scheme := runtime.NewScheme()

err = corev1.AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

err = certv1.AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
Expect(err).ToNot(HaveOccurred())
Expect(k8sClient).ToNot(BeNil())

k8sManager, err = ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme,
MetricsBindAddress: ":6090",
})
Expect(err).ToNot(HaveOccurred())
Expect(k8sManager).ToNot(BeNil())

bootstrapAuthenticator = &authenticator.BootstrapAuthenticator{
Client: k8sManager.GetClient(),
HostName: hostName,
PrivateKey: &rsa.PrivateKey{},
}
err = bootstrapAuthenticator.SetupWithManager(context.TODO(), k8sManager)
Expect(err).NotTo(HaveOccurred())
go func() {
err = k8sManager.GetCache().Start(ctx)
Expect(err).NotTo(HaveOccurred())
}()

Expect(k8sManager.GetCache().WaitForCacheSync(context.TODO())).To(BeTrue())
})

var _ = AfterSuite(func() {
cancel()
err := testEnv.Stop()
Expect(err).ToNot(HaveOccurred())
})

func WaitForObjectsToBePopulatedInCache(objects ...client.Object) {
pshail marked this conversation as resolved.
Show resolved Hide resolved
for _, object := range objects {
objectCopy := object.DeepCopyObject().(client.Object)
key := client.ObjectKeyFromObject(object)
Eventually(func() (done bool) {
if err := bootstrapAuthenticator.Client.Get(context.TODO(), key, objectCopy); err != nil {
return false
}
return true
}).Should(BeTrue())
}
}
51 changes: 51 additions & 0 deletions agent/authenticator/authenticator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2022 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package authenticator_test

import (
"context"
"fmt"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/agent/authenticator"
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/test/builder"
"k8s.io/apimachinery/pkg/types"
"k8s.io/kubectl/pkg/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

var _ = Describe("Bootstrap Authenticator", func() {

Context("When CSR is submitted", func() {
var (
ctx context.Context
k8sClientUncached client.Client
)
It("should return if the created CSR is not approved or denied", func() {
ctx = context.Background()
var clientErr error
k8sClientUncached, clientErr = client.New(cfg, client.Options{Scheme: scheme.Scheme})
Expect(clientErr).NotTo(HaveOccurred())

ByohCSR, err := builder.CertificateSigningRequest(fmt.Sprintf(authenticator.ByohCSRNameFormat, hostName), fmt.Sprintf("byoh:host:%s", hostName), "byoh:hosts", 2048).Build()
Expect(err).NotTo(HaveOccurred())
Expect(k8sClientUncached.Create(ctx, ByohCSR)).NotTo(HaveOccurred())
WaitForObjectsToBePopulatedInCache(ByohCSR)

_, err = bootstrapAuthenticator.Reconcile(ctx, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: fmt.Sprintf(authenticator.ByohCSRNameFormat, hostName)}})
Expect(err).NotTo(HaveOccurred())
})
It("should return error if CSR does not exist", func() {
ctx = context.Background()
_, err := bootstrapAuthenticator.Reconcile(ctx, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: fmt.Sprintf(authenticator.ByohCSRNameFormat, "fake-host")}})
Expect(err.Error()).To(ContainSubstring("CertificateSigningRequest.certificates.k8s.io \"byoh-csr-fake-host\" not found"))
})
})
})
65 changes: 65 additions & 0 deletions agent/authenticator/bootstrap_authenticator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2022 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package authenticator

import (
"context"
"crypto/rsa"
"fmt"

certv1 "k8s.io/api/certificates/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)

const ByohCSRNameFormat = "byoh-csr-%s"

// BootstrapAuthenticator encapsulates the data/logic needed to reconcile a hostCSR
type BootstrapAuthenticator struct {
Client client.Client
HostName string
PrivateKey *rsa.PrivateKey
}

// Reconcile handles events for the host CSR that is registered by this agent process
func (r *BootstrapAuthenticator) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
logger := ctrl.LoggerFrom(ctx)
logger.Info("Reconcile request received", "resource", req.NamespacedName)

// Fetch the host CSR instance
hostCSR := &certv1.CertificateSigningRequest{}
err := r.Client.Get(ctx, req.NamespacedName, hostCSR)
if err != nil {
logger.Error(err, "error getting host CSR")
return ctrl.Result{}, err
}

// TODO: workflow for approved CSR
pshail marked this conversation as resolved.
Show resolved Hide resolved

// TODO: workflow for rejected CSR

// return if not approved or denied
return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the manager
func (r *BootstrapAuthenticator) SetupWithManager(ctx context.Context, mgr manager.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&certv1.CertificateSigningRequest{}).WithEventFilter(
// watch only own created CSR
predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
return e.Object.GetName() == fmt.Sprintf(ByohCSRNameFormat, r.HostName)
},
UpdateFunc: func(e event.UpdateEvent) bool {
return e.ObjectOld.GetName() == fmt.Sprintf(ByohCSRNameFormat, r.HostName)
},
DeleteFunc: func(e event.DeleteEvent) bool {
return e.Object.GetName() == fmt.Sprintf(ByohCSRNameFormat, r.HostName)
}}).
Complete(r)
}
4 changes: 4 additions & 0 deletions agent/host_agent_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/onsi/gomega/gexec"
infrastructurev1beta1 "github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/apis/infrastructure/v1beta1"
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/test/e2e"
certv1 "k8s.io/api/certificates/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
Expand Down Expand Up @@ -90,6 +91,9 @@ var _ = BeforeSuite(func() {
err = clusterv1.AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

err = certv1.AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
Expect(err).NotTo(HaveOccurred())

Expand Down
Loading