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

feat: Add admission controller test suite #440

Merged
merged 3 commits into from
Oct 17, 2023
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
creationTimestamp: null
labels:
crowdstrike.com/component: rbac
crowdstrike.com/created-by: falcon-operator
crowdstrike.com/instance: admission-controller-role
crowdstrike.com/managed-by: kustomize
crowdstrike.com/name: clusterrole
crowdstrike.com/part-of: Falcon
crowdstrike.com/provider: crowdstrike
name: falcon-operator-admission-controller-role
rules:
- apiGroups:
- ""
resources:
- namespaces
- nodes
verbs:
- get
- list
- watch
- apiGroups:
- apps
resources:
- daemonsets
- deployments
verbs:
- get
- list
- watch
363 changes: 360 additions & 3 deletions bundle/manifests/falcon-operator.clusterserviceversion.yaml

Large diffs are not rendered by default.

548 changes: 548 additions & 0 deletions bundle/manifests/falcon.crowdstrike.com_falconadmissions.yaml

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -1899,7 +1899,7 @@ spec:
type: boolean
type: object
type:
description: Type of the registry to be used
description: Type of container registry to be used
enum:
- acr
- ecr
Expand Down
4 changes: 2 additions & 2 deletions bundle/metadata/annotations.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ annotations:
operators.operatorframework.io.bundle.metadata.v1: metadata/
operators.operatorframework.io.bundle.package.v1: falcon-operator
operators.operatorframework.io.bundle.channels.v1: alpha
operators.operatorframework.io.metrics.builder: operator-sdk-v1.30.0
operators.operatorframework.io.metrics.builder: operator-sdk-v1.29.0
operators.operatorframework.io.metrics.mediatype.v1: metrics+v1
operators.operatorframework.io.metrics.project_layout: go.kubebuilder.io/v3
operators.operatorframework.io.metrics.project_layout: go.kubebuilder.io/v4-alpha

# Annotations for testing.
operators.operatorframework.io.test.mediatype.v1: scorecard+v1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,7 @@ spec:
type: boolean
image:
description: Location of the Falcon Sensor image. Use only in
cases when you mirror the original image to your repository/name:tag,
and CrowdStrike OAuth2 API is not used.
cases when you mirror the original image to your repository/name:tag
pattern: ^.*:.*$
type: string
imagePullPolicy:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,8 +392,7 @@ spec:
x-descriptors:
- urn:alm:descriptor:com.tectonic.ui:password
- description: Location of the Falcon Sensor image. Use only in cases when you
mirror the original image to your repository/name:tag, and CrowdStrike OAuth2
API is not used.
mirror the original image to your repository/name:tag
displayName: Image
path: node.image
- description: Disable the Falcon Sensor's use of a proxy.
Expand Down
6 changes: 4 additions & 2 deletions controllers/admission/falconadmission_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ type FalconAdmissionReconciler struct {
Scheme *runtime.Scheme
}

const nsTest = "falcon-kac"

// SetupWithManager sets up the controller with the Manager.
func (r *FalconAdmissionReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
Expand Down Expand Up @@ -137,6 +135,10 @@ func (r *FalconAdmissionReconciler) Reconcile(ctx context.Context, req ctrl.Requ
}
}

if err := r.reconcileNamespace(ctx, req, log, falconAdmission); err != nil {
return ctrl.Result{}, err
}

