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

[release-2.6] Update to Go v1.20 #224

Merged
merged 1 commit into from
Aug 2, 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
2 changes: 1 addition & 1 deletion .ci-operator.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
build_root_image:
name: builder
namespace: stolostron
tag: go1.19-linux
tag: go1.20-linux
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Copyright Contributors to the Open Cluster Management project

# Stage 1: Use image builder to build the target binaries
FROM registry.ci.openshift.org/stolostron/builder:go1.19-linux AS builder
FROM registry.ci.openshift.org/stolostron/builder:go1.20-linux AS builder

ENV COMPONENT=cert-policy-controller
ENV REPO_PATH=/go/src/github.com/stolostron/${COMPONENT}
Expand Down
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ create-ns:
# Lint code
.PHONY: lint-dependencies
lint-dependencies:
$(call go-get-tool,github.com/golangci/golangci-lint/cmd/golangci-lint@v1.46.2)
$(call go-get-tool,github.com/golangci/golangci-lint/cmd/golangci-lint@v1.52.2)

.PHONY: lint
lint: lint-dependencies lint-all
Expand Down Expand Up @@ -205,7 +205,7 @@ kubebuilder-dependencies: $(LOCAL_BIN)

.PHONY: gosec
gosec:
$(call go-get-tool,github.com/securego/gosec/v2/cmd/gosec@v2.9.6)
$(call go-get-tool,github.com/securego/gosec/v2/cmd/gosec@v2.15.0)

.PHONY: gosec-scan
gosec-scan: gosec
Expand Down
8 changes: 4 additions & 4 deletions api/v1/certificatepolicy_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,21 +88,21 @@ type CertificatePolicySpec struct {
MinDuration *metav1.Duration `json:"minimumDuration,omitempty"`
// Minimum CA duration before a signing certificate expires that it is considered non-compliant.
// Golang's time units only.
MinCADuration *metav1.Duration `json:"minimumCADuration,omitempty"` // nolint:tagliatelle
MinCADuration *metav1.Duration `json:"minimumCADuration,omitempty"` //nolint:tagliatelle
// Maximum duration for a certificate, longer duration is considered non-compliant.
// Golang's time units only.
MaxDuration *metav1.Duration `json:"maximumDuration,omitempty"`
// Maximum CA duration for a signing certificate, longer duration is considered non-compliant.
// Golang's time units only.
MaxCADuration *metav1.Duration `json:"maximumCADuration,omitempty"` // nolint:tagliatelle
MaxCADuration *metav1.Duration `json:"maximumCADuration,omitempty"` //nolint:tagliatelle
// A pattern that must match any defined SAN entries in the certificate for the certificate to be compliant.
// Golang's regexp syntax only.
// +kubebuilder:validation:MinLength=1
AllowedSANPattern string `json:"allowedSANPattern,omitempty"` // nolint:tagliatelle
AllowedSANPattern string `json:"allowedSANPattern,omitempty"` //nolint:tagliatelle
// A pattern that must not match any defined SAN entries in the certificate for the certificate to be compliant.
// Golang's regexp syntax only.
// +kubebuilder:validation:MinLength=1
DisallowedSANPattern string `json:"disallowedSANPattern,omitempty"` // nolint:tagliatelle
DisallowedSANPattern string `json:"disallowedSANPattern,omitempty"` //nolint:tagliatelle
}

