| 1 |
/* |
| 2 |
Copyright 2022 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package validating_test |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"fmt" |
| 22 |
"strings" |
| 23 |
"sync" |
| 24 |
"sync/atomic" |
| 25 |
"testing" |
| 26 |
"time" |
| 27 |
|
| 28 |
"github.com/stretchr/testify/require" |
| 29 |
|
| 30 |
admissionregistrationv1 "k8s.io/api/admissionregistration/v1" |
| 31 |
v1 "k8s.io/api/core/v1" |
| 32 |
"k8s.io/apimachinery/pkg/api/meta" |
| 33 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 34 |
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 35 |
"k8s.io/apimachinery/pkg/labels" |
| 36 |
"k8s.io/apimachinery/pkg/runtime" |
| 37 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 38 |
"k8s.io/apimachinery/pkg/types" |
| 39 |
utiljson "k8s.io/apimachinery/pkg/util/json" |
| 40 |
"k8s.io/apimachinery/pkg/util/sets" |
| 41 |
"k8s.io/apiserver/pkg/admission" |
| 42 |
"k8s.io/apiserver/pkg/admission/plugin/policy/generic" |
| 43 |
"k8s.io/apiserver/pkg/admission/plugin/policy/matching" |
| 44 |
"k8s.io/apiserver/pkg/admission/plugin/policy/validating" |
| 45 |
auditinternal "k8s.io/apiserver/pkg/apis/audit" |
| 46 |
"k8s.io/apiserver/pkg/authorization/authorizer" |
| 47 |
"k8s.io/apiserver/pkg/warning" |
| 48 |
"k8s.io/client-go/kubernetes" |
| 49 |
) |
| 50 |
|
| 51 |
var ( |
| 52 |
clusterScopedParamsGVK schema.GroupVersionKind = schema.GroupVersionKind{ |
| 53 |
Group: "example.com", |
| 54 |
Version: "v1", |
| 55 |
Kind: "ClusterScopedParamsConfig", |
| 56 |
} |
| 57 |
|
| 58 |
paramsGVK schema.GroupVersionKind = schema.GroupVersionKind{ |
| 59 |
Group: "example.com", |
| 60 |
Version: "v1", |
| 61 |
Kind: "ParamsConfig", |
| 62 |
} |
| 63 |
|
| 64 |
// Common objects |
| 65 |
denyPolicy *admissionregistrationv1.ValidatingAdmissionPolicy = &admissionregistrationv1.ValidatingAdmissionPolicy{ |
| 66 |
ObjectMeta: metav1.ObjectMeta{ |
| 67 |
Name: "denypolicy.example.com", |
| 68 |
ResourceVersion: "1", |
| 69 |
}, |
| 70 |
Spec: admissionregistrationv1.ValidatingAdmissionPolicySpec{ |
| 71 |
ParamKind: &admissionregistrationv1.ParamKind{ |
| 72 |
APIVersion: paramsGVK.GroupVersion().String(), |
| 73 |
Kind: paramsGVK.Kind, |
| 74 |
}, |
| 75 |
FailurePolicy: ptrTo(admissionregistrationv1.Fail), |
| 76 |
Validations: []admissionregistrationv1.Validation{ |
| 77 |
{ |
| 78 |
Expression: "messageId for deny policy", |
| 79 |
}, |
| 80 |
}, |
| 81 |
}, |
| 82 |
} |
| 83 |
|
| 84 |
fakeParams *unstructured.Unstructured = &unstructured.Unstructured{ |
| 85 |
Object: map[string]interface{}{ |
| 86 |
"apiVersion": paramsGVK.GroupVersion().String(), |
| 87 |
"kind": paramsGVK.Kind, |
| 88 |
"metadata": map[string]interface{}{ |
| 89 |
"name": "replicas-test.example.com", |
| 90 |
"namespace": "default", |
| 91 |
"resourceVersion": "1", |
| 92 |
}, |
| 93 |
"maxReplicas": int64(3), |
| 94 |
}, |
| 95 |
} |
| 96 |
|
| 97 |
denyBinding *admissionregistrationv1.ValidatingAdmissionPolicyBinding = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{ |
| 98 |
ObjectMeta: metav1.ObjectMeta{ |
| 99 |
Name: "denybinding.example.com", |
| 100 |
ResourceVersion: "1", |
| 101 |
}, |
| 102 |
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{ |
| 103 |
PolicyName: denyPolicy.Name, |
| 104 |
ParamRef: &admissionregistrationv1.ParamRef{ |
| 105 |
Name: fakeParams.GetName(), |
| 106 |
Namespace: fakeParams.GetNamespace(), |
| 107 |
// fake object tracker does not populate defaults |
| 108 |
ParameterNotFoundAction: ptrTo(admissionregistrationv1.DenyAction), |
| 109 |
}, |
| 110 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny}, |
| 111 |
}, |
| 112 |
} |
| 113 |
denyBindingWithNoParamRef *admissionregistrationv1.ValidatingAdmissionPolicyBinding = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{ |
| 114 |
ObjectMeta: metav1.ObjectMeta{ |
| 115 |
Name: "denybinding.example.com", |
| 116 |
ResourceVersion: "1", |
| 117 |
}, |
| 118 |
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{ |
| 119 |
PolicyName: denyPolicy.Name, |
| 120 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny}, |
| 121 |
}, |
| 122 |
} |
| 123 |
|
| 124 |
denyBindingWithAudit = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{ |
| 125 |
ObjectMeta: metav1.ObjectMeta{ |
| 126 |
Name: "denybinding.example.com", |
| 127 |
ResourceVersion: "1", |
| 128 |
}, |
| 129 |
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{ |
| 130 |
PolicyName: denyPolicy.Name, |
| 131 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Audit}, |
| 132 |
}, |
| 133 |
} |
| 134 |
denyBindingWithWarn = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{ |
| 135 |
ObjectMeta: metav1.ObjectMeta{ |
| 136 |
Name: "denybinding.example.com", |
| 137 |
ResourceVersion: "1", |
| 138 |
}, |
| 139 |
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{ |
| 140 |
PolicyName: denyPolicy.Name, |
| 141 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Warn}, |
| 142 |
}, |
| 143 |
} |
| 144 |
denyBindingWithAll = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{ |
| 145 |
ObjectMeta: metav1.ObjectMeta{ |
| 146 |
Name: "denybinding.example.com", |
| 147 |
ResourceVersion: "1", |
| 148 |
}, |
| 149 |
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{ |
| 150 |
PolicyName: denyPolicy.Name, |
| 151 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny, admissionregistrationv1.Warn, admissionregistrationv1.Audit}, |
| 152 |
}, |
| 153 |
} |
| 154 |
) |
| 155 |
|
| 156 |
func newParam(name, namespace string, labels map[string]string) *unstructured.Unstructured { |
| 157 |
if len(namespace) == 0 { |
| 158 |
namespace = metav1.NamespaceDefault |
| 159 |
} |
| 160 |
res := &unstructured.Unstructured{ |
| 161 |
Object: map[string]interface{}{ |
| 162 |
"apiVersion": paramsGVK.GroupVersion().String(), |
| 163 |
"kind": paramsGVK.Kind, |
| 164 |
"metadata": map[string]interface{}{ |
| 165 |
"name": name, |
| 166 |
"namespace": namespace, |
| 167 |
"resourceVersion": "1", |
| 168 |
}, |
| 169 |
}, |
| 170 |
} |
| 171 |
res.SetLabels(labels) |
| 172 |
return res |
| 173 |
} |
| 174 |
|
| 175 |
func newClusterScopedParam(name string, labels map[string]string) *unstructured.Unstructured { |
| 176 |
res := &unstructured.Unstructured{ |
| 177 |
Object: map[string]interface{}{ |
| 178 |
"apiVersion": clusterScopedParamsGVK.GroupVersion().String(), |
| 179 |
"kind": clusterScopedParamsGVK.Kind, |
| 180 |
"metadata": map[string]interface{}{ |
| 181 |
"name": name, |
| 182 |
"resourceVersion": "1", |
| 183 |
}, |
| 184 |
}, |
| 185 |
} |
| 186 |
res.SetLabels(labels) |
| 187 |
return res |
| 188 |
} |
| 189 |
|
| 190 |
var _ validating.Validator = validateFunc(nil) |
| 191 |
|
| 192 |
type validateFunc func( |
| 193 |
ctx context.Context, |
| 194 |
matchResource schema.GroupVersionResource, |
| 195 |
versionedAttr *admission.VersionedAttributes, |
| 196 |
versionedParams runtime.Object, |
| 197 |
namespace *v1.Namespace, |
| 198 |
runtimeCELCostBudget int64, |
| 199 |
authz authorizer.Authorizer) validating.ValidateResult |
| 200 |
|
| 201 |
type fakeCompiler struct { |
| 202 |
ValidateFuncs map[types.NamespacedName]validating.Validator |
| 203 |
|
| 204 |
lock sync.Mutex |
| 205 |
NumCompiles map[types.NamespacedName]int |
| 206 |
} |
| 207 |
|
| 208 |
func (f *fakeCompiler) getNumCompiles(p *validating.Policy) int { |
| 209 |
f.lock.Lock() |
| 210 |
defer f.lock.Unlock() |
| 211 |
return f.NumCompiles[types.NamespacedName{ |
| 212 |
Name: p.Name, |
| 213 |
Namespace: p.Namespace, |
| 214 |
}] |
| 215 |
} |
| 216 |
|
| 217 |
func (f *fakeCompiler) RegisterDefinition(definition *validating.Policy, vf validateFunc) { |
| 218 |
if f.ValidateFuncs == nil { |
| 219 |
f.ValidateFuncs = make(map[types.NamespacedName]validating.Validator) |
| 220 |
} |
| 221 |
|
| 222 |
f.ValidateFuncs[types.NamespacedName{ |
| 223 |
Name: definition.Name, |
| 224 |
Namespace: definition.Namespace, |
| 225 |
}] = vf |
| 226 |
} |
| 227 |
|
| 228 |
func (f *fakeCompiler) CompilePolicy(policy *validating.Policy) validating.Validator { |
| 229 |
nn := types.NamespacedName{ |
| 230 |
Name: policy.Name, |
| 231 |
Namespace: policy.Namespace, |
| 232 |
} |
| 233 |
|
| 234 |
defer func() { |
| 235 |
f.lock.Lock() |
| 236 |
defer f.lock.Unlock() |
| 237 |
if f.NumCompiles == nil { |
| 238 |
f.NumCompiles = make(map[types.NamespacedName]int) |
| 239 |
} |
| 240 |
f.NumCompiles[nn]++ |
| 241 |
}() |
| 242 |
return f.ValidateFuncs[nn] |
| 243 |
} |
| 244 |
|
| 245 |
func (f validateFunc) Validate( |
| 246 |
ctx context.Context, |
| 247 |
matchResource schema.GroupVersionResource, |
| 248 |
versionedAttr *admission.VersionedAttributes, |
| 249 |
versionedParams runtime.Object, |
| 250 |
namespace *v1.Namespace, |
| 251 |
runtimeCELCostBudget int64, |
| 252 |
authz authorizer.Authorizer, |
| 253 |
) validating.ValidateResult { |
| 254 |
return f( |
| 255 |
ctx, |
| 256 |
matchResource, |
| 257 |
versionedAttr, |
| 258 |
versionedParams, |
| 259 |
namespace, |
| 260 |
runtimeCELCostBudget, |
| 261 |
authz, |
| 262 |
) |
| 263 |
} |
| 264 |
|
| 265 |
var _ generic.PolicyMatcher = &fakeMatcher{} |
| 266 |
|
| 267 |
func (f *fakeMatcher) ValidateInitialization() error { |
| 268 |
return nil |
| 269 |
} |
| 270 |
|
| 271 |
func (f *fakeMatcher) GetNamespace(name string) (*v1.Namespace, error) { |
| 272 |
return nil, nil |
| 273 |
} |
| 274 |
|
| 275 |
type fakeMatcher struct { |
| 276 |
DefaultMatch bool |
| 277 |
DefinitionMatchFuncs map[types.NamespacedName]func(generic.PolicyAccessor, admission.Attributes) bool |
| 278 |
BindingMatchFuncs map[types.NamespacedName]func(generic.BindingAccessor, admission.Attributes) bool |
| 279 |
} |
| 280 |
|
| 281 |
func (f *fakeMatcher) RegisterDefinition(definition *admissionregistrationv1.ValidatingAdmissionPolicy, matchFunc func(generic.PolicyAccessor, admission.Attributes) bool) { |
| 282 |
namespace, name := definition.Namespace, definition.Name |
| 283 |
key := types.NamespacedName{ |
| 284 |
Name: name, |
| 285 |
Namespace: namespace, |
| 286 |
} |
| 287 |
|
| 288 |
if matchFunc != nil { |
| 289 |
if f.DefinitionMatchFuncs == nil { |
| 290 |
f.DefinitionMatchFuncs = make(map[types.NamespacedName]func(generic.PolicyAccessor, admission.Attributes) bool) |
| 291 |
} |
| 292 |
f.DefinitionMatchFuncs[key] = matchFunc |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
func (f *fakeMatcher) RegisterBinding(binding *admissionregistrationv1.ValidatingAdmissionPolicyBinding, matchFunc func(generic.BindingAccessor, admission.Attributes) bool) { |
| 297 |
namespace, name := binding.Namespace, binding.Name |
| 298 |
key := types.NamespacedName{ |
| 299 |
Name: name, |
| 300 |
Namespace: namespace, |
| 301 |
} |
| 302 |
|
| 303 |
if matchFunc != nil { |
| 304 |
if f.BindingMatchFuncs == nil { |
| 305 |
f.BindingMatchFuncs = make(map[types.NamespacedName]func(generic.BindingAccessor, admission.Attributes) bool) |
| 306 |
} |
| 307 |
f.BindingMatchFuncs[key] = matchFunc |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
// Matches says whether this policy definition matches the provided admission |
| 312 |
// resource request |
| 313 |
func (f *fakeMatcher) DefinitionMatches(a admission.Attributes, o admission.ObjectInterfaces, definition generic.PolicyAccessor) (bool, schema.GroupVersionResource, schema.GroupVersionKind, error) { |
| 314 |
namespace, name := definition.GetNamespace(), definition.GetName() |
| 315 |
key := types.NamespacedName{ |
| 316 |
Name: name, |
| 317 |
Namespace: namespace, |
| 318 |
} |
| 319 |
if fun, ok := f.DefinitionMatchFuncs[key]; ok { |
| 320 |
return fun(definition, a), a.GetResource(), a.GetKind(), nil |
| 321 |
} |
| 322 |
|
| 323 |
// Default is match everything |
| 324 |
return f.DefaultMatch, a.GetResource(), a.GetKind(), nil |
| 325 |
} |
| 326 |
|
| 327 |
// Matches says whether this policy definition matches the provided admission |
| 328 |
// resource request |
| 329 |
func (f *fakeMatcher) BindingMatches(a admission.Attributes, o admission.ObjectInterfaces, binding generic.BindingAccessor) (bool, error) { |
| 330 |
namespace, name := binding.GetNamespace(), binding.GetName() |
| 331 |
key := types.NamespacedName{ |
| 332 |
Name: name, |
| 333 |
Namespace: namespace, |
| 334 |
} |
| 335 |
if fun, ok := f.BindingMatchFuncs[key]; ok { |
| 336 |
return fun(binding, a), nil |
| 337 |
} |
| 338 |
|
| 339 |
// Default is match everything |
| 340 |
return f.DefaultMatch, nil |
| 341 |
} |
| 342 |
|
| 343 |
func setupFakeTest(t *testing.T, comp *fakeCompiler, match *fakeMatcher) *generic.PolicyTestContext[*validating.Policy, *validating.PolicyBinding, validating.Validator] { |
| 344 |
return setupTestCommon(t, comp, match, true) |
| 345 |
} |
| 346 |
|
| 347 |
// Starts CEL admission controller and sets up a plugin configured with it as well |
| 348 |
// as object trackers for manipulating the objects available to the system |
| 349 |
// |
| 350 |
// ParamTracker only knows the gvk `paramGVK`. If in the future we need to |
| 351 |
// support multiple types of params this function needs to be augmented |
| 352 |
// |
| 353 |
// PolicyTracker expects FakePolicyDefinition and FakePolicyBinding types |
| 354 |
// !TODO: refactor this test/framework to remove startInformers argument and |
| 355 |
// clean up the return args, and in general make it more accessible. |
| 356 |
func setupTestCommon( |
| 357 |
t *testing.T, |
| 358 |
compiler *fakeCompiler, |
| 359 |
matcher generic.PolicyMatcher, |
| 360 |
shouldStartInformers bool, |
| 361 |
) *generic.PolicyTestContext[*validating.Policy, *validating.PolicyBinding, validating.Validator] { |
| 362 |
testContext, testContextCancel, err := generic.NewPolicyTestContext( |
| 363 |
validating.NewValidatingAdmissionPolicyAccessor, |
| 364 |
validating.NewValidatingAdmissionPolicyBindingAccessor, |
| 365 |
func(p *validating.Policy) validating.Validator { |
| 366 |
return compiler.CompilePolicy(p) |
| 367 |
}, |
| 368 |
func(a authorizer.Authorizer, m *matching.Matcher, client kubernetes.Interface) generic.Dispatcher[validating.PolicyHook] { |
| 369 |
coolMatcher := matcher |
| 370 |
if coolMatcher == nil { |
| 371 |
coolMatcher = generic.NewPolicyMatcher(m) |
| 372 |
} |
| 373 |
return validating.NewDispatcher(a, coolMatcher) |
| 374 |
}, |
| 375 |
nil, |
| 376 |
[]meta.RESTMapping{ |
| 377 |
{ |
| 378 |
Resource: paramsGVK.GroupVersion().WithResource("paramsconfigs"), |
| 379 |
GroupVersionKind: paramsGVK, |
| 380 |
Scope: meta.RESTScopeNamespace, |
| 381 |
}, |
| 382 |
{ |
| 383 |
Resource: clusterScopedParamsGVK.GroupVersion().WithResource("clusterscopedparamsconfigs"), |
| 384 |
GroupVersionKind: clusterScopedParamsGVK, |
| 385 |
Scope: meta.RESTScopeRoot, |
| 386 |
}, |
| 387 |
{ |
| 388 |
Resource: schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "validatingadmissionpolicies"}, |
| 389 |
GroupVersionKind: schema.GroupVersionKind{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingAdmissionPolicy"}, |
| 390 |
Scope: meta.RESTScopeRoot, |
| 391 |
}, |
| 392 |
}, |
| 393 |
) |
| 394 |
require.NoError(t, err) |
| 395 |
t.Cleanup(testContextCancel) |
| 396 |
|
| 397 |
if shouldStartInformers { |
| 398 |
require.NoError(t, testContext.Start()) |
| 399 |
} |
| 400 |
|
| 401 |
return testContext |
| 402 |
} |
| 403 |
|
| 404 |
func attributeRecord( |
| 405 |
old, new runtime.Object, |
| 406 |
operation admission.Operation, |
| 407 |
) *FakeAttributes { |
| 408 |
if old == nil && new == nil { |
| 409 |
panic("both `old` and `new` may not be nil") |
| 410 |
} |
| 411 |
|
| 412 |
// one of old/new may be nil, but not both |
| 413 |
example := new |
| 414 |
if example == nil { |
| 415 |
example = old |
| 416 |
} |
| 417 |
|
| 418 |
accessor, err := meta.Accessor(example) |
| 419 |
if err != nil { |
| 420 |
panic(err) |
| 421 |
} |
| 422 |
|
| 423 |
return &FakeAttributes{ |
| 424 |
Attributes: admission.NewAttributesRecord( |
| 425 |
new, |
| 426 |
old, |
| 427 |
example.GetObjectKind().GroupVersionKind(), |
| 428 |
accessor.GetNamespace(), |
| 429 |
accessor.GetName(), |
| 430 |
schema.GroupVersionResource{}, |
| 431 |
"", |
| 432 |
operation, |
| 433 |
nil, |
| 434 |
false, |
| 435 |
nil, |
| 436 |
), |
| 437 |
} |
| 438 |
} |
| 439 |
|
| 440 |
func ptrTo[T any](obj T) *T { |
| 441 |
return &obj |
| 442 |
} |
| 443 |
|
| 444 |
// ////////////////////////////////////////////////////////////////////////////// |
| 445 |
// Functionality Tests |
| 446 |
// ////////////////////////////////////////////////////////////////////////////// |
| 447 |
|
| 448 |
func TestPluginNotReady(t *testing.T) { |
| 449 |
compiler := &fakeCompiler{} |
| 450 |
matcher := &fakeMatcher{ |
| 451 |
DefaultMatch: true, |
| 452 |
} |
| 453 |
|
| 454 |
// Show that an unstarted informer (or one that has failed its listwatch) |
| 455 |
// will show proper error from plugin |
| 456 |
ctx := setupTestCommon(t, compiler, matcher, false) |
| 457 |
err := ctx.Plugin.Dispatch( |
| 458 |
context.Background(), |
| 459 |
// Object is irrelevant/unchecked for this test. Just test that |
| 460 |
// the evaluator is executed, and returns a denial |
| 461 |
attributeRecord(nil, fakeParams, admission.Create), |
| 462 |
&admission.RuntimeObjectInterfaces{}, |
| 463 |
) |
| 464 |
|
| 465 |
require.ErrorContains(t, err, "not yet ready to handle request") |
| 466 |
|
| 467 |
// Show that by now starting the informer, the error is dissipated |
| 468 |
ctx = setupTestCommon(t, compiler, matcher, true) |
| 469 |
err = ctx.Plugin.Dispatch( |
| 470 |
context.Background(), |
| 471 |
// Object is irrelevant/unchecked for this test. Just test that |
| 472 |
// the evaluator is executed, and returns a denial |
| 473 |
attributeRecord(nil, fakeParams, admission.Create), |
| 474 |
&admission.RuntimeObjectInterfaces{}, |
| 475 |
) |
| 476 |
|
| 477 |
require.NoError(t, err) |
| 478 |
} |
| 479 |
|
| 480 |
func TestBasicPolicyDefinitionFailure(t *testing.T) { |
| 481 |
datalock := sync.Mutex{} |
| 482 |
numCompiles := 0 |
| 483 |
|
| 484 |
compiler := &fakeCompiler{} |
| 485 |
matcher := &fakeMatcher{ |
| 486 |
DefaultMatch: true, |
| 487 |
} |
| 488 |
|
| 489 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 490 |
datalock.Lock() |
| 491 |
numCompiles += 1 |
| 492 |
datalock.Unlock() |
| 493 |
return validating.ValidateResult{ |
| 494 |
Decisions: []validating.PolicyDecision{ |
| 495 |
{ |
| 496 |
Action: validating.ActionDeny, |
| 497 |
Message: "Denied", |
| 498 |
}, |
| 499 |
}, |
| 500 |
} |
| 501 |
}) |
| 502 |
|
| 503 |
testContext := setupFakeTest(t, compiler, matcher) |
| 504 |
require.NoError(t, testContext.UpdateAndWait(fakeParams, denyPolicy, denyBinding)) |
| 505 |
|
| 506 |
warningRecorder := newWarningRecorder() |
| 507 |
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder) |
| 508 |
attr := attributeRecord(nil, fakeParams, admission.Create) |
| 509 |
err := testContext.Plugin.Dispatch( |
| 510 |
warnCtx, |
| 511 |
// Object is irrelevant/unchecked for this test. Just test that |
| 512 |
// the evaluator is executed, and returns a denial |
| 513 |
attr, |
| 514 |
&admission.RuntimeObjectInterfaces{}, |
| 515 |
) |
| 516 |
|
| 517 |
require.Equal(t, 0, warningRecorder.len()) |
| 518 |
|
| 519 |
annotations := attr.GetAnnotations(auditinternal.LevelMetadata) |
| 520 |
require.Empty(t, annotations) |
| 521 |
|
| 522 |
require.ErrorContains(t, err, `Denied`) |
| 523 |
} |
| 524 |
|
| 525 |
// Shows that if a definition does not match the input, it will not be used. |
| 526 |
// But with a different input it will be used. |
| 527 |
func TestDefinitionDoesntMatch(t *testing.T) { |
| 528 |
compiler := &fakeCompiler{} |
| 529 |
matcher := &fakeMatcher{ |
| 530 |
DefaultMatch: true, |
| 531 |
} |
| 532 |
|
| 533 |
testContext := setupFakeTest(t, compiler, matcher) |
| 534 |
|
| 535 |
datalock := sync.Mutex{} |
| 536 |
passedParams := []*unstructured.Unstructured{} |
| 537 |
numCompiles := 0 |
| 538 |
|
| 539 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 540 |
datalock.Lock() |
| 541 |
numCompiles += 1 |
| 542 |
datalock.Unlock() |
| 543 |
return validating.ValidateResult{ |
| 544 |
Decisions: []validating.PolicyDecision{ |
| 545 |
{ |
| 546 |
Action: validating.ActionDeny, |
| 547 |
Message: "Denied", |
| 548 |
}, |
| 549 |
}, |
| 550 |
} |
| 551 |
}) |
| 552 |
|
| 553 |
matcher.RegisterDefinition(denyPolicy, func(vap generic.PolicyAccessor, a admission.Attributes) bool { |
| 554 |
// Match names with even-numbered length |
| 555 |
obj := a.GetObject() |
| 556 |
|
| 557 |
accessor, err := meta.Accessor(obj) |
| 558 |
if err != nil { |
| 559 |
t.Fatal(err) |
| 560 |
return false |
| 561 |
} |
| 562 |
|
| 563 |
return len(accessor.GetName())%2 == 0 |
| 564 |
}) |
| 565 |
|
| 566 |
require.NoError(t, testContext.UpdateAndWait(fakeParams, denyPolicy, denyBinding)) |
| 567 |
|
| 568 |
// Validate a non-matching input. |
| 569 |
// Should pass validation with no error. |
| 570 |
|
| 571 |
nonMatchingParams := &unstructured.Unstructured{ |
| 572 |
Object: map[string]interface{}{ |
| 573 |
"apiVersion": paramsGVK.GroupVersion().String(), |
| 574 |
"kind": paramsGVK.Kind, |
| 575 |
"metadata": map[string]interface{}{ |
| 576 |
"name": "oddlength", |
| 577 |
"resourceVersion": "1", |
| 578 |
}, |
| 579 |
}, |
| 580 |
} |
| 581 |
require.NoError(t, |
| 582 |
testContext.Plugin.Dispatch(testContext, |
| 583 |
attributeRecord( |
| 584 |
nil, nonMatchingParams, |
| 585 |
admission.Create), &admission.RuntimeObjectInterfaces{})) |
| 586 |
require.Empty(t, passedParams) |
| 587 |
|
| 588 |
// Validate a matching input. |
| 589 |
// Should match and be denied. |
| 590 |
matchingParams := &unstructured.Unstructured{ |
| 591 |
Object: map[string]interface{}{ |
| 592 |
"apiVersion": paramsGVK.GroupVersion().String(), |
| 593 |
"kind": paramsGVK.Kind, |
| 594 |
"metadata": map[string]interface{}{ |
| 595 |
"name": "evenlength", |
| 596 |
"resourceVersion": "1", |
| 597 |
}, |
| 598 |
}, |
| 599 |
} |
| 600 |
require.ErrorContains(t, |
| 601 |
testContext.Plugin.Dispatch(testContext, |
| 602 |
attributeRecord( |
| 603 |
nil, matchingParams, |
| 604 |
admission.Create), &admission.RuntimeObjectInterfaces{}), |
| 605 |
`Denied`) |
| 606 |
require.Equal(t, 1, numCompiles) |
| 607 |
} |
| 608 |
|
| 609 |
func TestReconfigureBinding(t *testing.T) { |
| 610 |
compiler := &fakeCompiler{} |
| 611 |
matcher := &fakeMatcher{ |
| 612 |
DefaultMatch: true, |
| 613 |
} |
| 614 |
|
| 615 |
testContext := setupFakeTest(t, compiler, matcher) |
| 616 |
|
| 617 |
datalock := sync.Mutex{} |
| 618 |
numCompiles := 0 |
| 619 |
|
| 620 |
fakeParams2 := &unstructured.Unstructured{ |
| 621 |
Object: map[string]interface{}{ |
| 622 |
"apiVersion": paramsGVK.GroupVersion().String(), |
| 623 |
"kind": paramsGVK.Kind, |
| 624 |
"metadata": map[string]interface{}{ |
| 625 |
"name": "replicas-test2.example.com", |
| 626 |
// fake object tracker does not populate missing namespace |
| 627 |
"namespace": "default", |
| 628 |
"resourceVersion": "2", |
| 629 |
}, |
| 630 |
"maxReplicas": int64(35), |
| 631 |
}, |
| 632 |
} |
| 633 |
|
| 634 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 635 |
datalock.Lock() |
| 636 |
numCompiles += 1 |
| 637 |
datalock.Unlock() |
| 638 |
return validating.ValidateResult{ |
| 639 |
Decisions: []validating.PolicyDecision{ |
| 640 |
{ |
| 641 |
Action: validating.ActionDeny, |
| 642 |
Message: "Denied", |
| 643 |
}, |
| 644 |
}, |
| 645 |
} |
| 646 |
}) |
| 647 |
|
| 648 |
denyBinding2 := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{ |
| 649 |
ObjectMeta: metav1.ObjectMeta{ |
| 650 |
Name: "denybinding.example.com", |
| 651 |
ResourceVersion: "2", |
| 652 |
}, |
| 653 |
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{ |
| 654 |
PolicyName: denyPolicy.Name, |
| 655 |
ParamRef: &admissionregistrationv1.ParamRef{ |
| 656 |
Name: fakeParams2.GetName(), |
| 657 |
Namespace: fakeParams2.GetNamespace(), |
| 658 |
ParameterNotFoundAction: ptrTo(admissionregistrationv1.DenyAction), |
| 659 |
}, |
| 660 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny}, |
| 661 |
}, |
| 662 |
} |
| 663 |
|
| 664 |
require.NoError(t, testContext.UpdateAndWait(fakeParams, denyPolicy, denyBinding)) |
| 665 |
|
| 666 |
err := testContext.Plugin.Dispatch( |
| 667 |
testContext, |
| 668 |
attributeRecord(nil, fakeParams, admission.Create), |
| 669 |
&admission.RuntimeObjectInterfaces{}, |
| 670 |
) |
| 671 |
|
| 672 |
// Expect validation to fail for first time due to binding unconditionally |
| 673 |
// failing |
| 674 |
require.ErrorContains(t, err, `Denied`, "expect policy validation error") |
| 675 |
|
| 676 |
// Expect `Compile` only called once |
| 677 |
require.Equal(t, 1, numCompiles, "expect `Compile` to be called only once") |
| 678 |
|
| 679 |
// Update the tracker to point at different params |
| 680 |
require.NoError(t, testContext.UpdateAndWait(denyBinding2)) |
| 681 |
|
| 682 |
err = testContext.Plugin.Dispatch( |
| 683 |
testContext, |
| 684 |
attributeRecord(nil, fakeParams, admission.Create), |
| 685 |
&admission.RuntimeObjectInterfaces{}, |
| 686 |
) |
| 687 |
|
| 688 |
require.ErrorContains(t, err, "no params found for policy binding with `Deny` parameterNotFoundAction") |
| 689 |
|
| 690 |
// Add the missing params |
| 691 |
require.NoError(t, testContext.UpdateAndWait(fakeParams2)) |
| 692 |
|
| 693 |
// Expect validation to now fail again. |
| 694 |
err = testContext.Plugin.Dispatch( |
| 695 |
testContext, |
| 696 |
attributeRecord(nil, fakeParams, admission.Create), |
| 697 |
&admission.RuntimeObjectInterfaces{}, |
| 698 |
) |
| 699 |
|
| 700 |
// Expect validation to fail the third time due to validation failure |
| 701 |
require.ErrorContains(t, err, `Denied`, "expected a true policy failure, not a configuration error") |
| 702 |
// require.Equal(t, []*unstructured.Unstructured{fakeParams, fakeParams2}, passedParams, "expected call to `Validate` to cause call to evaluator") |
| 703 |
require.Equal(t, 2, numCompiles, "expect changing binding causes a recompile") |
| 704 |
} |
| 705 |
|
| 706 |
// Shows that a policy which is in effect will stop being in effect when removed |
| 707 |
func TestRemoveDefinition(t *testing.T) { |
| 708 |
compiler := &fakeCompiler{} |
| 709 |
matcher := &fakeMatcher{ |
| 710 |
DefaultMatch: true, |
| 711 |
} |
| 712 |
|
| 713 |
testContext := setupFakeTest(t, compiler, matcher) |
| 714 |
|
| 715 |
datalock := sync.Mutex{} |
| 716 |
numCompiles := 0 |
| 717 |
|
| 718 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 719 |
datalock.Lock() |
| 720 |
numCompiles += 1 |
| 721 |
datalock.Unlock() |
| 722 |
|
| 723 |
return validating.ValidateResult{ |
| 724 |
Decisions: []validating.PolicyDecision{ |
| 725 |
{ |
| 726 |
Action: validating.ActionDeny, |
| 727 |
Message: "Denied", |
| 728 |
}, |
| 729 |
}, |
| 730 |
} |
| 731 |
}) |
| 732 |
|
| 733 |
require.NoError(t, testContext.UpdateAndWait(fakeParams, denyPolicy, denyBinding)) |
| 734 |
|
| 735 |
record := attributeRecord(nil, fakeParams, admission.Create) |
| 736 |
require.ErrorContains(t, |
| 737 |
testContext.Plugin.Dispatch( |
| 738 |
testContext, |
| 739 |
record, |
| 740 |
&admission.RuntimeObjectInterfaces{}, |
| 741 |
), |
| 742 |
`Denied`) |
| 743 |
|
| 744 |
require.NoError(t, testContext.DeleteAndWait(denyPolicy)) |
| 745 |
|
| 746 |
require.NoError(t, testContext.Plugin.Dispatch( |
| 747 |
testContext, |
| 748 |
// Object is irrelevant/unchecked for this test. Just test that |
| 749 |
// the evaluator is executed, and returns a denial |
| 750 |
record, |
| 751 |
&admission.RuntimeObjectInterfaces{}, |
| 752 |
)) |
| 753 |
} |
| 754 |
|
| 755 |
// Shows that a binding which is in effect will stop being in effect when removed |
| 756 |
func TestRemoveBinding(t *testing.T) { |
| 757 |
compiler := &fakeCompiler{} |
| 758 |
matcher := &fakeMatcher{ |
| 759 |
DefaultMatch: true, |
| 760 |
} |
| 761 |
|
| 762 |
testContext := setupFakeTest(t, compiler, matcher) |
| 763 |
|
| 764 |
datalock := sync.Mutex{} |
| 765 |
numCompiles := 0 |
| 766 |
|
| 767 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 768 |
datalock.Lock() |
| 769 |
numCompiles += 1 |
| 770 |
datalock.Unlock() |
| 771 |
|
| 772 |
return validating.ValidateResult{ |
| 773 |
Decisions: []validating.PolicyDecision{ |
| 774 |
{ |
| 775 |
Action: validating.ActionDeny, |
| 776 |
Message: "Denied", |
| 777 |
}, |
| 778 |
}, |
| 779 |
} |
| 780 |
}) |
| 781 |
|
| 782 |
require.NoError(t, testContext.UpdateAndWait(fakeParams, denyPolicy, denyBinding)) |
| 783 |
|
| 784 |
record := attributeRecord(nil, fakeParams, admission.Create) |
| 785 |
|
| 786 |
require.ErrorContains(t, |
| 787 |
testContext.Plugin.Dispatch( |
| 788 |
testContext, |
| 789 |
record, |
| 790 |
&admission.RuntimeObjectInterfaces{}, |
| 791 |
), |
| 792 |
`Denied`) |
| 793 |
|
| 794 |
require.NoError(t, testContext.DeleteAndWait(denyBinding)) |
| 795 |
} |
| 796 |
|
| 797 |
// Shows that an error is surfaced if a paramSource specified in a binding does |
| 798 |
// not actually exist |
| 799 |
func TestInvalidParamSourceGVK(t *testing.T) { |
| 800 |
compiler := &fakeCompiler{} |
| 801 |
matcher := &fakeMatcher{ |
| 802 |
DefaultMatch: true, |
| 803 |
} |
| 804 |
|
| 805 |
testContext := setupFakeTest(t, compiler, matcher) |
| 806 |
passedParams := make(chan *unstructured.Unstructured) |
| 807 |
|
| 808 |
badPolicy := *denyPolicy |
| 809 |
badPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{ |
| 810 |
APIVersion: paramsGVK.GroupVersion().String(), |
| 811 |
Kind: "BadParamKind", |
| 812 |
} |
| 813 |
|
| 814 |
require.NoError(t, testContext.UpdateAndWait(&badPolicy, denyBinding)) |
| 815 |
|
| 816 |
err := testContext.Plugin.Dispatch( |
| 817 |
testContext, |
| 818 |
attributeRecord(nil, fakeParams, admission.Create), |
| 819 |
&admission.RuntimeObjectInterfaces{}, |
| 820 |
) |
| 821 |
|
| 822 |
// expect the specific error to be that the param was not found, not that CRD |
| 823 |
// is not existing |
| 824 |
require.ErrorContains(t, err, |
| 825 |
`failed to configure policy: failed to find resource referenced by paramKind: 'example.com/v1, Kind=BadParamKind'`) |
| 826 |
|
| 827 |
close(passedParams) |
| 828 |
require.Empty(t, passedParams) |
| 829 |
} |
| 830 |
|
| 831 |
// Shows that an error is surfaced if a param specified in a binding does not |
| 832 |
// actually exist |
| 833 |
func TestInvalidParamSourceInstanceName(t *testing.T) { |
| 834 |
compiler := &fakeCompiler{} |
| 835 |
matcher := &fakeMatcher{ |
| 836 |
DefaultMatch: true, |
| 837 |
} |
| 838 |
|
| 839 |
testContext := setupFakeTest(t, compiler, matcher) |
| 840 |
|
| 841 |
datalock := sync.Mutex{} |
| 842 |
passedParams := []*unstructured.Unstructured{} |
| 843 |
numCompiles := 0 |
| 844 |
|
| 845 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 846 |
datalock.Lock() |
| 847 |
numCompiles += 1 |
| 848 |
datalock.Unlock() |
| 849 |
|
| 850 |
return validating.ValidateResult{ |
| 851 |
Decisions: []validating.PolicyDecision{ |
| 852 |
{ |
| 853 |
Action: validating.ActionDeny, |
| 854 |
Message: "Denied", |
| 855 |
}, |
| 856 |
}, |
| 857 |
} |
| 858 |
}) |
| 859 |
|
| 860 |
require.NoError(t, testContext.UpdateAndWait(denyPolicy, denyBinding)) |
| 861 |
|
| 862 |
err := testContext.Plugin.Dispatch( |
| 863 |
testContext, |
| 864 |
attributeRecord(nil, fakeParams, admission.Create), |
| 865 |
&admission.RuntimeObjectInterfaces{}, |
| 866 |
) |
| 867 |
|
| 868 |
// expect the specific error to be that the param was not found, not that CRD |
| 869 |
// is not existing |
| 870 |
require.ErrorContains(t, err, |
| 871 |
"no params found for policy binding with `Deny` parameterNotFoundAction") |
| 872 |
require.Empty(t, passedParams) |
| 873 |
} |
| 874 |
|
| 875 |
// Show that policy still gets evaluated with `nil` param if paramRef & namespaceParamRef |
| 876 |
// are both unset |
| 877 |
func TestEmptyParamRef(t *testing.T) { |
| 878 |
compiler := &fakeCompiler{} |
| 879 |
matcher := &fakeMatcher{ |
| 880 |
DefaultMatch: true, |
| 881 |
} |
| 882 |
|
| 883 |
testContext := setupFakeTest(t, compiler, matcher) |
| 884 |
|
| 885 |
datalock := sync.Mutex{} |
| 886 |
numCompiles := 0 |
| 887 |
|
| 888 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 889 |
datalock.Lock() |
| 890 |
numCompiles += 1 |
| 891 |
datalock.Unlock() |
| 892 |
|
| 893 |
// Versioned params must be nil to pass the test |
| 894 |
if versionedParams != nil { |
| 895 |
return validating.ValidateResult{ |
| 896 |
Decisions: []validating.PolicyDecision{ |
| 897 |
{ |
| 898 |
Action: validating.ActionAdmit, |
| 899 |
}, |
| 900 |
}, |
| 901 |
} |
| 902 |
} |
| 903 |
return validating.ValidateResult{ |
| 904 |
Decisions: []validating.PolicyDecision{ |
| 905 |
{ |
| 906 |
Action: validating.ActionDeny, |
| 907 |
Message: "Denied", |
| 908 |
}, |
| 909 |
}, |
| 910 |
} |
| 911 |
}) |
| 912 |
|
| 913 |
require.NoError(t, testContext.UpdateAndWait(denyPolicy, denyBindingWithNoParamRef)) |
| 914 |
|
| 915 |
err := testContext.Plugin.Dispatch( |
| 916 |
testContext, |
| 917 |
// Object is irrelevant/unchecked for this test. Just test that |
| 918 |
// the evaluator is executed, and returns a denial |
| 919 |
attributeRecord(nil, fakeParams, admission.Create), |
| 920 |
&admission.RuntimeObjectInterfaces{}, |
| 921 |
) |
| 922 |
|
| 923 |
require.ErrorContains(t, err, `Denied`) |
| 924 |
require.Equal(t, 1, numCompiles) |
| 925 |
} |
| 926 |
|
| 927 |
// Shows that a definition with no param source works just fine, and has |
| 928 |
// nil params passed to its evaluator. |
| 929 |
// |
| 930 |
// Also shows that if binding has specified params in this instance then they |
| 931 |
// are silently ignored. |
| 932 |
func TestEmptyParamSource(t *testing.T) { |
| 933 |
compiler := &fakeCompiler{} |
| 934 |
matcher := &fakeMatcher{ |
| 935 |
DefaultMatch: true, |
| 936 |
} |
| 937 |
|
| 938 |
testContext := setupFakeTest(t, compiler, matcher) |
| 939 |
|
| 940 |
datalock := sync.Mutex{} |
| 941 |
numCompiles := 0 |
| 942 |
|
| 943 |
// Push some fake |
| 944 |
noParamSourcePolicy := *denyPolicy |
| 945 |
noParamSourcePolicy.Spec.ParamKind = nil |
| 946 |
|
| 947 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 948 |
datalock.Lock() |
| 949 |
numCompiles += 1 |
| 950 |
datalock.Unlock() |
| 951 |
return validating.ValidateResult{ |
| 952 |
Decisions: []validating.PolicyDecision{ |
| 953 |
{ |
| 954 |
Action: validating.ActionDeny, |
| 955 |
Message: "Denied", |
| 956 |
}, |
| 957 |
}, |
| 958 |
} |
| 959 |
}) |
| 960 |
|
| 961 |
require.NoError(t, testContext.UpdateAndWait(&noParamSourcePolicy, denyBindingWithNoParamRef)) |
| 962 |
|
| 963 |
err := testContext.Plugin.Dispatch( |
| 964 |
testContext, |
| 965 |
// Object is irrelevant/unchecked for this test. Just test that |
| 966 |
// the evaluator is executed, and returns a denial |
| 967 |
attributeRecord(nil, fakeParams, admission.Create), |
| 968 |
&admission.RuntimeObjectInterfaces{}, |
| 969 |
) |
| 970 |
|
| 971 |
require.ErrorContains(t, err, `Denied`) |
| 972 |
require.Equal(t, 1, numCompiles) |
| 973 |
} |
| 974 |
|
| 975 |
// Shows what happens when multiple policies share one param type, then |
| 976 |
// one policy stops using the param. The expectation is the second policy |
| 977 |
// keeps behaving normally |
| 978 |
func TestMultiplePoliciesSharedParamType(t *testing.T) { |
| 979 |
compiler := &fakeCompiler{} |
| 980 |
matcher := &fakeMatcher{ |
| 981 |
DefaultMatch: true, |
| 982 |
} |
| 983 |
|
| 984 |
testContext := setupFakeTest(t, compiler, matcher) |
| 985 |
|
| 986 |
// Use ConfigMap native-typed param |
| 987 |
policy1 := *denyPolicy |
| 988 |
policy1.Name = "denypolicy1.example.com" |
| 989 |
policy1.Spec = admissionregistrationv1.ValidatingAdmissionPolicySpec{ |
| 990 |
ParamKind: &admissionregistrationv1.ParamKind{ |
| 991 |
APIVersion: paramsGVK.GroupVersion().String(), |
| 992 |
Kind: paramsGVK.Kind, |
| 993 |
}, |
| 994 |
FailurePolicy: ptrTo(admissionregistrationv1.Fail), |
| 995 |
Validations: []admissionregistrationv1.Validation{ |
| 996 |
{ |
| 997 |
Expression: "policy1", |
| 998 |
}, |
| 999 |
}, |
| 1000 |
} |
| 1001 |
|
| 1002 |
policy2 := *denyPolicy |
| 1003 |
policy2.Name = "denypolicy2.example.com" |
| 1004 |
policy2.Spec = admissionregistrationv1.ValidatingAdmissionPolicySpec{ |
| 1005 |
ParamKind: &admissionregistrationv1.ParamKind{ |
| 1006 |
APIVersion: paramsGVK.GroupVersion().String(), |
| 1007 |
Kind: paramsGVK.Kind, |
| 1008 |
}, |
| 1009 |
FailurePolicy: ptrTo(admissionregistrationv1.Fail), |
| 1010 |
Validations: []admissionregistrationv1.Validation{ |
| 1011 |
{ |
| 1012 |
Expression: "policy2", |
| 1013 |
}, |
| 1014 |
}, |
| 1015 |
} |
| 1016 |
|
| 1017 |
binding1 := *denyBinding |
| 1018 |
binding2 := *denyBinding |
| 1019 |
|
| 1020 |
binding1.Name = "denybinding1.example.com" |
| 1021 |
binding1.Spec.PolicyName = policy1.Name |
| 1022 |
binding2.Name = "denybinding2.example.com" |
| 1023 |
binding2.Spec.PolicyName = policy2.Name |
| 1024 |
|
| 1025 |
evaluations1 := atomic.Int64{} |
| 1026 |
evaluations2 := atomic.Int64{} |
| 1027 |
|
| 1028 |
compiler.RegisterDefinition(&policy1, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1029 |
evaluations1.Add(1) |
| 1030 |
|
| 1031 |
return validating.ValidateResult{ |
| 1032 |
Decisions: []validating.PolicyDecision{ |
| 1033 |
{ |
| 1034 |
Action: validating.ActionAdmit, |
| 1035 |
}, |
| 1036 |
}, |
| 1037 |
} |
| 1038 |
}) |
| 1039 |
|
| 1040 |
compiler.RegisterDefinition(&policy2, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1041 |
evaluations2.Add(1) |
| 1042 |
return validating.ValidateResult{ |
| 1043 |
Decisions: []validating.PolicyDecision{ |
| 1044 |
{ |
| 1045 |
Action: validating.ActionDeny, |
| 1046 |
Message: "Policy2Denied", |
| 1047 |
}, |
| 1048 |
}, |
| 1049 |
} |
| 1050 |
}) |
| 1051 |
|
| 1052 |
require.NoError(t, testContext.UpdateAndWait(fakeParams, &policy1, &binding1)) |
| 1053 |
|
| 1054 |
// Make sure policy 1 is created and bound to the params type first |
| 1055 |
require.NoError(t, testContext.UpdateAndWait(&policy2, &binding2)) |
| 1056 |
|
| 1057 |
err := testContext.Plugin.Dispatch( |
| 1058 |
testContext, |
| 1059 |
// Object is irrelevant/unchecked for this test. Just test that |
| 1060 |
// the evaluator is executed, and returns admit meaning the params |
| 1061 |
// passed was a configmap |
| 1062 |
attributeRecord(nil, fakeParams, admission.Create), |
| 1063 |
&admission.RuntimeObjectInterfaces{}, |
| 1064 |
) |
| 1065 |
|
| 1066 |
require.ErrorContains(t, err, `Denied`) |
| 1067 |
require.EqualValues(t, 1, compiler.getNumCompiles(&policy1)) |
| 1068 |
require.EqualValues(t, 1, evaluations1.Load()) |
| 1069 |
require.EqualValues(t, 1, compiler.getNumCompiles(&policy2)) |
| 1070 |
require.EqualValues(t, 1, evaluations2.Load()) |
| 1071 |
|
| 1072 |
// Remove param type from policy1 |
| 1073 |
// Show that policy2 evaluator is still being passed the configmaps |
| 1074 |
policy1.Spec.ParamKind = nil |
| 1075 |
policy1.ResourceVersion = "2" |
| 1076 |
|
| 1077 |
binding1.Spec.ParamRef = nil |
| 1078 |
binding1.ResourceVersion = "2" |
| 1079 |
|
| 1080 |
require.NoError(t, testContext.UpdateAndWait(&policy1, &binding1)) |
| 1081 |
|
| 1082 |
err = testContext.Plugin.Dispatch( |
| 1083 |
testContext, |
| 1084 |
// Object is irrelevant/unchecked for this test. Just test that |
| 1085 |
// the evaluator is executed, and returns admit meaning the params |
| 1086 |
// passed was a configmap |
| 1087 |
attributeRecord(nil, fakeParams, admission.Create), |
| 1088 |
&admission.RuntimeObjectInterfaces{}, |
| 1089 |
) |
| 1090 |
|
| 1091 |
require.ErrorContains(t, err, `Policy2Denied`) |
| 1092 |
require.EqualValues(t, 2, compiler.getNumCompiles(&policy1)) |
| 1093 |
require.EqualValues(t, 2, evaluations1.Load()) |
| 1094 |
require.EqualValues(t, 1, compiler.getNumCompiles(&policy2)) |
| 1095 |
require.EqualValues(t, 2, evaluations2.Load()) |
| 1096 |
} |
| 1097 |
|
| 1098 |
// Shows that we can refer to native-typed params just fine |
| 1099 |
// (as opposed to CRD params) |
| 1100 |
func TestNativeTypeParam(t *testing.T) { |
| 1101 |
compiler := &fakeCompiler{} |
| 1102 |
matcher := &fakeMatcher{ |
| 1103 |
DefaultMatch: true, |
| 1104 |
} |
| 1105 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1106 |
evaluations := atomic.Int64{} |
| 1107 |
|
| 1108 |
// Use ConfigMap native-typed param |
| 1109 |
nativeTypeParamPolicy := *denyPolicy |
| 1110 |
nativeTypeParamPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{ |
| 1111 |
APIVersion: "v1", |
| 1112 |
Kind: "ConfigMap", |
| 1113 |
} |
| 1114 |
|
| 1115 |
compiler.RegisterDefinition(&nativeTypeParamPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1116 |
evaluations.Add(1) |
| 1117 |
if _, ok := versionedParams.(*v1.ConfigMap); ok { |
| 1118 |
return validating.ValidateResult{ |
| 1119 |
Decisions: []validating.PolicyDecision{ |
| 1120 |
{ |
| 1121 |
Action: validating.ActionDeny, |
| 1122 |
Message: "correct type", |
| 1123 |
}, |
| 1124 |
}, |
| 1125 |
} |
| 1126 |
} |
| 1127 |
return validating.ValidateResult{ |
| 1128 |
Decisions: []validating.PolicyDecision{ |
| 1129 |
{ |
| 1130 |
Action: validating.ActionDeny, |
| 1131 |
Message: "Incorrect param type", |
| 1132 |
}, |
| 1133 |
}, |
| 1134 |
} |
| 1135 |
}) |
| 1136 |
|
| 1137 |
configMapParam := &v1.ConfigMap{ |
| 1138 |
TypeMeta: metav1.TypeMeta{ |
| 1139 |
APIVersion: "v1", |
| 1140 |
Kind: "ConfigMap", |
| 1141 |
}, |
| 1142 |
ObjectMeta: metav1.ObjectMeta{ |
| 1143 |
Name: "replicas-test.example.com", |
| 1144 |
Namespace: "default", |
| 1145 |
ResourceVersion: "1", |
| 1146 |
}, |
| 1147 |
Data: map[string]string{ |
| 1148 |
"coolkey": "coolvalue", |
| 1149 |
}, |
| 1150 |
} |
| 1151 |
require.NoError(t, testContext.UpdateAndWait(&nativeTypeParamPolicy, denyBinding, configMapParam)) |
| 1152 |
|
| 1153 |
err := testContext.Plugin.Dispatch( |
| 1154 |
testContext, |
| 1155 |
// Object is irrelevant/unchecked for this test. Just test that |
| 1156 |
// the evaluator is executed, and returns admit meaning the params |
| 1157 |
// passed was a configmap |
| 1158 |
attributeRecord(nil, fakeParams, admission.Create), |
| 1159 |
&admission.RuntimeObjectInterfaces{}, |
| 1160 |
) |
| 1161 |
|
| 1162 |
require.ErrorContains(t, err, "correct type") |
| 1163 |
require.EqualValues(t, 1, compiler.getNumCompiles(&nativeTypeParamPolicy)) |
| 1164 |
require.EqualValues(t, 1, evaluations.Load()) |
| 1165 |
} |
| 1166 |
|
| 1167 |
func TestAuditValidationAction(t *testing.T) { |
| 1168 |
compiler := &fakeCompiler{} |
| 1169 |
matcher := &fakeMatcher{ |
| 1170 |
DefaultMatch: true, |
| 1171 |
} |
| 1172 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1173 |
|
| 1174 |
// Push some fake |
| 1175 |
noParamSourcePolicy := *denyPolicy |
| 1176 |
noParamSourcePolicy.Spec.ParamKind = nil |
| 1177 |
|
| 1178 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1179 |
return validating.ValidateResult{ |
| 1180 |
Decisions: []validating.PolicyDecision{ |
| 1181 |
{ |
| 1182 |
Action: validating.ActionDeny, |
| 1183 |
Message: "I'm sorry Dave", |
| 1184 |
}, |
| 1185 |
}, |
| 1186 |
} |
| 1187 |
}) |
| 1188 |
|
| 1189 |
require.NoError(t, testContext.UpdateAndWait(&noParamSourcePolicy, denyBindingWithAudit)) |
| 1190 |
|
| 1191 |
attr := attributeRecord(nil, fakeParams, admission.Create) |
| 1192 |
warningRecorder := newWarningRecorder() |
| 1193 |
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder) |
| 1194 |
err := testContext.Plugin.Dispatch( |
| 1195 |
warnCtx, |
| 1196 |
attr, |
| 1197 |
&admission.RuntimeObjectInterfaces{}, |
| 1198 |
) |
| 1199 |
|
| 1200 |
require.Equal(t, 0, warningRecorder.len()) |
| 1201 |
|
| 1202 |
annotations := attr.GetAnnotations(auditinternal.LevelMetadata) |
| 1203 |
require.Len(t, annotations, 1) |
| 1204 |
valueJson, ok := annotations["validation.policy.admission.k8s.io/validation_failure"] |
| 1205 |
require.True(t, ok) |
| 1206 |
var value []validating.ValidationFailureValue |
| 1207 |
jsonErr := utiljson.Unmarshal([]byte(valueJson), &value) |
| 1208 |
require.NoError(t, jsonErr) |
| 1209 |
expected := []validating.ValidationFailureValue{{ |
| 1210 |
ExpressionIndex: 0, |
| 1211 |
Message: "I'm sorry Dave", |
| 1212 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Audit}, |
| 1213 |
Binding: "denybinding.example.com", |
| 1214 |
Policy: noParamSourcePolicy.Name, |
| 1215 |
}} |
| 1216 |
require.Equal(t, expected, value) |
| 1217 |
|
| 1218 |
require.NoError(t, err) |
| 1219 |
} |
| 1220 |
|
| 1221 |
func TestWarnValidationAction(t *testing.T) { |
| 1222 |
compiler := &fakeCompiler{} |
| 1223 |
matcher := &fakeMatcher{ |
| 1224 |
DefaultMatch: true, |
| 1225 |
} |
| 1226 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1227 |
|
| 1228 |
// Push some fake |
| 1229 |
noParamSourcePolicy := *denyPolicy |
| 1230 |
noParamSourcePolicy.Spec.ParamKind = nil |
| 1231 |
|
| 1232 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1233 |
return validating.ValidateResult{ |
| 1234 |
Decisions: []validating.PolicyDecision{ |
| 1235 |
{ |
| 1236 |
Action: validating.ActionDeny, |
| 1237 |
Message: "I'm sorry Dave", |
| 1238 |
}, |
| 1239 |
}, |
| 1240 |
} |
| 1241 |
}) |
| 1242 |
|
| 1243 |
require.NoError(t, testContext.UpdateAndWait(&noParamSourcePolicy, denyBindingWithWarn)) |
| 1244 |
|
| 1245 |
attr := attributeRecord(nil, fakeParams, admission.Create) |
| 1246 |
warningRecorder := newWarningRecorder() |
| 1247 |
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder) |
| 1248 |
err := testContext.Plugin.Dispatch( |
| 1249 |
warnCtx, |
| 1250 |
attr, |
| 1251 |
&admission.RuntimeObjectInterfaces{}, |
| 1252 |
) |
| 1253 |
|
| 1254 |
require.Equal(t, 1, warningRecorder.len()) |
| 1255 |
require.True(t, warningRecorder.hasWarning("Validation failed for ValidatingAdmissionPolicy 'denypolicy.example.com' with binding 'denybinding.example.com': I'm sorry Dave")) |
| 1256 |
|
| 1257 |
annotations := attr.GetAnnotations(auditinternal.LevelMetadata) |
| 1258 |
require.Empty(t, annotations) |
| 1259 |
|
| 1260 |
require.NoError(t, err) |
| 1261 |
} |
| 1262 |
|
| 1263 |
func TestAllValidationActions(t *testing.T) { |
| 1264 |
compiler := &fakeCompiler{} |
| 1265 |
matcher := &fakeMatcher{ |
| 1266 |
DefaultMatch: true, |
| 1267 |
} |
| 1268 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1269 |
|
| 1270 |
// Push some fake |
| 1271 |
noParamSourcePolicy := *denyPolicy |
| 1272 |
noParamSourcePolicy.Spec.ParamKind = nil |
| 1273 |
|
| 1274 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1275 |
return validating.ValidateResult{ |
| 1276 |
Decisions: []validating.PolicyDecision{ |
| 1277 |
{ |
| 1278 |
Action: validating.ActionDeny, |
| 1279 |
Message: "I'm sorry Dave", |
| 1280 |
}, |
| 1281 |
}, |
| 1282 |
} |
| 1283 |
}) |
| 1284 |
|
| 1285 |
require.NoError(t, testContext.UpdateAndWait(&noParamSourcePolicy, denyBindingWithAll)) |
| 1286 |
|
| 1287 |
attr := attributeRecord(nil, fakeParams, admission.Create) |
| 1288 |
warningRecorder := newWarningRecorder() |
| 1289 |
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder) |
| 1290 |
err := testContext.Plugin.Dispatch( |
| 1291 |
warnCtx, |
| 1292 |
attr, |
| 1293 |
&admission.RuntimeObjectInterfaces{}, |
| 1294 |
) |
| 1295 |
|
| 1296 |
require.Equal(t, 1, warningRecorder.len()) |
| 1297 |
require.True(t, warningRecorder.hasWarning("Validation failed for ValidatingAdmissionPolicy 'denypolicy.example.com' with binding 'denybinding.example.com': I'm sorry Dave")) |
| 1298 |
|
| 1299 |
annotations := attr.GetAnnotations(auditinternal.LevelMetadata) |
| 1300 |
require.Len(t, annotations, 1) |
| 1301 |
valueJson, ok := annotations["validation.policy.admission.k8s.io/validation_failure"] |
| 1302 |
require.True(t, ok) |
| 1303 |
var value []validating.ValidationFailureValue |
| 1304 |
jsonErr := utiljson.Unmarshal([]byte(valueJson), &value) |
| 1305 |
require.NoError(t, jsonErr) |
| 1306 |
expected := []validating.ValidationFailureValue{{ |
| 1307 |
ExpressionIndex: 0, |
| 1308 |
Message: "I'm sorry Dave", |
| 1309 |
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny, admissionregistrationv1.Warn, admissionregistrationv1.Audit}, |
| 1310 |
Binding: "denybinding.example.com", |
| 1311 |
Policy: noParamSourcePolicy.Name, |
| 1312 |
}} |
| 1313 |
require.Equal(t, expected, value) |
| 1314 |
|
| 1315 |
require.ErrorContains(t, err, "I'm sorry Dave") |
| 1316 |
} |
| 1317 |
|
| 1318 |
func TestNamespaceParamRefName(t *testing.T) { |
| 1319 |
compiler := &fakeCompiler{} |
| 1320 |
matcher := &fakeMatcher{ |
| 1321 |
DefaultMatch: true, |
| 1322 |
} |
| 1323 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1324 |
|
| 1325 |
evaluations := atomic.Int64{} |
| 1326 |
|
| 1327 |
// Use ConfigMap native-typed param |
| 1328 |
nativeTypeParamPolicy := *denyPolicy |
| 1329 |
nativeTypeParamPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{ |
| 1330 |
APIVersion: "v1", |
| 1331 |
Kind: "ConfigMap", |
| 1332 |
} |
| 1333 |
|
| 1334 |
namespaceParamBinding := *denyBinding |
| 1335 |
namespaceParamBinding.Spec.ParamRef = &admissionregistrationv1.ParamRef{ |
| 1336 |
Name: "replicas-test.example.com", |
| 1337 |
} |
| 1338 |
lock := sync.Mutex{} |
| 1339 |
observedParamNamespaces := []string{} |
| 1340 |
compiler.RegisterDefinition(&nativeTypeParamPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1341 |
lock.Lock() |
| 1342 |
defer lock.Unlock() |
| 1343 |
|
| 1344 |
evaluations.Add(1) |
| 1345 |
if p, ok := versionedParams.(*v1.ConfigMap); ok { |
| 1346 |
observedParamNamespaces = append(observedParamNamespaces, p.Namespace) |
| 1347 |
return validating.ValidateResult{ |
| 1348 |
Decisions: []validating.PolicyDecision{ |
| 1349 |
{ |
| 1350 |
Action: validating.ActionDeny, |
| 1351 |
Message: "correct type", |
| 1352 |
}, |
| 1353 |
}, |
| 1354 |
} |
| 1355 |
} |
| 1356 |
return validating.ValidateResult{ |
| 1357 |
Decisions: []validating.PolicyDecision{ |
| 1358 |
{ |
| 1359 |
Action: validating.ActionDeny, |
| 1360 |
Message: "Incorrect param type", |
| 1361 |
}, |
| 1362 |
}, |
| 1363 |
} |
| 1364 |
}) |
| 1365 |
|
| 1366 |
configMapParam := &v1.ConfigMap{ |
| 1367 |
TypeMeta: metav1.TypeMeta{ |
| 1368 |
APIVersion: "v1", |
| 1369 |
Kind: "ConfigMap", |
| 1370 |
}, |
| 1371 |
ObjectMeta: metav1.ObjectMeta{ |
| 1372 |
Name: "replicas-test.example.com", |
| 1373 |
Namespace: "default", |
| 1374 |
ResourceVersion: "1", |
| 1375 |
}, |
| 1376 |
Data: map[string]string{ |
| 1377 |
"coolkey": "default", |
| 1378 |
}, |
| 1379 |
} |
| 1380 |
configMapParam2 := &v1.ConfigMap{ |
| 1381 |
TypeMeta: metav1.TypeMeta{ |
| 1382 |
APIVersion: "v1", |
| 1383 |
Kind: "ConfigMap", |
| 1384 |
}, |
| 1385 |
ObjectMeta: metav1.ObjectMeta{ |
| 1386 |
Name: "replicas-test.example.com", |
| 1387 |
Namespace: "mynamespace", |
| 1388 |
ResourceVersion: "1", |
| 1389 |
}, |
| 1390 |
Data: map[string]string{ |
| 1391 |
"coolkey": "mynamespace", |
| 1392 |
}, |
| 1393 |
} |
| 1394 |
configMapParam3 := &v1.ConfigMap{ |
| 1395 |
TypeMeta: metav1.TypeMeta{ |
| 1396 |
APIVersion: "v1", |
| 1397 |
Kind: "ConfigMap", |
| 1398 |
}, |
| 1399 |
ObjectMeta: metav1.ObjectMeta{ |
| 1400 |
Name: "replicas-test.example.com", |
| 1401 |
Namespace: "othernamespace", |
| 1402 |
ResourceVersion: "1", |
| 1403 |
}, |
| 1404 |
Data: map[string]string{ |
| 1405 |
"coolkey": "othernamespace", |
| 1406 |
}, |
| 1407 |
} |
| 1408 |
require.NoError(t, testContext.UpdateAndWait(&nativeTypeParamPolicy, &namespaceParamBinding, configMapParam, configMapParam2, configMapParam3)) |
| 1409 |
|
| 1410 |
// Object is irrelevant/unchecked for this test. Just test that |
| 1411 |
// the evaluator is executed with correct namespace, and returns admit |
| 1412 |
// meaning the params passed was a configmap |
| 1413 |
err := testContext.Plugin.Dispatch( |
| 1414 |
testContext, |
| 1415 |
attributeRecord(nil, configMapParam, admission.Create), |
| 1416 |
&admission.RuntimeObjectInterfaces{}, |
| 1417 |
) |
| 1418 |
|
| 1419 |
func() { |
| 1420 |
lock.Lock() |
| 1421 |
defer lock.Unlock() |
| 1422 |
require.ErrorContains(t, err, "correct type") |
| 1423 |
require.EqualValues(t, 1, compiler.getNumCompiles(&nativeTypeParamPolicy)) |
| 1424 |
require.EqualValues(t, 1, evaluations.Load()) |
| 1425 |
}() |
| 1426 |
|
| 1427 |
err = testContext.Plugin.Dispatch( |
| 1428 |
testContext, |
| 1429 |
attributeRecord(nil, configMapParam2, admission.Create), |
| 1430 |
&admission.RuntimeObjectInterfaces{}, |
| 1431 |
) |
| 1432 |
|
| 1433 |
func() { |
| 1434 |
lock.Lock() |
| 1435 |
defer lock.Unlock() |
| 1436 |
require.ErrorContains(t, err, "correct type") |
| 1437 |
require.EqualValues(t, 1, compiler.getNumCompiles(&nativeTypeParamPolicy)) |
| 1438 |
require.EqualValues(t, 2, evaluations.Load()) |
| 1439 |
}() |
| 1440 |
|
| 1441 |
err = testContext.Plugin.Dispatch( |
| 1442 |
testContext, |
| 1443 |
attributeRecord(nil, configMapParam3, admission.Create), |
| 1444 |
&admission.RuntimeObjectInterfaces{}, |
| 1445 |
) |
| 1446 |
|
| 1447 |
func() { |
| 1448 |
lock.Lock() |
| 1449 |
defer lock.Unlock() |
| 1450 |
require.ErrorContains(t, err, "correct type") |
| 1451 |
require.EqualValues(t, 1, compiler.getNumCompiles(&nativeTypeParamPolicy)) |
| 1452 |
require.EqualValues(t, 3, evaluations.Load()) |
| 1453 |
}() |
| 1454 |
|
| 1455 |
err = testContext.Plugin.Dispatch( |
| 1456 |
testContext, |
| 1457 |
attributeRecord(nil, configMapParam, admission.Create), |
| 1458 |
&admission.RuntimeObjectInterfaces{}, |
| 1459 |
) |
| 1460 |
|
| 1461 |
func() { |
| 1462 |
lock.Lock() |
| 1463 |
defer lock.Unlock() |
| 1464 |
require.ErrorContains(t, err, "correct type") |
| 1465 |
require.EqualValues(t, []string{"default", "mynamespace", "othernamespace", "default"}, observedParamNamespaces) |
| 1466 |
require.EqualValues(t, 1, compiler.getNumCompiles(&nativeTypeParamPolicy)) |
| 1467 |
require.EqualValues(t, 4, evaluations.Load()) |
| 1468 |
}() |
| 1469 |
} |
| 1470 |
|
| 1471 |
func TestParamRef(t *testing.T) { |
| 1472 |
for _, paramIsClusterScoped := range []bool{false, true} { |
| 1473 |
for _, nameIsSet := range []bool{false, true} { |
| 1474 |
for _, namespaceIsSet := range []bool{false, true} { |
| 1475 |
if paramIsClusterScoped && namespaceIsSet { |
| 1476 |
// Skip invalid configuration |
| 1477 |
continue |
| 1478 |
} |
| 1479 |
|
| 1480 |
for _, selectorIsSet := range []bool{false, true} { |
| 1481 |
if selectorIsSet && nameIsSet { |
| 1482 |
// SKip invalid configuration |
| 1483 |
continue |
| 1484 |
} |
| 1485 |
|
| 1486 |
for _, denyNotFound := range []bool{false, true} { |
| 1487 |
|
| 1488 |
name := "ParamRef" |
| 1489 |
|
| 1490 |
if paramIsClusterScoped { |
| 1491 |
name = "ClusterScoped" + name |
| 1492 |
} |
| 1493 |
|
| 1494 |
if nameIsSet { |
| 1495 |
name = name + "WithName" |
| 1496 |
} else if selectorIsSet { |
| 1497 |
name = name + "WithLabelSelector" |
| 1498 |
} else { |
| 1499 |
name = name + "WithEverythingSelector" |
| 1500 |
} |
| 1501 |
|
| 1502 |
if namespaceIsSet { |
| 1503 |
name = name + "WithNamespace" |
| 1504 |
} |
| 1505 |
|
| 1506 |
if denyNotFound { |
| 1507 |
name = name + "DenyNotFound" |
| 1508 |
} else { |
| 1509 |
name = name + "AllowNotFound" |
| 1510 |
} |
| 1511 |
|
| 1512 |
t.Run(name, func(t *testing.T) { |
| 1513 |
t.Parallel() |
| 1514 |
// Test creating a policy with a cluster or namesapce-scoped param |
| 1515 |
// and binding with the provided configuration. Test will ensure |
| 1516 |
// that the provided configuration is capable of matching |
| 1517 |
// params as expected, and not matching params when not expected. |
| 1518 |
// Also ensures the NotFound setting works as expected with this particular |
| 1519 |
// configuration of ParamRef when all the previously |
| 1520 |
// matched params are deleted. |
| 1521 |
testParamRefCase(t, paramIsClusterScoped, nameIsSet, namespaceIsSet, selectorIsSet, denyNotFound) |
| 1522 |
}) |
| 1523 |
} |
| 1524 |
} |
| 1525 |
} |
| 1526 |
} |
| 1527 |
} |
| 1528 |
} |
| 1529 |
|
| 1530 |
// testParamRefCase constructs a ParamRef and policy with appropriate ParamKind |
| 1531 |
// for the given parameters, then constructs a scenario with several matching/non-matching params |
| 1532 |
// of varying names, namespaces, labels. |
| 1533 |
// |
| 1534 |
// Test then selects subset of params that should match provided configuration |
| 1535 |
// and ensuers those params are the only ones used. |
| 1536 |
// |
| 1537 |
// Also ensures NotFound action is enforced correctly by deleting all found |
| 1538 |
// params and ensuring the Action is used. |
| 1539 |
// |
| 1540 |
// This test is not meant to test every possible scenario of matching/not matching: |
| 1541 |
// only that each ParamRef CAN be evaluated correctly for both cluster scoped |
| 1542 |
// and namespace-scoped request kinds, and that the failure action is correctly |
| 1543 |
// applied. |
| 1544 |
func testParamRefCase(t *testing.T, paramIsClusterScoped, nameIsSet, namespaceIsSet, selectorIsSet, denyNotFound bool) { |
| 1545 |
// Create a cluster scoped and a namespace scoped CRD |
| 1546 |
policy := *denyPolicy |
| 1547 |
binding := *denyBinding |
| 1548 |
binding.Spec.ParamRef = &admissionregistrationv1.ParamRef{} |
| 1549 |
paramRef := binding.Spec.ParamRef |
| 1550 |
|
| 1551 |
shouldErrorOnClusterScopedRequests := !namespaceIsSet && !paramIsClusterScoped |
| 1552 |
|
| 1553 |
matchingParamName := "replicas-test.example.com" |
| 1554 |
matchingNamespace := "mynamespace" |
| 1555 |
nonMatchingNamespace := "othernamespace" |
| 1556 |
|
| 1557 |
matchingLabels := labels.Set{"doesitmatch": "yes"} |
| 1558 |
nonmatchingLabels := labels.Set{"doesitmatch": "no"} |
| 1559 |
otherNonmatchingLabels := labels.Set{"notaffiliated": "no"} |
| 1560 |
|
| 1561 |
if paramIsClusterScoped { |
| 1562 |
policy.Spec.ParamKind = &admissionregistrationv1.ParamKind{ |
| 1563 |
APIVersion: clusterScopedParamsGVK.GroupVersion().String(), |
| 1564 |
Kind: clusterScopedParamsGVK.Kind, |
| 1565 |
} |
| 1566 |
} else { |
| 1567 |
policy.Spec.ParamKind = &admissionregistrationv1.ParamKind{ |
| 1568 |
APIVersion: paramsGVK.GroupVersion().String(), |
| 1569 |
Kind: paramsGVK.Kind, |
| 1570 |
} |
| 1571 |
} |
| 1572 |
|
| 1573 |
if nameIsSet { |
| 1574 |
paramRef.Name = matchingParamName |
| 1575 |
} else if selectorIsSet { |
| 1576 |
paramRef.Selector = metav1.SetAsLabelSelector(matchingLabels) |
| 1577 |
} else { |
| 1578 |
paramRef.Selector = &metav1.LabelSelector{} |
| 1579 |
} |
| 1580 |
|
| 1581 |
if namespaceIsSet { |
| 1582 |
paramRef.Namespace = matchingNamespace |
| 1583 |
} |
| 1584 |
|
| 1585 |
if denyNotFound { |
| 1586 |
paramRef.ParameterNotFoundAction = ptrTo(admissionregistrationv1.DenyAction) |
| 1587 |
} else { |
| 1588 |
paramRef.ParameterNotFoundAction = ptrTo(admissionregistrationv1.AllowAction) |
| 1589 |
} |
| 1590 |
|
| 1591 |
compiler := &fakeCompiler{} |
| 1592 |
matcher := &fakeMatcher{ |
| 1593 |
DefaultMatch: true, |
| 1594 |
} |
| 1595 |
|
| 1596 |
var matchedParams []runtime.Object |
| 1597 |
paramLock := sync.Mutex{} |
| 1598 |
observeParam := func(p runtime.Object) { |
| 1599 |
paramLock.Lock() |
| 1600 |
defer paramLock.Unlock() |
| 1601 |
matchedParams = append(matchedParams, p) |
| 1602 |
} |
| 1603 |
getAndResetObservedParams := func() []runtime.Object { |
| 1604 |
paramLock.Lock() |
| 1605 |
defer paramLock.Unlock() |
| 1606 |
oldParams := matchedParams |
| 1607 |
matchedParams = nil |
| 1608 |
return oldParams |
| 1609 |
} |
| 1610 |
|
| 1611 |
compiler.RegisterDefinition(&policy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1612 |
observeParam(versionedParams) |
| 1613 |
return validating.ValidateResult{ |
| 1614 |
Decisions: []validating.PolicyDecision{ |
| 1615 |
{ |
| 1616 |
Action: validating.ActionDeny, |
| 1617 |
Message: "Denied by policy", |
| 1618 |
}, |
| 1619 |
}, |
| 1620 |
} |
| 1621 |
}) |
| 1622 |
|
| 1623 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1624 |
|
| 1625 |
// Create library of params to try to fool the controller |
| 1626 |
params := []*unstructured.Unstructured{ |
| 1627 |
newParam(matchingParamName, v1.NamespaceDefault, nonmatchingLabels), |
| 1628 |
newParam(matchingParamName, matchingNamespace, nonmatchingLabels), |
| 1629 |
newParam(matchingParamName, nonMatchingNamespace, nonmatchingLabels), |
| 1630 |
|
| 1631 |
newParam(matchingParamName+"1", v1.NamespaceDefault, matchingLabels), |
| 1632 |
newParam(matchingParamName+"1", matchingNamespace, matchingLabels), |
| 1633 |
newParam(matchingParamName+"1", nonMatchingNamespace, matchingLabels), |
| 1634 |
|
| 1635 |
newParam(matchingParamName+"2", v1.NamespaceDefault, otherNonmatchingLabels), |
| 1636 |
newParam(matchingParamName+"2", matchingNamespace, otherNonmatchingLabels), |
| 1637 |
newParam(matchingParamName+"2", nonMatchingNamespace, otherNonmatchingLabels), |
| 1638 |
|
| 1639 |
newParam(matchingParamName+"3", v1.NamespaceDefault, otherNonmatchingLabels), |
| 1640 |
newParam(matchingParamName+"3", matchingNamespace, matchingLabels), |
| 1641 |
newParam(matchingParamName+"3", nonMatchingNamespace, matchingLabels), |
| 1642 |
|
| 1643 |
newClusterScopedParam(matchingParamName, matchingLabels), |
| 1644 |
newClusterScopedParam(matchingParamName+"1", nonmatchingLabels), |
| 1645 |
newClusterScopedParam(matchingParamName+"2", otherNonmatchingLabels), |
| 1646 |
newClusterScopedParam(matchingParamName+"3", matchingLabels), |
| 1647 |
newClusterScopedParam(matchingParamName+"4", nonmatchingLabels), |
| 1648 |
newClusterScopedParam(matchingParamName+"5", otherNonmatchingLabels), |
| 1649 |
} |
| 1650 |
|
| 1651 |
for _, p := range params { |
| 1652 |
// Don't wait for these sync the informers would not have been |
| 1653 |
// created unless bound to a policy |
| 1654 |
require.NoError(t, testContext.Update(p)) |
| 1655 |
} |
| 1656 |
|
| 1657 |
require.NoError(t, testContext.UpdateAndWait(&policy, &binding)) |
| 1658 |
|
| 1659 |
namespacedRequestObject := newParam("some param", nonMatchingNamespace, nil) |
| 1660 |
clusterScopedRequestObject := newClusterScopedParam("other param", nil) |
| 1661 |
|
| 1662 |
// Validate a namespaced object, and verify that the params being validated |
| 1663 |
// are the ones we would expect |
| 1664 |
timeoutCtx, timeoutCancel := context.WithTimeout(testContext, 5*time.Second) |
| 1665 |
defer timeoutCancel() |
| 1666 |
var expectedParamsForNamespacedRequest []*unstructured.Unstructured |
| 1667 |
for _, p := range params { |
| 1668 |
if p.GetAPIVersion() != policy.Spec.ParamKind.APIVersion || p.GetKind() != policy.Spec.ParamKind.Kind { |
| 1669 |
continue |
| 1670 |
} else if len(paramRef.Name) > 0 && p.GetName() != paramRef.Name { |
| 1671 |
continue |
| 1672 |
} else if len(paramRef.Namespace) > 0 && p.GetNamespace() != paramRef.Namespace { |
| 1673 |
continue |
| 1674 |
} |
| 1675 |
|
| 1676 |
if !paramIsClusterScoped { |
| 1677 |
// If the paramRef has empty namespace and the kind is |
| 1678 |
// namespaced-scoped, then it only matches params of the same |
| 1679 |
// namespace |
| 1680 |
if len(paramRef.Namespace) == 0 && p.GetNamespace() != namespacedRequestObject.GetNamespace() { |
| 1681 |
continue |
| 1682 |
} |
| 1683 |
} |
| 1684 |
|
| 1685 |
if paramRef.Selector != nil { |
| 1686 |
ls := p.GetLabels() |
| 1687 |
matched := true |
| 1688 |
|
| 1689 |
for k, v := range paramRef.Selector.MatchLabels { |
| 1690 |
if l, hasLabel := ls[k]; !hasLabel { |
| 1691 |
matched = false |
| 1692 |
break |
| 1693 |
} else if l != v { |
| 1694 |
matched = false |
| 1695 |
break |
| 1696 |
} |
| 1697 |
} |
| 1698 |
|
| 1699 |
// Empty selector matches everything |
| 1700 |
if len(paramRef.Selector.MatchExpressions) == 0 && len(paramRef.Selector.MatchLabels) == 0 { |
| 1701 |
matched = true |
| 1702 |
} |
| 1703 |
|
| 1704 |
if !matched { |
| 1705 |
continue |
| 1706 |
} |
| 1707 |
} |
| 1708 |
|
| 1709 |
expectedParamsForNamespacedRequest = append(expectedParamsForNamespacedRequest, p) |
| 1710 |
require.NoError(t, testContext.WaitForReconcile(timeoutCtx, p)) |
| 1711 |
} |
| 1712 |
require.NotEmpty(t, expectedParamsForNamespacedRequest, "all test cases should match at least one param") |
| 1713 |
require.ErrorContains(t, testContext.Plugin.Dispatch(context.TODO(), attributeRecord(nil, namespacedRequestObject, admission.Create), &admission.RuntimeObjectInterfaces{}), "Denied by policy") |
| 1714 |
require.ElementsMatch(t, expectedParamsForNamespacedRequest, getAndResetObservedParams(), "should exactly match expected params") |
| 1715 |
|
| 1716 |
// Validate a cluster-scoped object, and verify that the params being validated |
| 1717 |
// are the ones we would expect |
| 1718 |
var expectedParamsForClusterScopedRequest []*unstructured.Unstructured |
| 1719 |
timeoutCtx, timeoutCancel = context.WithTimeout(testContext, 5*time.Second) |
| 1720 |
defer timeoutCancel() |
| 1721 |
for _, p := range params { |
| 1722 |
if shouldErrorOnClusterScopedRequests { |
| 1723 |
continue |
| 1724 |
} else if p.GetAPIVersion() != policy.Spec.ParamKind.APIVersion || p.GetKind() != policy.Spec.ParamKind.Kind { |
| 1725 |
continue |
| 1726 |
} else if len(paramRef.Name) > 0 && p.GetName() != paramRef.Name { |
| 1727 |
continue |
| 1728 |
} else if len(paramRef.Namespace) > 0 && p.GetNamespace() != paramRef.Namespace { |
| 1729 |
continue |
| 1730 |
} else if !paramIsClusterScoped && len(paramRef.Namespace) == 0 && p.GetNamespace() != v1.NamespaceDefault { |
| 1731 |
continue |
| 1732 |
} |
| 1733 |
|
| 1734 |
if paramRef.Selector != nil { |
| 1735 |
ls := p.GetLabels() |
| 1736 |
matched := true |
| 1737 |
for k, v := range paramRef.Selector.MatchLabels { |
| 1738 |
if l, hasLabel := ls[k]; !hasLabel { |
| 1739 |
matched = false |
| 1740 |
break |
| 1741 |
} else if l != v { |
| 1742 |
matched = false |
| 1743 |
break |
| 1744 |
} |
| 1745 |
} |
| 1746 |
|
| 1747 |
// Empty selector matches everything |
| 1748 |
if len(paramRef.Selector.MatchExpressions) == 0 && len(paramRef.Selector.MatchLabels) == 0 { |
| 1749 |
matched = true |
| 1750 |
} |
| 1751 |
|
| 1752 |
if !matched { |
| 1753 |
continue |
| 1754 |
} |
| 1755 |
} |
| 1756 |
|
| 1757 |
expectedParamsForClusterScopedRequest = append(expectedParamsForClusterScopedRequest, p) |
| 1758 |
require.NoError(t, testContext.WaitForReconcile(timeoutCtx, p)) |
| 1759 |
|
| 1760 |
} |
| 1761 |
|
| 1762 |
err := testContext.Plugin.Dispatch(context.TODO(), attributeRecord(nil, clusterScopedRequestObject, admission.Create), &admission.RuntimeObjectInterfaces{}) |
| 1763 |
if shouldErrorOnClusterScopedRequests { |
| 1764 |
// Cannot validate cliuster-scoped resources against a paramRef that sets namespace |
| 1765 |
require.ErrorContains(t, err, "failed to configure binding: cannot use namespaced paramRef in policy binding that matches cluster-scoped resources") |
| 1766 |
} else { |
| 1767 |
require.NotEmpty(t, expectedParamsForClusterScopedRequest, "all test cases should match at least one param") |
| 1768 |
require.ErrorContains(t, err, "Denied by policy") |
| 1769 |
} |
| 1770 |
require.ElementsMatch(t, expectedParamsForClusterScopedRequest, getAndResetObservedParams(), "should exactly match expected params") |
| 1771 |
|
| 1772 |
// Remove all params matched by namespaced, and cluster-scoped validation. |
| 1773 |
// Validate again to make sure NotFoundAction is respected |
| 1774 |
var deleted []runtime.Object |
| 1775 |
for _, p := range expectedParamsForNamespacedRequest { |
| 1776 |
deleted = append(deleted, p) |
| 1777 |
} |
| 1778 |
|
| 1779 |
for _, p := range expectedParamsForClusterScopedRequest { |
| 1780 |
deleted = append(deleted, p) |
| 1781 |
} |
| 1782 |
|
| 1783 |
require.NoError(t, testContext.DeleteAndWait(deleted...)) |
| 1784 |
|
| 1785 |
// Check that NotFound is working correctly for both namespaeed & non-namespaced |
| 1786 |
// request object |
| 1787 |
err = testContext.Plugin.Dispatch(context.TODO(), attributeRecord(nil, namespacedRequestObject, admission.Create), &admission.RuntimeObjectInterfaces{}) |
| 1788 |
if denyNotFound { |
| 1789 |
require.ErrorContains(t, err, "no params found for policy binding with `Deny` parameterNotFoundAction") |
| 1790 |
} else { |
| 1791 |
require.NoError(t, err, "Allow not found expects no error when no params found. Policy should have been skipped") |
| 1792 |
} |
| 1793 |
require.Empty(t, getAndResetObservedParams(), "policy should not have been evaluated") |
| 1794 |
|
| 1795 |
err = testContext.Plugin.Dispatch(context.TODO(), attributeRecord(nil, clusterScopedRequestObject, admission.Create), &admission.RuntimeObjectInterfaces{}) |
| 1796 |
if shouldErrorOnClusterScopedRequests { |
| 1797 |
require.ErrorContains(t, err, "failed to configure binding: cannot use namespaced paramRef in policy binding that matches cluster-scoped resources") |
| 1798 |
|
| 1799 |
} else if denyNotFound { |
| 1800 |
require.ErrorContains(t, err, "no params found for policy binding with `Deny` parameterNotFoundAction") |
| 1801 |
} else { |
| 1802 |
require.NoError(t, err, "Allow not found expects no error when no params found. Policy should have been skipped") |
| 1803 |
} |
| 1804 |
require.Empty(t, getAndResetObservedParams(), "policy should not have been evaluated") |
| 1805 |
} |
| 1806 |
|
| 1807 |
// If the ParamKind is ClusterScoped, and namespace param is used. |
| 1808 |
// This is a Configuration Error of the policy |
| 1809 |
func TestNamespaceParamRefClusterScopedParamError(t *testing.T) { |
| 1810 |
compiler := &fakeCompiler{} |
| 1811 |
matcher := &fakeMatcher{ |
| 1812 |
DefaultMatch: true, |
| 1813 |
} |
| 1814 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1815 |
|
| 1816 |
evaluations := atomic.Int64{} |
| 1817 |
|
| 1818 |
// Use ValidatingAdmissionPolicy for param type since it is cluster-scoped |
| 1819 |
nativeTypeParamPolicy := *denyPolicy |
| 1820 |
nativeTypeParamPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{ |
| 1821 |
APIVersion: "admissionregistration.k8s.io/v1beta1", |
| 1822 |
Kind: "ValidatingAdmissionPolicy", |
| 1823 |
} |
| 1824 |
|
| 1825 |
namespaceParamBinding := *denyBinding |
| 1826 |
namespaceParamBinding.Spec.ParamRef = &admissionregistrationv1.ParamRef{ |
| 1827 |
Name: "other-param-to-use-with-no-label.example.com", |
| 1828 |
Namespace: "mynamespace", |
| 1829 |
} |
| 1830 |
|
| 1831 |
compiler.RegisterDefinition(&nativeTypeParamPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1832 |
evaluations.Add(1) |
| 1833 |
if _, ok := versionedParams.(*admissionregistrationv1.ValidatingAdmissionPolicy); ok { |
| 1834 |
return validating.ValidateResult{ |
| 1835 |
Decisions: []validating.PolicyDecision{ |
| 1836 |
{ |
| 1837 |
Action: validating.ActionAdmit, |
| 1838 |
Message: "correct type", |
| 1839 |
}, |
| 1840 |
}, |
| 1841 |
} |
| 1842 |
} |
| 1843 |
return validating.ValidateResult{ |
| 1844 |
Decisions: []validating.PolicyDecision{ |
| 1845 |
{ |
| 1846 |
Action: validating.ActionDeny, |
| 1847 |
Message: fmt.Sprintf("Incorrect param type %T", versionedParams), |
| 1848 |
}, |
| 1849 |
}, |
| 1850 |
} |
| 1851 |
}) |
| 1852 |
|
| 1853 |
require.NoError(t, testContext.UpdateAndWait(&nativeTypeParamPolicy, &namespaceParamBinding)) |
| 1854 |
|
| 1855 |
// Object is irrelevant/unchecked for this test. Just test that |
| 1856 |
// the evaluator is executed with correct namespace, and returns admit |
| 1857 |
// meaning the params passed was a configmap |
| 1858 |
err := testContext.Plugin.Dispatch( |
| 1859 |
testContext, |
| 1860 |
attributeRecord(nil, fakeParams, admission.Create), |
| 1861 |
&admission.RuntimeObjectInterfaces{}, |
| 1862 |
) |
| 1863 |
|
| 1864 |
require.ErrorContains(t, err, "paramRef.namespace must not be provided for a cluster-scoped `paramKind`") |
| 1865 |
require.EqualValues(t, 1, compiler.getNumCompiles(&nativeTypeParamPolicy)) |
| 1866 |
require.EqualValues(t, 0, evaluations.Load()) |
| 1867 |
} |
| 1868 |
|
| 1869 |
func TestAuditAnnotations(t *testing.T) { |
| 1870 |
compiler := &fakeCompiler{} |
| 1871 |
matcher := &fakeMatcher{ |
| 1872 |
DefaultMatch: true, |
| 1873 |
} |
| 1874 |
testContext := setupFakeTest(t, compiler, matcher) |
| 1875 |
|
| 1876 |
// Push some fake |
| 1877 |
policy := *denyPolicy |
| 1878 |
compiler.RegisterDefinition(denyPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult { |
| 1879 |
o, err := meta.Accessor(versionedParams) |
| 1880 |
if err != nil { |
| 1881 |
t.Fatal(err) |
| 1882 |
} |
| 1883 |
exampleValue := "normal-value" |
| 1884 |
if o.GetName() == "replicas-test2.example.com" { |
| 1885 |
exampleValue = "special-value" |
| 1886 |
} |
| 1887 |
return validating.ValidateResult{ |
| 1888 |
AuditAnnotations: []validating.PolicyAuditAnnotation{ |
| 1889 |
{ |
| 1890 |
Key: "example-key", |
| 1891 |
Value: exampleValue, |
| 1892 |
Action: validating.AuditAnnotationActionPublish, |
| 1893 |
}, |
| 1894 |
{ |
| 1895 |
Key: "excluded-key", |
| 1896 |
Value: "excluded-value", |
| 1897 |
Action: validating.AuditAnnotationActionExclude, |
| 1898 |
}, |
| 1899 |
{ |
| 1900 |
Key: "error-key", |
| 1901 |
Action: validating.AuditAnnotationActionError, |
| 1902 |
Error: "example error", |
| 1903 |
}, |
| 1904 |
}, |
| 1905 |
} |
| 1906 |
}) |
| 1907 |
|
| 1908 |
fakeParams2 := fakeParams.DeepCopy() |
| 1909 |
fakeParams2.SetName("replicas-test2.example.com") |
| 1910 |
denyBinding2 := denyBinding.DeepCopy() |
| 1911 |
denyBinding2.SetName("denybinding2.example.com") |
| 1912 |
denyBinding2.Spec.ParamRef.Name = fakeParams2.GetName() |
| 1913 |
|
| 1914 |
fakeParams3 := fakeParams.DeepCopy() |
| 1915 |
fakeParams3.SetName("replicas-test3.example.com") |
| 1916 |
denyBinding3 := denyBinding.DeepCopy() |
| 1917 |
denyBinding3.SetName("denybinding3.example.com") |
| 1918 |
denyBinding3.Spec.ParamRef.Name = fakeParams3.GetName() |
| 1919 |
|
| 1920 |
require.NoError(t, testContext.UpdateAndWait(fakeParams, fakeParams2, fakeParams3, &policy, denyBinding, denyBinding2, denyBinding3)) |
| 1921 |
|
| 1922 |
attr := attributeRecord(nil, fakeParams, admission.Create) |
| 1923 |
err := testContext.Plugin.Dispatch( |
| 1924 |
testContext, |
| 1925 |
attr, |
| 1926 |
&admission.RuntimeObjectInterfaces{}, |
| 1927 |
) |
| 1928 |
|
| 1929 |
annotations := attr.GetAnnotations(auditinternal.LevelMetadata) |
| 1930 |
require.Len(t, annotations, 1) |
| 1931 |
value := annotations[policy.Name+"/example-key"] |
| 1932 |
parts := strings.Split(value, ", ") |
| 1933 |
require.Len(t, parts, 2) |
| 1934 |
require.Contains(t, parts, "normal-value", "special-value") |
| 1935 |
|
| 1936 |
require.ErrorContains(t, err, "example error") |
| 1937 |
} |
| 1938 |
|
| 1939 |
// FakeAttributes decorates admission.Attributes. It's used to trace the added annotations. |
| 1940 |
type FakeAttributes struct { |
| 1941 |
admission.Attributes |
| 1942 |
annotations map[string]string |
| 1943 |
mutex sync.Mutex |
| 1944 |
} |
| 1945 |
|
| 1946 |
// AddAnnotation adds an annotation key value pair to FakeAttributes |
| 1947 |
func (f *FakeAttributes) AddAnnotation(k, v string) error { |
| 1948 |
return f.AddAnnotationWithLevel(k, v, auditinternal.LevelMetadata) |
| 1949 |
} |
| 1950 |
|
| 1951 |
// AddAnnotationWithLevel adds an annotation key value pair to FakeAttributes |
| 1952 |
func (f *FakeAttributes) AddAnnotationWithLevel(k, v string, _ auditinternal.Level) error { |
| 1953 |
f.mutex.Lock() |
| 1954 |
defer f.mutex.Unlock() |
| 1955 |
if err := f.Attributes.AddAnnotation(k, v); err != nil { |
| 1956 |
return err |
| 1957 |
} |
| 1958 |
if f.annotations == nil { |
| 1959 |
f.annotations = make(map[string]string) |
| 1960 |
} |
| 1961 |
f.annotations[k] = v |
| 1962 |
return nil |
| 1963 |
} |
| 1964 |
|
| 1965 |
// GetAnnotations reads annotations from FakeAttributes |
| 1966 |
func (f *FakeAttributes) GetAnnotations(_ auditinternal.Level) map[string]string { |
| 1967 |
f.mutex.Lock() |
| 1968 |
defer f.mutex.Unlock() |
| 1969 |
annotations := make(map[string]string, len(f.annotations)) |
| 1970 |
for k, v := range f.annotations { |
| 1971 |
annotations[k] = v |
| 1972 |
} |
| 1973 |
return annotations |
| 1974 |
} |
| 1975 |
|
| 1976 |
type warningRecorder struct { |
| 1977 |
sync.Mutex |
| 1978 |
warnings sets.Set[string] |
| 1979 |
} |
| 1980 |
|
| 1981 |
func newWarningRecorder() *warningRecorder { |
| 1982 |
return &warningRecorder{warnings: sets.New[string]()} |
| 1983 |
} |
| 1984 |
|
| 1985 |
func (r *warningRecorder) AddWarning(_, text string) { |
| 1986 |
r.Lock() |
| 1987 |
defer r.Unlock() |
| 1988 |
r.warnings.Insert(text) |
| 1989 |
return |
| 1990 |
} |
| 1991 |
|
| 1992 |
func (r *warningRecorder) hasWarning(text string) bool { |
| 1993 |
r.Lock() |
| 1994 |
defer r.Unlock() |
| 1995 |
return r.warnings.Has(text) |
| 1996 |
} |
| 1997 |
|
| 1998 |
func (r *warningRecorder) len() int { |
| 1999 |
r.Lock() |
| 2000 |
defer r.Unlock() |
| 2001 |
return len(r.warnings) |
| 2002 |
} |