// Image being set will override other image based settings
if falconAdmission.Spec.Image != "" {
if _, err := r.setImageTag(ctx, falconAdmission); err != nil {
Expand Down
172 changes: 172 additions & 0 deletions controllers/admission/falconadmission_controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package controllers

import (
"context"
"fmt"
"time"

falconv1alpha1 "github.com/crowdstrike/falcon-operator/api/falcon/v1alpha1"
k8sutils "github.com/crowdstrike/falcon-operator/internal/controller/common"
"github.com/crowdstrike/falcon-operator/pkg/common"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

var _ = Describe("FalconAdmission controller", func() {
Context("FalconAdmission controller test", func() {

const AdmissionControllerName = "test-falconadmissioncontroller"
const AdmissionControllerNamespace = "falcon-kac"
admissionImage := "example.com/image:test"
falconCID := "1234567890ABCDEF1234567890ABCDEF-12"

ctx := context.Background()

namespace := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: AdmissionControllerNamespace,
Namespace: AdmissionControllerNamespace,
},
}

typeNamespaceName := types.NamespacedName{Name: AdmissionControllerName, Namespace: AdmissionControllerNamespace}

BeforeEach(func() {
By("Creating the Namespace to perform the tests")
err := k8sClient.Create(ctx, namespace)
Expect(err).To(Not(HaveOccurred()))
})

AfterEach(func() {
// TODO(user): Attention if you improve this code by adding other context test you MUST
// be aware of the current delete namespace limitations. More info: https://book.kubebuilder.io/reference/envtest.html#testing-considerations
By("Deleting the Namespace to perform the tests")
_ = k8sClient.Delete(ctx, namespace)
})

It("should successfully reconcile a custom resource for FalconAdmission", func() {
By("Creating the custom resource for the Kind FalconAdmission")
falconAdmission := &falconv1alpha1.FalconAdmission{}
err := k8sClient.Get(ctx, typeNamespaceName, falconAdmission)
if err != nil && errors.IsNotFound(err) {
// Let's mock our custom resource at the same way that we would
// apply on the cluster the manifest under config/samples
falconAdmission := &falconv1alpha1.FalconAdmission{
ObjectMeta: metav1.ObjectMeta{
Name: AdmissionControllerName,
Namespace: AdmissionControllerNamespace,
},
Spec: falconv1alpha1.FalconAdmissionSpec{
Falcon: falconv1alpha1.FalconSensor{
CID: &falconCID,
},
InstallNamespace: "falcon-kac",
Image: admissionImage,
Registry: falconv1alpha1.RegistrySpec{
Type: "crowdstrike",
},
AdmissionConfig: falconv1alpha1.FalconAdmissionConfigSpec{
DepUpdateStrategy: falconv1alpha1.FalconAdmissionUpdateStrategy{
RollingUpdate: appsv1.RollingUpdateDeployment{
MaxUnavailable: &intstr.IntOrString{IntVal: 1},
MaxSurge: &intstr.IntOrString{IntVal: 1},
},
},
},
},
}

err = k8sClient.Create(ctx, falconAdmission)
Expect(err).To(Not(HaveOccurred()))
}

By("Checking if the custom resource was successfully created")
Eventually(func() error {
found := &falconv1alpha1.FalconAdmission{}
return k8sClient.Get(ctx, typeNamespaceName, found)
}, time.Minute, time.Second).Should(Succeed())

By("Reconciling the custom resource created")
falconAdmissionReconciler := &FalconAdmissionReconciler{
Client: k8sClient,
Scheme: k8sClient.Scheme(),
}

_, err = falconAdmissionReconciler.Reconcile(ctx, reconcile.Request{
NamespacedName: typeNamespaceName,
})
Expect(err).To(Not(HaveOccurred()))

By("Checking if Service Account was successfully created in the reconciliation")
Eventually(func() error {
found := &corev1.ServiceAccount{}
return k8sClient.Get(ctx, types.NamespacedName{Name: "falcon-operator-admission-controller", Namespace: AdmissionControllerNamespace}, found)
}, time.Minute, time.Second).Should(Succeed())

By("Checking if ResourceQuota was successfully created in the reconciliation")
Eventually(func() error {
found := &corev1.ResourceQuota{}
return k8sClient.Get(ctx, types.NamespacedName{Name: "test-falconadmissioncontroller", Namespace: AdmissionControllerNamespace}, found)
}, time.Minute, time.Second).Should(Succeed())

By("Checking if TLS Secret was successfully created in the reconciliation")
Eventually(func() error {
found := &corev1.Secret{}
return k8sClient.Get(ctx, types.NamespacedName{Name: "test-falconadmissioncontroller-tls", Namespace: AdmissionControllerNamespace}, found)
}, time.Minute, time.Second).Should(Succeed())

By("Checking if ConfigMap was successfully created in the reconciliation")
Eventually(func() error {
found := &corev1.ConfigMap{}
return k8sClient.Get(ctx, types.NamespacedName{Name: "test-falconadmissioncontroller-config", Namespace: AdmissionControllerNamespace}, found)
}, time.Minute, time.Second).Should(Succeed())

By("Checking if Service was successfully created in the reconciliation")
Eventually(func() error {
found := &corev1.Service{}
return k8sClient.Get(ctx, types.NamespacedName{Name: "test-falconadmissioncontroller", Namespace: AdmissionControllerNamespace}, found)
}, time.Minute, time.Second).Should(Succeed())

By("Checking if Deployment was successfully created in the reconciliation")
Eventually(func() error {
found := &appsv1.Deployment{}
return k8sClient.Get(ctx, types.NamespacedName{Name: "test-falconadmissioncontroller", Namespace: AdmissionControllerNamespace}, found)
}, time.Minute, time.Second).Should(Succeed())

By("Checking if pods were successfully created in the reconciliation")
Eventually(func() error {
pod, err := k8sutils.GetReadyPod(k8sClient, ctx, AdmissionControllerNamespace, map[string]string{common.FalconComponentKey: common.FalconAdmissionController})
if err != nil && err.Error() != "No webhook service pod found in a Ready state" {
return err
}
if pod.Name == "" {
_, err = falconAdmissionReconciler.Reconcile(ctx, reconcile.Request{
NamespacedName: typeNamespaceName,
})
}
return err
}, time.Minute, time.Second).Should(Succeed())

By("Checking the latest Status Condition added to the FalconAdmission instance")
Eventually(func() error {
if falconAdmission.Status.Conditions != nil && len(falconAdmission.Status.Conditions) != 0 {
latestStatusCondition := falconAdmission.Status.Conditions[len(falconAdmission.Status.Conditions)-1]
expectedLatestStatusCondition := metav1.Condition{Type: falconv1alpha1.ConditionDeploymentReady,
Status: metav1.ConditionTrue, Reason: falconv1alpha1.ReasonInstallSucceeded,
Message: "FalconAdmission installation completed"}
if latestStatusCondition != expectedLatestStatusCondition {
return fmt.Errorf("The latest status condition added to the FalconAdmission instance is not as expected")
}
}
return nil
}, time.Minute, time.Second).Should(Succeed())
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ var testEnv *envtest.Environment
func TestAPIs(t *testing.T) {
RegisterFailHandler(Fail)

RunSpecs(t, "Controller Suite")
RunSpecs(t, "Admission Controller Controller Suite")
}

var _ = BeforeSuite(func() {
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")},
ErrorIfCRDPathMissing: true,
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ var _ = Describe("FalconContainer controller", func() {
By("Checking if pods were successfully created in the reconciliation")
Eventually(func() error {
pod, err := k8sutils.GetReadyPod(k8sClient, ctx, SidecarSensorNamespace, map[string]string{common.FalconComponentKey: common.FalconSidecarSensor})
if err != nil && err.Error() != "No Injector pod found in a Ready state" {
if err != nil && err.Error() != "No webhook service pod found in a Ready state" {
return err
}
if pod.Name == "" {
Expand Down
1 change: 0 additions & 1 deletion controllers/falcon_container/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ var _ = BeforeSuite(func() {
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")},
ErrorIfCRDPathMissing: true,
WebhookInstallOptions: envtest.WebhookInstallOptions{},
}

var err error
Expand Down
13 changes: 10 additions & 3 deletions deploy/falcon-operator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2702,8 +2702,7 @@ spec:
type: boolean
image:
description: Location of the Falcon Sensor image. Use only in
cases when you mirror the original image to your repository/name:tag,
and CrowdStrike OAuth2 API is not used.
cases when you mirror the original image to your repository/name:tag
pattern: ^.*:.*$
type: string
imagePullPolicy:
Expand Down Expand Up @@ -3695,7 +3694,7 @@ spec:
- linux
containers:
- args:
- --leader-elect
- --config=controller_manager_config.yaml
command:
- /manager
env:
Expand Down Expand Up @@ -3731,8 +3730,16 @@ spec:
drop:
- ALL
privileged: false
volumeMounts:
- mountPath: /controller_manager_config.yaml
name: manager-config
subPath: controller_manager_config.yaml
securityContext:
fsGroup: 65534
runAsNonRoot: true
serviceAccountName: falcon-operator-controller-manager
terminationGracePeriodSeconds: 10
volumes:
- configMap:
name: falcon-operator-manager-config
name: manager-config
22 changes: 20 additions & 2 deletions internal/controller/assets/rbac_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ func TestRole(t *testing.T) {
Namespace: namespace,
Labels: common.CRLabels("role", name, common.FalconAdmissionController),
},
Rules: []rbacv1.PolicyRule{
{
Verbs: []string{"create", "get", "list", "watch", "update"},
APIGroups: []string{""},
Resources: []string{"configmaps"},
},
{
Verbs: []string{"get", "list", "watch", "update"},
APIGroups: []string{""},
Resources: []string{"pods"},
},
{
Verbs: []string{"get", "list", "watch", "create", "update", "delete"},
APIGroups: []string{"coordination.k8s.io"},
Resources: []string{"leases"},
},
},
}
got := Role(name, namespace)
if diff := cmp.Diff(want, got); diff != "" {
Expand All @@ -107,8 +124,9 @@ func TestRoleBinding(t *testing.T) {
Kind: "RoleBinding",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: common.CRLabels("rolebinding", name, component),
Name: name,
Labels: common.CRLabels("rolebinding", name, component),
Namespace: namespace,
},
Subjects: []rbacv1.Subject{
{
Expand Down
Loading
Loading