// CertificatePolicyStatus defines the observed state of CertificatePolicy
Expand Down
40 changes: 24 additions & 16 deletions controllers/certificatepolicy_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ var (
var log = ctrl.Log.WithName(ControllerName)

// Initialize to initialize some controller variables.
func Initialize(kClient *kubernetes.Interface, mgr manager.Manager, namespace, eventParent string,
func Initialize(kClient *kubernetes.Interface, _ manager.Manager, namespace, eventParent string,
defaultDuration time.Duration,
) (err error) {
KubeClient = kClient
Expand Down Expand Up @@ -138,7 +138,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.

instance.Status.CompliancyDetails = make(map[string]policyv1.CompliancyDetails)

handleAddingPolicy(instance)
handleAddingPolicy(ctx, instance)
}

reqLogger.V(1).Info("Successful processing", "instance.Name", instance.Name, "instance.Namespace",
Expand Down Expand Up @@ -174,7 +174,9 @@ func ensureDefaultLabel(instance *policyv1.CertificatePolicy) bool {
}

// PeriodicallyExecCertificatePolicies always check status - let this be the only function in the controller.
func PeriodicallyExecCertificatePolicies(freq uint, loopflag bool) {
func PeriodicallyExecCertificatePolicies(
ctx context.Context, freq uint, loopflag bool,
) {
log.V(3).Info("Entered PeriodicallyExecCertificatePolicies")
var plcToUpdateMap map[string]*policyv1.CertificatePolicy

Expand All @@ -185,11 +187,11 @@ func PeriodicallyExecCertificatePolicies(freq uint, loopflag bool) {

plcToUpdateMap = make(map[string]*policyv1.CertificatePolicy)

stateChange := ProcessPolicies(plcToUpdateMap)
stateChange := ProcessPolicies(ctx, plcToUpdateMap)

if stateChange {
// update status of all policies that changed:
faultyPlc, err := updatePolicyStatus(plcToUpdateMap)
faultyPlc, err := updatePolicyStatus(ctx, plcToUpdateMap)
if err != nil {
log.Error(err, "Unable to update policy status", "Name", faultyPlc.Name, "Namespace",
faultyPlc.Namespace)
Expand All @@ -212,7 +214,9 @@ func PeriodicallyExecCertificatePolicies(freq uint, loopflag bool) {
}

// ProcessPolicies reads each policy and looks for violations returning true if a change is found.
func ProcessPolicies(plcToUpdateMap map[string]*policyv1.CertificatePolicy) bool {
func ProcessPolicies(
ctx context.Context, plcToUpdateMap map[string]*policyv1.CertificatePolicy,
) bool {
stateChange := false

plcMap := make(map[string]*policyv1.CertificatePolicy)
Expand All @@ -223,7 +227,7 @@ func ProcessPolicies(plcToUpdateMap map[string]*policyv1.CertificatePolicy) bool
// update available policies if there are changed namespaces
for _, plc := range plcMap {
// Retrieve the namespaces based on filters in NamespaceSelector
selectedNamespaces := retrieveNamespaces(plc.Spec.NamespaceSelector)
selectedNamespaces := retrieveNamespaces(ctx, plc.Spec.NamespaceSelector)

// add availablePolicy if not present
for _, ns := range selectedNamespaces {
Expand Down Expand Up @@ -262,7 +266,7 @@ func ProcessPolicies(plcToUpdateMap map[string]*policyv1.CertificatePolicy) bool

log.V(2).Info("Checking certificates", "namespace", namespace, "policy.Name", policy.Name)

update, nonCompliant, list := checkSecrets(policy, namespace)
update, nonCompliant, list := checkSecrets(ctx, policy, namespace)

if strings.EqualFold(string(policy.Spec.RemediationAction), string(policyv1.Enforce)) {
log.V(1).Info("Enforce is set, but not implemented on this controller")
Expand Down Expand Up @@ -338,7 +342,9 @@ func toLabelSet(v map[string]policyv1.NonEmptyString) labels.Set {
// Checks each namespace for certificates that are going to expire within 3 months
// Returns whether a state change is happening, the number of uncompliant certificates
// and a list of the uncompliant certificates.
func checkSecrets(policy *policyv1.CertificatePolicy, namespace string) (bool, uint, map[string]policyv1.Cert) {
func checkSecrets(
ctx context.Context, policy *policyv1.CertificatePolicy, namespace string,
) (bool, uint, map[string]policyv1.Cert) {
slog := log.WithValues("policy.Namespace", policy.Namespace, "policy.Name", policy.Name)
slog.V(3).Info("Entered checkSecrets")

Expand All @@ -351,7 +357,7 @@ func checkSecrets(policy *policyv1.CertificatePolicy, namespace string) (bool, u
// GOAL: Want the label selector to find secrets with certificates only!! -> is-certificate
// Loops through all the secrets within the CertificatePolicy's specified namespace
labelSelector := toLabelSet(policy.Spec.LabelSelector)
secretList, _ := (common.KubeClient).CoreV1().Secrets(namespace).List(context.TODO(),
secretList, _ := (common.KubeClient).CoreV1().Secrets(namespace).List(ctx,
metav1.ListOptions{LabelSelector: labelSelector.String()})

for _, secretItem := range secretList.Items {
Expand Down Expand Up @@ -380,14 +386,14 @@ func checkSecrets(policy *policyv1.CertificatePolicy, namespace string) (bool, u
return update, uint(len(nonCompliantCertificates)), nonCompliantCertificates
}

func retrieveNamespaces(selector policyv1.Target) []string {
func retrieveNamespaces(ctx context.Context, selector policyv1.Target) []string {
var selectedNamespaces []string
// If MatchLabels/MatchExpressions/Include were not provided, return no namespaces
if selector.MatchLabels == nil && selector.MatchExpressions == nil && len(selector.Include) == 0 {
log.Info("NamespaceSelector is empty. Skipping namespace retrieval.")
} else {
var err error
selectedNamespaces, err = common.GetSelectedNamespaces(selector)
selectedNamespaces, err = common.GetSelectedNamespaces(ctx, selector)
if err != nil {
log.Error(
err, "Error filtering namespaces with provided NamespaceSelector",
Expand Down Expand Up @@ -744,7 +750,9 @@ func checkComplianceChangeBasedOnDetails(plc *policyv1.CertificatePolicy) (compl
return reflect.DeepEqual(previous, plc.Status.ComplianceState)
}

func updatePolicyStatus(policies map[string]*policyv1.CertificatePolicy) (*policyv1.CertificatePolicy, error) {
func updatePolicyStatus(
ctx context.Context, policies map[string]*policyv1.CertificatePolicy,
) (*policyv1.CertificatePolicy, error) {
log.V(3).Info("Entered updatePolicyStatus")

for _, instance := range policies { // policies is a map where: key = plc.Name, value = pointer to plc
Expand All @@ -767,7 +775,7 @@ func updatePolicyStatus(policies map[string]*policyv1.CertificatePolicy) (*polic
}
}

err := reconcilingAgent.Status().Update(context.TODO(), instance)
err := reconcilingAgent.Status().Update(ctx, instance)
if err != nil {
return instance, err
}
Expand Down Expand Up @@ -798,7 +806,7 @@ func handleRemovingPolicy(name string) {
}
}

func handleAddingPolicy(plc *policyv1.CertificatePolicy) {
func handleAddingPolicy(ctx context.Context, plc *policyv1.CertificatePolicy) {
log.V(3).Info("Entered handleAddingPolicy")

// clean up that policy from the availablePolicies list, in case the modification is in the
Expand All @@ -814,7 +822,7 @@ func handleAddingPolicy(plc *policyv1.CertificatePolicy) {
addFlag := false

// Retrieve the namespaces based on filters in NamespaceSelector
selectedNamespaces := retrieveNamespaces(plc.Spec.NamespaceSelector)
selectedNamespaces := retrieveNamespaces(ctx, plc.Spec.NamespaceSelector)

for _, ns := range selectedNamespaces {
key := fmt.Sprintf("%s/%s", ns, plc.Name)
Expand Down
26 changes: 13 additions & 13 deletions controllers/certificatepolicy_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ func TestPeriodicallyExecCertificatePolicies(t *testing.T) {
certPolicy.Name = fmt.Sprintf("%s-%d", certPolicy.Name, i)
certPolicy.Spec.NamespaceSelector.Include = []policiesv1.NonEmptyString{test.namespaceSelector}

handleAddingPolicy(certPolicy)
PeriodicallyExecCertificatePolicies(1, false)
handleAddingPolicy(context.TODO(), certPolicy)
PeriodicallyExecCertificatePolicies(context.TODO(), 1, false)

policy, found := availablePolicies.GetObject(test.cacheNamespace + "/" + certPolicy.Name)
assert.True(t, found)
Expand All @@ -197,7 +197,7 @@ func TestPeriodicallyExecCertificatePolicies(t *testing.T) {
}
}

func TestCheckComplianceBasedOnDetails(t *testing.T) {
func TestCheckComplianceBasedOnDetails(_ *testing.T) {
var simpleClient kubernetes.Interface = testclient.NewSimpleClientset()

common.Initialize(simpleClient, nil)
Expand Down Expand Up @@ -302,14 +302,14 @@ func TestHandleAddingPolicy(t *testing.T) {
}
certPolicy.Spec.NamespaceSelector.Include = []policiesv1.NonEmptyString{"default"}

handleAddingPolicy(certPolicy)
handleAddingPolicy(context.TODO(), certPolicy)
policy, found := availablePolicies.GetObject(certPolicy.Namespace + "/" + certPolicy.Name)
assert.True(t, found)
assert.NotNil(t, policy)
handleRemovingPolicy(certPolicy.Name)
}

func TestPrintMap(t *testing.T) {
func TestPrintMap(_ *testing.T) {
certPolicy := policiesv1.CertificatePolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Expand Down Expand Up @@ -494,10 +494,10 @@ func TestProcessPolicies(t *testing.T) {
MinDuration: &metav1.Duration{Duration: time.Hour * 24 * 35},
},
}
handleAddingPolicy(instance)
handleAddingPolicy(context.TODO(), instance)

plcToUpdateMap := make(map[string]*policiesv1.CertificatePolicy)
value := ProcessPolicies(plcToUpdateMap)
value := ProcessPolicies(context.TODO(), plcToUpdateMap)
assert.True(t, value)

_, found := availablePolicies.GetObject("/" + instance.Name)
Expand Down Expand Up @@ -587,7 +587,7 @@ uFPO5+jBaPT3/G0z1dDrZZDOxhTSkFuyLTXnaEhIbZQW0Mniq1m5nswOAgfompmA
target := []policiesv1.NonEmptyString{"default"}
instance.Spec.NamespaceSelector.Include = target

handleAddingPolicy(instance)
handleAddingPolicy(context.TODO(), instance)

policy, found := availablePolicies.GetObject(instance.Namespace + "/" + instance.Name)
assert.True(t, found)
Expand All @@ -605,7 +605,7 @@ uFPO5+jBaPT3/G0z1dDrZZDOxhTSkFuyLTXnaEhIbZQW0Mniq1m5nswOAgfompmA
assert.Nil(t, err)
assert.NotNil(t, cert)

update, nonCompliant, list := checkSecrets(instance, "default")
update, nonCompliant, list := checkSecrets(context.TODO(), instance, "default")

assert.Nil(t, err)
assert.Equal(t, uint(1), nonCompliant)
Expand Down Expand Up @@ -664,7 +664,7 @@ xUSmOkQ0VchHrQY4a3z4yzgWIdDe34DhonLA1njXcd66kzY5cD1EykmLcIPFLqCx

target = []policiesv1.NonEmptyString{"default"}
instance.Spec.NamespaceSelector.Include = target
handleAddingPolicy(instance)
handleAddingPolicy(context.TODO(), instance)

policy, found = availablePolicies.GetObject(instance.Namespace + "/" + instance.Name)
assert.True(t, found)
Expand All @@ -678,7 +678,7 @@ xUSmOkQ0VchHrQY4a3z4yzgWIdDe34DhonLA1njXcd66kzY5cD1EykmLcIPFLqCx
)
assert.Equal(t, 2, len(secretList.Items))

update, nonCompliant, list = checkSecrets(instance, "default")
update, nonCompliant, list = checkSecrets(context.TODO(), instance, "default")

assert.Nil(t, err)
assert.Equal(t, uint(2), nonCompliant)
Expand Down Expand Up @@ -799,15 +799,15 @@ uFPO5+jBaPT3/G0z1dDrZZDOxhTSkFuyLTXnaEhIbZQW0Mniq1m5nswOAgfompmA
target := []policiesv1.NonEmptyString{"def*"}
instance.Spec.NamespaceSelector.Include = target

handleAddingPolicy(instance)
handleAddingPolicy(context.TODO(), instance)

policy, found := availablePolicies.GetObject(instance.Namespace + "/" + instance.Name)
assert.True(t, found)
assert.NotNil(t, policy)

plcToUpdateMap := make(map[string]*policiesv1.CertificatePolicy)

stateChange := ProcessPolicies(plcToUpdateMap)
stateChange := ProcessPolicies(context.TODO(), plcToUpdateMap)
assert.True(t, stateChange)

message := convertPolicyStatusToString(instance, DefaultDuration)
Expand Down
2 changes: 1 addition & 1 deletion controllers/certificatepolicy_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func convertPolicyStatusToString(plc *policyv1.CertificatePolicy, defaultDuratio
}

// Message format:
// NonCompliant; x certificates expire in less than 300h: namespace:secretname, namespace:secretname, ...
// NonCompliant; x certificates expire in less than 300h: namespace:secretname1, namespace:secretname2, ...
expireCount := 0
expireCACount := 0
durationCount := 0
Expand Down
2 changes: 1 addition & 1 deletion controllers/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ limitations under the License.

package controllers

// nolint:gci
//nolint:gci
import (
"path/filepath"
"testing"
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module open-cluster-management.io/cert-policy-controller

go 1.19
go 1.20

require (
github.com/go-logr/zapr v1.2.3
Expand Down
6 changes: 3 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

package main

// nolint:gci
//nolint:gci
import (
"context"
"errors"
Expand Down Expand Up @@ -56,7 +56,7 @@ func printVersion() {
"GOOS", runtime.GOOS, "GOARCH", runtime.GOARCH)
}

// nolint:wsl
//nolint:wsl
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(extpolicyv1.AddToScheme(scheme))
Expand Down Expand Up @@ -262,7 +262,7 @@ func main() {
_ = controllers.Initialize(&generatedClient, mgr, namespace, eventOnParent, time.Duration(0)) /* #nosec G104 */
// PeriodicallyExecCertificatePolicies is the go-routine that periodically checks the policies and
// does the needed work to make sure the desired state is achieved
go controllers.PeriodicallyExecCertificatePolicies(frequency, true)
go controllers.PeriodicallyExecCertificatePolicies(context.TODO(), frequency, true)

if enableLease {
startLeaseController(generatedClient, hubConfigPath, clusterName)
Expand Down
8 changes: 4 additions & 4 deletions pkg/common/namespace_selection.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
var log = ctrl.Log

// GetSelectedNamespaces returns the list of filtered namespaces according to the policy namespace selector.
func GetSelectedNamespaces(selector policyv1.Target) ([]string, error) {
func GetSelectedNamespaces(ctx context.Context, selector policyv1.Target) ([]string, error) {
// Build LabelSelector from provided MatchLabels and MatchExpressions
var labelSelector metav1.LabelSelector
// Handle when MatchLabels/MatchExpressions were not provided to prevent nil pointer dereference.
Expand All @@ -43,7 +43,7 @@ func GetSelectedNamespaces(selector policyv1.Target) ([]string, error) {
}

// get all namespaces matching selector
allNamespaces, err := GetAllNamespaces(labelSelector)
allNamespaces, err := GetAllNamespaces(ctx, labelSelector)
if err != nil {
log.Error(err, "error retrieving namespaces")

Expand All @@ -70,7 +70,7 @@ func GetSelectedNamespaces(selector policyv1.Target) ([]string, error) {
}

// GetAllNamespaces gets the list of all namespaces from k8s.
func GetAllNamespaces(labelSelector metav1.LabelSelector) ([]string, error) {
func GetAllNamespaces(ctx context.Context, labelSelector metav1.LabelSelector) ([]string, error) {
parsedSelector, err := metav1.LabelSelectorAsSelector(&labelSelector)
if err != nil {
return nil, fmt.Errorf("error parsing namespace LabelSelector: %w", err)
Expand All @@ -82,7 +82,7 @@ func GetAllNamespaces(labelSelector metav1.LabelSelector) ([]string, error) {

log.V(2).Info("Retrieving namespaces with LabelSelector", "LabelSelector", parsedSelector.String())

nsList, err := (KubeClient).CoreV1().Namespaces().List(context.TODO(), listOpt)
nsList, err := (KubeClient).CoreV1().Namespaces().List(ctx, listOpt)
if err != nil {
log.Error(err, "could not list namespaces from the API server")

Expand Down
Loading