Skip to content

refactor: support direct rule evaluation #225

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

Merged
merged 3 commits into from
Aug 6, 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
16 changes: 16 additions & 0 deletions api/v1alpha1/azurevalidator_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package v1alpha1

import (
"github.com/validator-labs/validator-plugin-azure/pkg/constants"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

Expand All @@ -33,6 +34,11 @@ type AzureValidatorSpec struct {
Auth AzureAuth `json:"auth" yaml:"auth"`
}

// PluginCode returns the Azure validator's plugin code.
func (s AzureValidatorSpec) PluginCode() string {
return constants.PluginCode
}

// ResultCount returns the number of validation results expected for an AzureValidatorSpec.
func (s AzureValidatorSpec) ResultCount() int {
return len(s.RBACRules) + len(s.CommunityGalleryImageRules)
Expand Down Expand Up @@ -139,6 +145,16 @@ type AzureValidator struct {
Status AzureValidatorStatus `json:"status,omitempty"`
}

// PluginCode returns the Azure validator's plugin code.
func (v AzureValidator) PluginCode() string {
return v.Spec.PluginCode()
}

// ResultCount returns the number of validation results expected for an AzureValidator.
func (v AzureValidator) ResultCount() int {
return v.Spec.ResultCount()
}

//+kubebuilder:object:root=true

// AzureValidatorList contains a list of AzureValidator
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ require (
github.com/go-logr/logr v1.4.2
github.com/onsi/ginkgo/v2 v2.19.1
github.com/onsi/gomega v1.34.1
github.com/validator-labs/validator v0.1.0
github.com/validator-labs/validator v0.1.1
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
k8s.io/api v0.30.3
k8s.io/apimachinery v0.30.3
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/validator-labs/validator v0.1.0 h1:GVekIT5sG+kcyUbT04qb/pURmd9eE6NNKnSR9yJ1sQk=
github.com/validator-labs/validator v0.1.0/go.mod h1:OeJMHGKW3pWGkvKxHLN7HzjelSILJg2k8w3Z9SdML1g=
github.com/validator-labs/validator v0.1.1 h1:BzUWeSAP5eGHX2oOulJWZxXr+Zz6Uh6ZqP5sYudnv3I=
github.com/validator-labs/validator v0.1.1/go.mod h1:to8CMM+LlTcEzbqxVyHND9/uJO2+ORTFk9ovqVOnCU8=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
Expand Down
85 changes: 7 additions & 78 deletions internal/controller/azurevalidator_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,21 @@ package controller
import (
"context"
"errors"
"fmt"
"os"
"time"

"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ktypes "k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/cluster-api/util/patch"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/validator-labs/validator-plugin-azure/api/v1alpha1"
"github.com/validator-labs/validator-plugin-azure/internal/constants"
azure_utils "github.com/validator-labs/validator-plugin-azure/internal/utils/azure"
"github.com/validator-labs/validator-plugin-azure/internal/validators"
"github.com/validator-labs/validator-plugin-azure/pkg/validate"
vapi "github.com/validator-labs/validator/api/v1alpha1"
"github.com/validator-labs/validator/pkg/types"
"github.com/validator-labs/validator/pkg/util"
vres "github.com/validator-labs/validator/pkg/validationresult"
)

Expand Down Expand Up @@ -91,16 +85,16 @@ func (r *AzureValidatorReconciler) Reconcile(ctx context.Context, req ctrl.Reque
return ctrl.Result{}, err
}
nn := ktypes.NamespacedName{
Name: validationResultName(validator),
Name: vres.Name(validator),
Namespace: req.Namespace,
}
if err := r.Get(ctx, nn, vr); err == nil {
vres.HandleExistingValidationResult(vr, r.Log)
vres.HandleExisting(vr, r.Log)
} else {
if !apierrs.IsNotFound(err) {
l.Error(err, "unexpected error getting ValidationResult")
}
if err := vres.HandleNewValidationResult(ctx, r.Client, p, buildValidationResult(validator), r.Log); err != nil {
if err := vres.HandleNew(ctx, r.Client, p, vres.Build(validator), r.Log); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: time.Millisecond}, nil
Expand All @@ -109,50 +103,11 @@ func (r *AzureValidatorReconciler) Reconcile(ctx context.Context, req ctrl.Reque
// Always update the expected result count in case the validator's rules have changed
vr.Spec.ExpectedResults = validator.Spec.ResultCount()

resp := types.ValidationResponse{
ValidationRuleResults: make([]*types.ValidationRuleResult, 0, vr.Spec.ExpectedResults),
ValidationRuleErrors: make([]error, 0, vr.Spec.ExpectedResults),
}

azureAPI, err := azure_utils.NewAzureAPI()
if err != nil {
l.Error(err, "failed to create Azure API object")
} else {
azureCtx := context.WithoutCancel(ctx)
if os.Getenv("IS_TEST") == "true" {
var cancel context.CancelFunc
azureCtx, cancel = context.WithDeadline(ctx, time.Now().Add(azure_utils.TestClientTimeout))
defer cancel()
}

daClient := azure_utils.NewDenyAssignmentsClient(azureCtx, azureAPI.DenyAssignmentsClient)
raClient := azure_utils.NewRoleAssignmentsClient(azureCtx, azureAPI.RoleAssignmentsClient)
rdClient := azure_utils.NewRoleDefinitionsClient(azureCtx, azureAPI.RoleDefinitionsClient)
cgiClient := azure_utils.NewCommunityGalleryImagesClient(azureCtx, azureAPI.CommunityGalleryImagesClientProducer)

// RBAC rules
rbacSvc := validators.NewRBACRuleService(daClient, raClient, rdClient)
for _, rule := range validator.Spec.RBACRules {
vrr, err := rbacSvc.ReconcileRBACRule(rule)
if err != nil {
l.Error(err, "failed to reconcile RBAC rule")
}
resp.AddResult(vrr, err)
}

// Community gallery image rules
cgiSvc := validators.NewCommunityGalleryImageRuleService(cgiClient, r.Log)
for _, rule := range validator.Spec.CommunityGalleryImageRules {
vrr, err := cgiSvc.ReconcileCommunityGalleryImageRule(rule)
if err != nil {
l.Error(err, "failed to reconcile community gallery image rule")
}
resp.AddResult(vrr, err)
}
}
// Validate the rules
resp := validate.Validate(validator.Spec, r.Log)

// Patch the ValidationResult with the latest ValidationRuleResults
if err := vres.SafeUpdateValidationResult(ctx, p, vr, resp, r.Log); err != nil {
if err := vres.SafeUpdate(ctx, p, vr, resp, r.Log); err != nil {
return ctrl.Result{}, err
}

Expand Down Expand Up @@ -185,29 +140,3 @@ func (r *AzureValidatorReconciler) SetupWithManager(mgr ctrl.Manager) error {
For(&v1alpha1.AzureValidator{}).
Complete(r)
}

func buildValidationResult(validator *v1alpha1.AzureValidator) *vapi.ValidationResult {
return &vapi.ValidationResult{
ObjectMeta: metav1.ObjectMeta{
Name: validationResultName(validator),
Namespace: validator.Namespace,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: validator.APIVersion,
Kind: validator.Kind,
Name: validator.Name,
UID: validator.UID,
Controller: util.Ptr(true),
},
},
},
Spec: vapi.ValidationResultSpec{
Plugin: constants.PluginCode,
ExpectedResults: validator.Spec.ResultCount(),
},
}
}

func validationResultName(validator *v1alpha1.AzureValidator) string {
return fmt.Sprintf("validator-plugin-azure-%s", validator.Name)
}
3 changes: 2 additions & 1 deletion internal/controller/azurevalidator_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
. "github.com/onsi/gomega"
"github.com/validator-labs/validator-plugin-azure/api/v1alpha1"
vapi "github.com/validator-labs/validator/api/v1alpha1"
vres "github.com/validator-labs/validator/pkg/validationresult"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
Expand Down Expand Up @@ -159,7 +160,7 @@ var _ = Describe("AzureValidator controller", Ordered, func() {
}

vr := &vapi.ValidationResult{}
vrKey := types.NamespacedName{Name: validationResultName(val), Namespace: validatorNamespace}
vrKey := types.NamespacedName{Name: vres.Name(val), Namespace: validatorNamespace}

valEmptySecretName := val.DeepCopy()
valEmptySecretName.Name = fmt.Sprintf("%s-empty-secret-name", azureValidatorName)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Package validators contains services that reconcile the validation rules supported by the plugin.
package validators
// Package azure contains services that reconcile the validation rules supported by the plugin.
package azure

import (
"fmt"
Expand All @@ -10,7 +10,7 @@ import (
corev1 "k8s.io/api/core/v1"

"github.com/validator-labs/validator-plugin-azure/api/v1alpha1"
"github.com/validator-labs/validator-plugin-azure/internal/constants"
"github.com/validator-labs/validator-plugin-azure/pkg/constants"
vapi "github.com/validator-labs/validator/api/v1alpha1"
vapiconstants "github.com/validator-labs/validator/pkg/constants"
vapitypes "github.com/validator-labs/validator/pkg/types"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package validators
package azure

import (
"errors"
Expand Down
6 changes: 3 additions & 3 deletions internal/validators/rbac.go → pkg/azure/rbac.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package validators
package azure

import (
"fmt"
Expand All @@ -8,8 +8,8 @@ import (
corev1 "k8s.io/api/core/v1"

"github.com/validator-labs/validator-plugin-azure/api/v1alpha1"
"github.com/validator-labs/validator-plugin-azure/internal/constants"
azerr "github.com/validator-labs/validator-plugin-azure/internal/utils/azureerrors"
"github.com/validator-labs/validator-plugin-azure/pkg/constants"
azerr "github.com/validator-labs/validator-plugin-azure/pkg/utils/azureerrors"
vapi "github.com/validator-labs/validator/api/v1alpha1"
vapiconstants "github.com/validator-labs/validator/pkg/constants"
vapitypes "github.com/validator-labs/validator/pkg/types"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package validators
package azure

import (
"fmt"
Expand All @@ -7,7 +7,7 @@ import (
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/authorization/armauthorization/v2"
"golang.org/x/exp/maps"

map_utils "github.com/validator-labs/validator-plugin-azure/internal/utils/maps"
map_utils "github.com/validator-labs/validator-plugin-azure/pkg/utils/maps"
)

const (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package validators
package azure

import (
"reflect"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package validators
package azure

import (
"errors"
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
63 changes: 63 additions & 0 deletions pkg/validate/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Package validate defines a Validate function that evaluates an AzureValidatorSpec and returns a ValidationResponse.
package validate

import (
"context"
"os"
"time"

"github.com/go-logr/logr"
"github.com/validator-labs/validator/pkg/types"

"github.com/validator-labs/validator-plugin-azure/api/v1alpha1"
"github.com/validator-labs/validator-plugin-azure/pkg/azure"
utils "github.com/validator-labs/validator-plugin-azure/pkg/utils/azure"
)

// Validate validates the AzureValidatorSpec and returns a ValidationResponse.
func Validate(spec v1alpha1.AzureValidatorSpec, log logr.Logger) types.ValidationResponse {
resp := types.ValidationResponse{
ValidationRuleResults: make([]*types.ValidationRuleResult, 0, spec.ResultCount()),
ValidationRuleErrors: make([]error, 0, spec.ResultCount()),
}

azureAPI, err := utils.NewAzureAPI()
if err != nil {
log.Error(err, "failed to create Azure API object")
return resp

Check warning on line 27 in pkg/validate/validate.go

View check run for this annotation

Codecov / codecov/patch

pkg/validate/validate.go#L26-L27

Added lines #L26 - L27 were not covered by tests
}

ctx := context.Background()
if os.Getenv("IS_TEST") == "true" {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, time.Now().Add(utils.TestClientTimeout))
defer cancel()
}

daClient := utils.NewDenyAssignmentsClient(ctx, azureAPI.DenyAssignmentsClient)
raClient := utils.NewRoleAssignmentsClient(ctx, azureAPI.RoleAssignmentsClient)
rdClient := utils.NewRoleDefinitionsClient(ctx, azureAPI.RoleDefinitionsClient)
cgiClient := utils.NewCommunityGalleryImagesClient(ctx, azureAPI.CommunityGalleryImagesClientProducer)

// RBAC rules
rbacSvc := azure.NewRBACRuleService(daClient, raClient, rdClient)
for _, rule := range spec.RBACRules {
vrr, err := rbacSvc.ReconcileRBACRule(rule)
if err != nil {
log.Error(err, "failed to reconcile RBAC rule")
}
resp.AddResult(vrr, err)
}

// Community gallery image rules
cgiSvc := azure.NewCommunityGalleryImageRuleService(cgiClient, log)
for _, rule := range spec.CommunityGalleryImageRules {
vrr, err := cgiSvc.ReconcileCommunityGalleryImageRule(rule)
if err != nil {
log.Error(err, "failed to reconcile community gallery image rule")

Check warning on line 57 in pkg/validate/validate.go

View check run for this annotation

Codecov / codecov/patch

pkg/validate/validate.go#L55-L57

Added lines #L55 - L57 were not covered by tests
}
resp.AddResult(vrr, err)

Check warning on line 59 in pkg/validate/validate.go

View check run for this annotation

Codecov / codecov/patch

pkg/validate/validate.go#L59

Added line #L59 was not covered by tests
}

return resp
}