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

Create VAP binding objects; update semantic equals to include labels #386

Merged
merged 4 commits into from
Jan 12, 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
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func MatchKindsCEL() []cel.ExpressionAccessor {
func BindParamsV1Alpha1() admissionregistrationv1alpha1.Variable {
return admissionregistrationv1alpha1.Variable{
Name: schema.ParamsName,
Expression: "params.spec.parameters",
Expression: "!has(params.spec) ? null : !has(params.spec.parameters) ? null: params.spec.parameters",
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -731,3 +731,84 @@ func TestMatchExcludedNamespacesGlob(t *testing.T) {
})
}
}

func UnstructuredWithValue(val interface{}, fields ...string) *unstructured.Unstructured {
obj := &unstructured.Unstructured{Object: map[string]interface{}{}}
if err := unstructured.SetNestedField(obj.Object, val, fields...); err != nil {
panic(fmt.Errorf("%w: while setting unstructured value", err))
}
return obj
}

func TestVariableBinding(t *testing.T) {
tests := []struct {
name string
constraint *unstructured.Unstructured
assertionCEL string
}{
{
name: "Params are defined",
constraint: UnstructuredWithValue(true, "spec", "parameters", "paramExists"),
assertionCEL: "variables.params.paramExists == true",
},
{
name: "Params not defined, spec is defined",
constraint: UnstructuredWithValue(true, "spec"),
assertionCEL: "variables.params == null",
},
{
name: "No spec",
constraint: UnstructuredWithValue(map[string]interface{}{}, "status"),
assertionCEL: "variables.params == null",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
filterCompiler, err := cel.NewCompositedCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion()))
if err != nil {
t.Fatal(err)
}
celOpts := cel.OptionalVariableDeclarations{HasParams: true}
filterCompiler.CompileAndStoreVariables(BindParamsCEL(), celOpts, environment.StoredExpressions)
matcher := matchconditions.NewMatcher(
filterCompiler.Compile(
[]cel.ExpressionAccessor{
&matchconditions.MatchCondition{
Name: "TestParams",
Expression: test.assertionCEL,
},
},
celOpts,
environment.StoredExpressions,
),
ptr.To[v1.FailurePolicyType](v1.Fail),
"matchTest",
"name",
test.name,
)

obj := &unstructured.Unstructured{}
objName := "test-obj"
obj.SetName(objName)
obj.SetGroupVersionKind(rSchema.GroupVersionKind{Group: "FooGroup", Kind: "BarKind"})
objBytes, err := json.Marshal(obj.Object)
if err != nil {
t.Fatal(err)
}
request := &admissionv1.AdmissionRequest{
Kind: metav1.GroupVersionKind{Group: "FooGroup", Kind: "BarKind"},
Object: runtime.RawExtension{Raw: objBytes},
}
request.Name = objName

versionedAttributes, err := RequestToVersionedAttributes(request)
if err != nil {
t.Fatal(err)
}

if err := shouldMatch(true, false, matcher.Match(context.Background(), versionedAttributes, test.constraint, nil)); err != nil {
t.Error(err)
}
})
}
}
5 changes: 5 additions & 0 deletions constraint/pkg/client/drivers/k8scel/transform/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package transform

import "errors"

var ErrBadEnforcementAction = errors.New("invalid enforcement action")
67 changes: 65 additions & 2 deletions constraint/pkg/client/drivers/k8scel/transform/make_vap_objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ package transform

import (
"fmt"
"strings"

apiconstraints "github.com/open-policy-agent/frameworks/constraint/pkg/apis/constraints"
templatesv1beta1 "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1"
"github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/k8scel/schema"
"github.com/open-policy-agent/frameworks/constraint/pkg/core/templates"
admissionregistrationv1alpha1 "k8s.io/api/admissionregistration/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/utils/ptr"
)

func TemplateToPolicyDefinition(template *templates.ConstraintTemplate) (*admissionregistrationv1alpha1.ValidatingAdmissionPolicy, error) {
Expand Down Expand Up @@ -40,11 +45,11 @@ func TemplateToPolicyDefinition(template *templates.ConstraintTemplate) (*admiss

policy := &admissionregistrationv1alpha1.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("g8r-%s", template.GetName()),
Name: fmt.Sprintf("gatekeeper-%s", template.GetName()),
},
Spec: admissionregistrationv1alpha1.ValidatingAdmissionPolicySpec{
ParamKind: &admissionregistrationv1alpha1.ParamKind{
APIVersion: templatesv1beta1.SchemeGroupVersion.Version,
APIVersion: fmt.Sprintf("%s/%s", apiconstraints.Group, templatesv1beta1.SchemeGroupVersion.Version),
Kind: template.Spec.CRD.Spec.Names.Kind,
},
MatchConstraints: nil, // We cannot support match constraints since `resource` is not available shift-left
Expand All @@ -57,3 +62,61 @@ func TemplateToPolicyDefinition(template *templates.ConstraintTemplate) (*admiss
}
return policy, nil
}

func ConstraintToBinding(constraint *unstructured.Unstructured) (*admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, error) {
enforcementActionStr, err := apiconstraints.GetEnforcementAction(constraint)
if err != nil {
return nil, err
}

var enforcementAction admissionregistrationv1alpha1.ValidationAction
switch enforcementActionStr {
case apiconstraints.EnforcementActionDeny:
enforcementAction = admissionregistrationv1alpha1.Deny
case "warn":
enforcementAction = admissionregistrationv1alpha1.Warn
default:
return nil, fmt.Errorf("%w: unrecognized enforcement action %s, must be `warn` or `deny`", ErrBadEnforcementAction, enforcementActionStr)
}

binding := &admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("gatekeeper-%s", constraint.GetName()),
},
Spec: admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: fmt.Sprintf("gatekeeper-%s", strings.ToLower(constraint.GetKind())),
ParamRef: &admissionregistrationv1alpha1.ParamRef{
Name: constraint.GetName(),
ParameterNotFoundAction: ptr.To[admissionregistrationv1alpha1.ParameterNotFoundActionType](admissionregistrationv1alpha1.AllowAction),
},
MatchResources: &admissionregistrationv1alpha1.MatchResources{},
ValidationActions: []admissionregistrationv1alpha1.ValidationAction{enforcementAction},
},
}
objectSelectorMap, found, err := unstructured.NestedMap(constraint.Object, "spec", "match", "labelSelector")
if err != nil {
return nil, err
}
var objectSelector *metav1.LabelSelector
if found {
objectSelector = &metav1.LabelSelector{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(objectSelectorMap, objectSelector); err != nil {
return nil, err
}
binding.Spec.MatchResources.ObjectSelector = objectSelector
}

namespaceSelectorMap, found, err := unstructured.NestedMap(constraint.Object, "spec", "match", "namespaceSelector")
if err != nil {
return nil, err
}
var namespaceSelector *metav1.LabelSelector
if found {
namespaceSelector = &metav1.LabelSelector{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(namespaceSelectorMap, namespaceSelector); err != nil {
return nil, err
}
binding.Spec.MatchResources.NamespaceSelector = namespaceSelector
}
return binding, nil
}
Loading
Loading