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 e2e util package to abstract common e2e tasks #136

Merged
merged 1 commit into from
May 2, 2024
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
65 changes: 30 additions & 35 deletions test/e2e/suite/carotation/carotation.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package carotation

import (
"bytes"
"os/exec"
"time"

corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
Expand All @@ -27,11 +27,20 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/cert-manager/csi-driver-spiffe/test/e2e/framework"
"github.com/cert-manager/csi-driver-spiffe/test/e2e/util"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

const (
mountPath = "/var/run/secrets/my-pod"
containerName = "my-container"

pollInterval = 1 * time.Second
pollTimeout = 60 * time.Second
)

var _ = framework.CasesDescribe("CA rotation", func() {
f := framework.NewDefaultFramework("CA rotation")

Expand Down Expand Up @@ -95,14 +104,14 @@ var _ = framework.CasesDescribe("CA rotation", func() {
ServiceAccountName: "test-pod",
Containers: []corev1.Container{
{
Name: "my-container",
Name: containerName,
Image: "docker.io/library/busybox:1.36.1-musl",
ImagePullPolicy: corev1.PullNever,
Command: []string{"sleep", "10000"},
VolumeMounts: []corev1.VolumeMount{
{
Name: "csi-driver-spiffe",
MountPath: "/var/run/secrets/my-pod",
MountPath: mountPath,
},
},
},
Expand All @@ -116,55 +125,41 @@ var _ = framework.CasesDescribe("CA rotation", func() {
Expect(f.Client().Create(f.Context(), &pod2)).NotTo(HaveOccurred())

By("Waiting for pods to become ready")
for _, podName := range []string{"test-pod-1", "test-pod-2"} {
Eventually(func() bool {
var pod corev1.Pod
Expect(f.Client().Get(f.Context(), client.ObjectKey{Namespace: f.Namespace.Name, Name: podName}, &pod)).NotTo(HaveOccurred())

for _, c := range pod.Status.Conditions {
if c.Type == corev1.PodReady {
return c.Status == corev1.ConditionTrue
}
}

return false
}, "20s", "1s").Should(BeTrue(), "expected pod to become ready in time")
}
Expect(util.WaitForPodReady(f, &pod1)).NotTo(HaveOccurred())
Expect(util.WaitForPodReady(f, &pod2)).NotTo(HaveOccurred())

By("Comparing the CA stored in secret with CA stored in the Secret")
var caSecret corev1.Secret
Expect(f.Client().Get(f.Context(), client.ObjectKey{Namespace: f.Config().IssuerSecretNamespace, Name: f.Config().IssuerSecretName}, &caSecret)).NotTo(HaveOccurred())
caData, ok := caSecret.Data["ca.crt"]
Expect(ok).To(BeTrue(), "expected 'ca.crt' to be present in Issuer CA Secret")

for _, podName := range []string{"test-pod-1", "test-pod-2"} {
buf := new(bytes.Buffer)
// #nosec G204
cmd := exec.Command(f.Config().KubectlBinPath, "exec", "-n", f.Namespace.Name, podName, "-cmy-container", "--", "cat", "/var/run/secrets/my-pod/ca.crt")
cmd.Stdout = buf
cmd.Stderr = GinkgoWriter
Expect(cmd.Run()).ToNot(HaveOccurred())
pod1Bundle, err := util.ReadCertFromMountPath(f, mountPath, pod1.Name, containerName)
Expect(err).NotTo(HaveOccurred())

Expect(caData).To(Equal(buf.Bytes()), "expected the Issuer CA bundle to equal the CA mounted to the pod file")
}
pod2Bundle, err := util.ReadCertFromMountPath(f, mountPath, pod2.Name, containerName)
Expect(err).NotTo(HaveOccurred())

Expect(caData).To(Equal(pod1Bundle.CAPEM), "expected Issuer CA bundle to equal CA mounted in pod1 file")

Expect(caData).To(Equal(pod2Bundle.CAPEM), "expected Issuer CA bundle to equal CA mounted in pod2 file")

By("Updating the CA data in Secret")

newCAData := append([]byte("# This is a comment\n"), caData...)

caSecret.Data["ca.crt"] = newCAData
Expect(f.Client().Update(f.Context(), &caSecret)).NotTo(HaveOccurred())

By("Waiting for the new CA data to be written to pod volumes")
for _, podName := range []string{"test-pod-1", "test-pod-2"} {
for _, podName := range []string{pod1.Name, pod2.Name} {
Eventually(func() bool {
buf := new(bytes.Buffer)
// #nosec G204
cmd := exec.Command(f.Config().KubectlBinPath, "exec", "-n"+f.Namespace.Name, podName, "-cmy-container", "--", "cat", "/var/run/secrets/my-pod/ca.crt")
cmd.Stdout = buf
cmd.Stderr = GinkgoWriter
Expect(cmd.Run()).ToNot(HaveOccurred())

return bytes.Equal(buf.Bytes(), newCAData)
}, "100s", "1s").Should(BeTrue(), "expected the CA data to be updated on pod file")
newBundle, err := util.ReadCertFromMountPath(f, mountPath, podName, containerName)
Expect(err).ToNot(HaveOccurred())

return bytes.Equal(newBundle.CAPEM, newCAData)
}).WithTimeout(pollTimeout).WithPolling(pollInterval).WithContext(f.Context()).Should(BeTrue(), "expected the CA data to be updated on pod file")
}

By("Cleaning up resources")
Expand Down
66 changes: 21 additions & 45 deletions test/e2e/suite/fsgroup/fsgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,23 @@ limitations under the License.
package fsgroup

import (
"bytes"
"os/exec"

corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/cert-manager/csi-driver-spiffe/test/e2e/framework"
"github.com/cert-manager/csi-driver-spiffe/test/e2e/util"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

const (
mountPath = "/var/run/secrets/my-pod"
containerName = "my-container"
)

var _ = framework.CasesDescribe("FSGroup", func() {
f := framework.NewDefaultFramework("FSGroup")

Expand Down Expand Up @@ -64,14 +66,14 @@ var _ = framework.CasesDescribe("FSGroup", func() {
},
Containers: []corev1.Container{
{
Name: "my-container",
Name: containerName,
Image: "docker.io/library/busybox:1.36.1-musl",
ImagePullPolicy: corev1.PullNever,
Command: []string{"sleep", "10000"},
VolumeMounts: []corev1.VolumeMount{
{
Name: "csi-driver-spiffe",
MountPath: "/var/run/secrets/my-pod",
MountPath: mountPath,
},
},
},
Expand Down Expand Up @@ -137,27 +139,14 @@ var _ = framework.CasesDescribe("FSGroup", func() {
Expect(f.Client().Create(f.Context(), &pod)).NotTo(HaveOccurred())

By("Waiting for pod to become ready")
Eventually(func() bool {
Expect(f.Client().Get(f.Context(), client.ObjectKey{Namespace: f.Namespace.Name, Name: pod.Name}, &pod)).NotTo(HaveOccurred())
for _, c := range pod.Status.Conditions {
if c.Type == corev1.PodReady {
return c.Status == corev1.ConditionTrue
}
}
return false
}, "180s", "1s").Should(BeTrue(), "expected pod to become ready in time")
Expect(util.WaitForPodReady(f, &pod)).NotTo(HaveOccurred())

By("Ensuring files can be read from volume")
for _, filename := range []string{"tls.crt", "tls.key", "ca.crt"} {
buf := new(bytes.Buffer)
// #nosec G204
cmd := exec.Command(f.Config().KubectlBinPath, "exec", "-n", f.Namespace.Name, pod.Name, "-cmy-container", "--", "cat", "/var/run/secrets/my-pod/"+filename)
cmd.Stdout = buf
cmd.Stderr = GinkgoWriter
Expect(cmd.Run()).ToNot(HaveOccurred())

Expect(buf.Bytes()).NotTo(BeEmpty(), "expected the file to have a non-zero entry")
}
bundle, err := util.ReadCertFromMountPath(f, mountPath, pod.Name, containerName)
Expect(err).NotTo(HaveOccurred())

Expect(bundle.CheckNotEmpty()).NotTo(HaveOccurred())

Expect(f.Client().Delete(f.Context(), &pod)).NotTo(HaveOccurred())
})

Expand All @@ -169,28 +158,15 @@ var _ = framework.CasesDescribe("FSGroup", func() {
badPod.Spec.SecurityContext.RunAsGroup = ptr.To(int64(123))
Expect(f.Client().Create(f.Context(), &badPod)).NotTo(HaveOccurred())

By("Waiting for pod to become ready")
Eventually(func() bool {
Expect(f.Client().Get(f.Context(), client.ObjectKey{Namespace: f.Namespace.Name, Name: badPod.Name}, &badPod)).NotTo(HaveOccurred())
for _, c := range badPod.Status.Conditions {
if c.Type == corev1.PodReady {
return c.Status == corev1.ConditionTrue
}
}
return false
}, "180s", "1s").Should(BeTrue(), "expected pod to become ready in time")
By("Waiting for bad pod to become ready")
Expect(util.WaitForPodReady(f, &badPod)).NotTo(HaveOccurred())

By("Ensuring files cannot be read from volume")
for _, filename := range []string{"tls.crt", "tls.key", "ca.crt"} {
buf := new(bytes.Buffer)
// #nosec G204
cmd := exec.Command(f.Config().KubectlBinPath, "exec", "-n", f.Namespace.Name, badPod.Name, "-cmy-container", "--", "cat", "/var/run/secrets/my-pod/"+filename)
cmd.Stdout = buf
cmd.Stderr = GinkgoWriter
Expect(cmd.Run()).To(HaveOccurred())

Expect(buf.Bytes()).To(BeEmpty(), "expected the file to have a zero entry")
}
bundle, err := util.ReadCertFromMountPath(f, mountPath, badPod.Name, containerName)
Expect(err).To(HaveOccurred())

Expect(bundle).To(BeNil())

Expect(f.Client().Delete(f.Context(), &badPod)).NotTo(HaveOccurred())
})
})
141 changes: 141 additions & 0 deletions test/e2e/util/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
Copyright 2024 The cert-manager 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 util

import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"path/filepath"
"time"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/wait"
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/cert-manager/csi-driver-spiffe/test/e2e/framework"

. "github.com/onsi/ginkgo/v2"
)

const (
pollInterval = 1 * time.Second
pollTimeout = 60 * time.Second
pollImmediate = false
)

func WaitForPodReady(f *framework.Framework, pod *corev1.Pod) error {
return wait.PollUntilContextTimeout(f.Context(), pollInterval, pollTimeout, pollImmediate, func(ctx context.Context) (bool, error) {
err := f.Client().Get(ctx, client.ObjectKeyFromObject(pod), pod)
if err != nil {
return false, err
}

for _, cond := range pod.Status.Conditions {
if cond.Type != corev1.PodReady {
continue
}

return cond.Status == corev1.ConditionTrue, nil
}

return false, nil
})
}

// CertBundle holds PEM data read from a csi-driver-spiffe mounted volume
type CertBundle struct {
CertificatePEM []byte
PrivateKeyPEM []byte
CAPEM []byte
}

// CheckNotEmpty returns an error if any of the PEM entries in the CertBundle are empty
func (cb *CertBundle) CheckNotEmpty() error {
if cb == nil {
return fmt.Errorf("nil CertBundle is empty")
}

var errs []error

if len(cb.CertificatePEM) == 0 {
errs = append(errs, fmt.Errorf("tls.crt was empty"))
}

if len(cb.PrivateKeyPEM) == 0 {
errs = append(errs, fmt.Errorf("tls.key was empty"))
}

if len(cb.CAPEM) == 0 {
errs = append(errs, fmt.Errorf("ca.crt was empty"))
}

return errors.Join(errs...)
}

// ReadCertFromMountPath uses kubectl exec to retrieve tls.crt, tls.key and ca.crt from a running pod
func ReadCertFromMountPath(f *framework.Framework, mountPath string, podName string, containerName string) (*CertBundle, error) {
bundle := new(CertBundle)

type fileWithPtr struct {
Filename string
TargetBuffer *[]byte
}

targets := []fileWithPtr{{
Filename: "tls.crt",
TargetBuffer: &bundle.CertificatePEM,
}, {
Filename: "tls.key",
TargetBuffer: &bundle.PrivateKeyPEM,
}, {
Filename: "ca.crt",
TargetBuffer: &bundle.CAPEM,
}}

var readErrs []error

for _, target := range targets {
buf := new(bytes.Buffer)

fullPath := filepath.Join(mountPath, target.Filename)
containerArg := fmt.Sprintf("-c%s", containerName)

// #nosec G204
cmd := exec.Command(f.Config().KubectlBinPath, "exec", "-n", f.Namespace.Name, podName, containerArg, "--", "cat", fullPath)

cmd.Stdout = buf
cmd.Stderr = GinkgoWriter

err := cmd.Run()
if err != nil {
readErrs = append(readErrs, fmt.Errorf("failed to read %q from target pod: %s", fullPath, err))
continue
}

*target.TargetBuffer = buf.Bytes()
}

err := errors.Join(readErrs...)
if err != nil {
return nil, err
}

return bundle, nil
}