Skip to content

Commit

Permalink
chore(comments): Write function comments and update license header
Browse files Browse the repository at this point in the history
  • Loading branch information
m8rmclaren committed Dec 14, 2023
1 parent a2f5acb commit 00742cd
Show file tree
Hide file tree
Showing 11 changed files with 44 additions and 19 deletions.
6 changes: 5 additions & 1 deletion internal/controllers/certificaterequest_controller.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 Keyfactor.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -61,6 +61,8 @@ type CertificateRequestReconciler struct {
// +kubebuilder:rbac:groups=cert-manager.io,resources=certificaterequests/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch

// Reconcile attempts to sign a CertificateRequest given the configuration provided and a configured
// EJBCA signer instance.
func (r *CertificateRequestReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
log := ctrl.LoggerFrom(ctx)

Expand Down Expand Up @@ -245,6 +247,8 @@ func (r *CertificateRequestReconciler) Reconcile(ctx context.Context, req ctrl.R
return ctrl.Result{}, nil
}

// SetupWithManager registers the CertificateRequestReconciler with the controller manager.
// It configures controller-runtime to reconcile cert-manager CertificateRequests in the cluster.
func (r *CertificateRequestReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&cmapi.CertificateRequest{}).
Expand Down
2 changes: 1 addition & 1 deletion internal/controllers/certificaterequest_controller_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Keyfactor Command Authors.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
2 changes: 1 addition & 1 deletion internal/controllers/fake_configclient_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Keyfactor Command Authors.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
4 changes: 4 additions & 0 deletions internal/controllers/issuer_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ type IssuerReconciler struct {
//+kubebuilder:rbac:groups=ejbca-issuer.keyfactor.com,resources=issuers/status;clusterissuers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=ejbca-issuer.keyfactor.com,resources=issuers/finalizers,verbs=update

// newIssuer returns a new Issuer or ClusterIssuer object
func (r *IssuerReconciler) newIssuer() (client.Object, error) {
issuerGVK := ejbcaissuer.GroupVersion.WithKind(r.Kind)
ro, err := r.Scheme.New(issuerGVK)
Expand All @@ -69,6 +70,7 @@ func (r *IssuerReconciler) newIssuer() (client.Object, error) {
return ro.(client.Object), nil
}

// Reconcile reconciles and updates the status of an Issuer or ClusterIssuer object
func (r *IssuerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
log := ctrl.LoggerFrom(ctx)

Expand Down Expand Up @@ -167,6 +169,8 @@ func (r *IssuerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (res
return ctrl.Result{RequeueAfter: defaultHealthCheckInterval}, nil
}

// SetupWithManager registers the IssuerReconciler with the controller manager.
// It configures controller-runtime to reconcile Keyfactor EJBCA Issuers/ClusterIssuers in the cluster.
func (r *IssuerReconciler) SetupWithManager(mgr ctrl.Manager) error {
issuerType, err := r.newIssuer()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/controllers/issuer_controller_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Keyfactor Command Authors.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
10 changes: 10 additions & 0 deletions internal/issuer/signer/signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ type Signer interface {
Sign(context.Context, []byte) ([]byte, []byte, error)
}

// EjbcaHealthCheckerFromIssuerAndSecretData creates a HealthChecker from an IssuerSpec and a map of secret data
func EjbcaHealthCheckerFromIssuerAndSecretData(ctx context.Context, spec *ejbcaissuer.IssuerSpec, clientCertSecretData map[string][]byte, caCertSecretData map[string][]byte) (HealthChecker, error) {
signer := ejbcaSigner{}

Expand All @@ -65,6 +66,7 @@ func EjbcaHealthCheckerFromIssuerAndSecretData(ctx context.Context, spec *ejbcai
return &signer, nil
}

// ejbcaSignerFromIssuerAndSecretData creates a Signer from an IssuerSpec and a map of secret data
func ejbcaSignerFromIssuerAndSecretData(ctx context.Context, spec *ejbcaissuer.IssuerSpec, annotations map[string]string, clientCertSecretData map[string][]byte, caCertSecretData map[string][]byte) (*ejbcaSigner, error) {
signLog := log.FromContext(ctx)
signer := ejbcaSigner{}
Expand Down Expand Up @@ -116,10 +118,12 @@ func ejbcaSignerFromIssuerAndSecretData(ctx context.Context, spec *ejbcaissuer.I
return &signer, nil
}

// EjbcaSignerFromIssuerAndSecretData is a wrapper around ejbcaSignerFromIssuerAndSecretData that returns a Signer interface
func EjbcaSignerFromIssuerAndSecretData(ctx context.Context, spec *ejbcaissuer.IssuerSpec, annotations map[string]string, clientCertSecretData map[string][]byte, caCertSecretData map[string][]byte) (Signer, error) {
return ejbcaSignerFromIssuerAndSecretData(ctx, spec, annotations, clientCertSecretData, caCertSecretData)
}

// Check checks the status of the EJBCA API
func (s *ejbcaSigner) Check() error {
// Check EJBCA API status
_, _, err := s.client.V1CertificateApi.Status2(context.Background()).Execute()
Expand All @@ -130,6 +134,7 @@ func (s *ejbcaSigner) Check() error {
return nil
}

// getEndEntityName determines the end entity name to use for the EJBCA request
func (s *ejbcaSigner) getEndEntityName(ctx context.Context, csr *x509.CertificateRequest) string {
eeLog := log.FromContext(ctx)
eeName := ""
Expand Down Expand Up @@ -192,6 +197,7 @@ func (s *ejbcaSigner) getEndEntityName(ctx context.Context, csr *x509.Certificat
return eeName
}

// Sign signs a CSR with EJBCA
func (s *ejbcaSigner) Sign(ctx context.Context, csrBytes []byte) ([]byte, []byte, error) {
k8sLog := log.FromContext(ctx)

Expand Down Expand Up @@ -252,6 +258,7 @@ func (s *ejbcaSigner) Sign(ctx context.Context, csrBytes []byte) ([]byte, []byte
return compileCertificatesToPemBytes(certAndChain)
}

// createClientFromSecretMap creates an EJBCA API client from a map of secret data
func createClientFromSecretMap(ctx context.Context, hostname string, clientCertSecretData map[string][]byte, caCertSecretData map[string][]byte) (*ejbca.APIClient, error) {
var err error
k8sLog := log.FromContext(ctx)
Expand Down Expand Up @@ -452,6 +459,7 @@ func compileCertificatesToPemBytes(certificates []*x509.Certificate) ([]byte, []
return []byte(leaf.String()), []byte(chain.String()), nil
}

// decodePEMBytes takes a byte array containing PEM encoded data and returns a slice of PEM blocks and a private key PEM block
func decodePEMBytes(buf []byte) ([]*pem.Block, *pem.Block) {
var privKey *pem.Block
var certificates []*pem.Block
Expand All @@ -469,10 +477,12 @@ func decodePEMBytes(buf []byte) ([]*pem.Block, *pem.Block) {
return certificates, privKey
}

// ptr is a helper function that returns a pointer to the provided value
func ptr[T any](v T) *T {
return &v
}

// generateRandomString generates a random string of length n
func generateRandomString(length int) string {
rand.Seed(time.Now().UnixNano())
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
Expand Down
2 changes: 1 addition & 1 deletion internal/issuer/signer/signer_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Keyfactor Command Authors.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
14 changes: 13 additions & 1 deletion internal/issuer/util/configclient.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Keyfactor Command Authors.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -28,6 +28,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
)

// ConfigClient is an interface for a K8s REST client.
type ConfigClient interface {
SetContext(ctx context.Context)
GetConfigMap(name types.NamespacedName, out *corev1.ConfigMap) error
Expand All @@ -43,6 +44,7 @@ type configClient struct {
verifyAccessFunc func(apiResource string, resource types.NamespacedName) error
}

// NewConfigClient creates a new K8s REST client using the configuration from the controller-runtime.
func NewConfigClient(ctx context.Context) (ConfigClient, error) {
config := ctrl.GetConfigOrDie()

Expand All @@ -64,11 +66,15 @@ func NewConfigClient(ctx context.Context) (ConfigClient, error) {
return client, nil
}

// SetContext sets the context for the client.
func (c *configClient) SetContext(ctx context.Context) {
c.ctx = ctx
c.logger = klog.FromContext(ctx)
}

// verifyAccessToResource verifies that the client has access to a given resource in a given namespace
// by creating a SelfSubjectAccessReview. This is done to avoid errors when the client does not have
// access to the resource.
func (c *configClient) verifyAccessToResource(apiResource string, resource types.NamespacedName) error {
verbs := []string{"get", "list", "watch"}

Expand Down Expand Up @@ -101,13 +107,16 @@ func (c *configClient) verifyAccessToResource(apiResource string, resource types
return nil
}

// GetConfigMap gets the configmap with the given name and namespace and copies it into the out parameter.
func (c *configClient) GetConfigMap(name types.NamespacedName, out *corev1.ConfigMap) error {
if c == nil {
return fmt.Errorf("config client is nil")
}

// Check if the client has access to the configmap resource
if _, ok := c.accessCache[name.String()]; !ok {
// If this is the first time the client is accessing the resource and it does have
// permission, add it to the access cache so that it does not need to be checked again.
err := c.verifyAccessFunc("configmaps", name)
if err != nil {
return err
Expand All @@ -126,13 +135,16 @@ func (c *configClient) GetConfigMap(name types.NamespacedName, out *corev1.Confi
return nil
}

// GetSecret gets the secret with the given name and namespace and copies it into the out parameter.
func (c *configClient) GetSecret(name types.NamespacedName, out *corev1.Secret) error {
if c == nil {
return fmt.Errorf("config client is nil")
}

// Check if the client has access to the secret resource
if _, ok := c.accessCache[name.String()]; !ok {
// If this is the first time the client is accessing the resource and it does have
// permission, add it to the access cache so that it does not need to be checked again.
err := c.verifyAccessFunc("secrets", name)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion internal/issuer/util/configclient_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Keyfactor Command Authors.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
17 changes: 6 additions & 11 deletions internal/issuer/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,7 @@ import (
ejbcaissuer "github.com/Keyfactor/ejbca-issuer/api/v1alpha1"
)

func GetCertificateRequestAnnotations(issuer client.Object) (map[string]string, error) {
switch t := issuer.(type) {
case *ejbcaissuer.Issuer:
return t.GetAnnotations(), nil
case *ejbcaissuer.ClusterIssuer:
return t.GetAnnotations(), nil
default:
return nil, fmt.Errorf("not an issuer type: %t", t)
}
}

// GetName is a helper function that returns the name of an Issuer object.
func GetName(issuer client.Object) (string, error) {
switch t := issuer.(type) {
case *ejbcaissuer.Issuer:
Expand All @@ -52,6 +42,7 @@ func GetName(issuer client.Object) (string, error) {
}
}

// GetSpecAndStatus is a helper function that returns the Spec and Status of an Issuer object.
func GetSpecAndStatus(issuer client.Object) (*ejbcaissuer.IssuerSpec, *ejbcaissuer.IssuerStatus, error) {
switch t := issuer.(type) {
case *ejbcaissuer.Issuer:
Expand All @@ -63,6 +54,7 @@ func GetSpecAndStatus(issuer client.Object) (*ejbcaissuer.IssuerSpec, *ejbcaissu
}
}

// SetCertificateRequestReadyCondition is a helper function that sets the Ready condition on an IssuerStatus.
func SetCertificateRequestReadyCondition(ctx context.Context, csr *cmapi.CertificateRequest, status cmmeta.ConditionStatus, reason, message string) {
log := ctrl.LoggerFrom(ctx)

Expand All @@ -79,6 +71,7 @@ func SetCertificateRequestReadyCondition(ctx context.Context, csr *cmapi.Certifi
)
}

// SetIssuerReadyCondition is a helper function that sets the Ready condition on an IssuerStatus.
func SetIssuerReadyCondition(ctx context.Context, name, kind string, status *ejbcaissuer.IssuerStatus, conditionStatus ejbcaissuer.ConditionStatus, reason, message string) {
log := ctrl.LoggerFrom(ctx)

Expand Down Expand Up @@ -107,6 +100,7 @@ func SetIssuerReadyCondition(ctx context.Context, name, kind string, status *ejb
}
}

// GetReadyCondition is a helper function that returns the Ready condition from an IssuerStatus.
func GetReadyCondition(status *ejbcaissuer.IssuerStatus) *ejbcaissuer.IssuerCondition {
for _, c := range status.Conditions {
if c.Type == ejbcaissuer.IssuerConditionReady {
Expand All @@ -116,6 +110,7 @@ func GetReadyCondition(status *ejbcaissuer.IssuerStatus) *ejbcaissuer.IssuerCond
return nil
}

// IsReady is a helper function that returns true if the Ready condition is set to True.
func IsReady(status *ejbcaissuer.IssuerStatus) bool {
if c := GetReadyCondition(status); c != nil {
return c.Status == ejbcaissuer.ConditionTrue
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 Keyfactor.
Copyright © 2023 Keyfactor
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down

0 comments on commit 00742cd

Please sign in to comment.