-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidation.go
275 lines (249 loc) · 9.53 KB
/
validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
Copyright 2024 Preferred Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kaptest
import (
"context"
"fmt"
"reflect"
v1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/plugin/cel"
"k8s.io/apiserver/pkg/admission/plugin/policy/validating"
"k8s.io/apiserver/pkg/admission/plugin/webhook/matchconditions"
celconfig "k8s.io/apiserver/pkg/apis/cel"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/cel/environment"
)
// ValidatorInterface is an interface to evaluate ValidatingAdmissionPolicy.
type ValidatorInterface interface {
EvalMatchCondition(p ValidationParams) *matchconditions.MatchResult
Validate(p ValidationParams) (*validating.ValidateResult, error)
}
type Validator struct {
policy *v1.ValidatingAdmissionPolicy
validator validating.Validator
matcher matchconditions.Matcher
}
var _ ValidatorInterface = &Validator{}
// ValidationParams contains the parameters required to evaluate a ValidatingAdmissionPolicy.
type ValidationParams struct {
Object runtime.Object
OldObject runtime.Object
ParamObj runtime.Object
NamespaceObj *corev1.Namespace
UserInfo user.Info
}
func (p ValidationParams) Operation() admission.Operation {
if p.Object != nil && p.OldObject != nil {
return admission.Update
}
if p.Object != nil {
return admission.Create
}
return admission.Delete
}
// NewValidator compiles the provided ValidatingAdmissionPolicy and generates Validator.
func NewValidator(policy *v1.ValidatingAdmissionPolicy) *Validator {
v, m := compilePolicy(policy)
return &Validator{validator: v, policy: policy, matcher: m}
}
// Original: https://github.com/kubernetes/kubernetes/blob/8bd6c10ba5833369fb6582587b77de8f8b51c371/staging/src/k8s.io/apiserver/pkg/admission/plugin/policy/validating/plugin.go#L121-L157
func compilePolicy(policy *v1.ValidatingAdmissionPolicy) (validating.Validator, matchconditions.Matcher) {
hasParam := false
if policy.Spec.ParamKind != nil {
hasParam = true
}
// NOTE: StrictCost option is disabled for now.
optionalVars := cel.OptionalVariableDeclarations{HasParams: hasParam, HasAuthorizer: true, StrictCost: false}
expressionOptionalVars := cel.OptionalVariableDeclarations{HasParams: hasParam, HasAuthorizer: false, StrictCost: false}
failurePolicy := policy.Spec.FailurePolicy
var matcher matchconditions.Matcher = nil
matchConditions := policy.Spec.MatchConditions
compositionEnvTemplate, err := cel.NewCompositionEnv(cel.VariablesTypeName, environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion(), false))
if err != nil {
panic(err)
}
filterCompiler := cel.NewCompositedCompilerFromTemplate(compositionEnvTemplate)
filterCompiler.CompileAndStoreVariables(convertv1beta1Variables(policy.Spec.Variables), optionalVars, environment.StoredExpressions)
if len(matchConditions) > 0 {
matchExpressionAccessors := make([]cel.ExpressionAccessor, len(matchConditions))
for i := range matchConditions {
matchExpressionAccessors[i] = (*matchconditions.MatchCondition)(&matchConditions[i])
}
matcher = matchconditions.NewMatcher(filterCompiler.Compile(matchExpressionAccessors, optionalVars, environment.StoredExpressions), failurePolicy, "policy", "validate", policy.Name)
}
res := validating.NewValidator(
filterCompiler.Compile(convertv1Validations(policy.Spec.Validations), optionalVars, environment.StoredExpressions),
matcher,
filterCompiler.Compile(convertv1AuditAnnotations(policy.Spec.AuditAnnotations), optionalVars, environment.StoredExpressions),
filterCompiler.Compile(convertv1MessageExpressions(policy.Spec.Validations), expressionOptionalVars, environment.StoredExpressions),
failurePolicy,
)
return res, matcher
}
func convertv1Validations(inputValidations []v1.Validation) []cel.ExpressionAccessor {
celExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))
for i, validation := range inputValidations {
validation := validating.ValidationCondition{
Expression: validation.Expression,
Message: validation.Message,
Reason: validation.Reason,
}
celExpressionAccessor[i] = &validation
}
return celExpressionAccessor
}
func convertv1MessageExpressions(inputValidations []v1.Validation) []cel.ExpressionAccessor {
celExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))
for i, validation := range inputValidations {
if validation.MessageExpression != "" {
condition := validating.MessageExpressionCondition{
MessageExpression: validation.MessageExpression,
}
celExpressionAccessor[i] = &condition
}
}
return celExpressionAccessor
}
func convertv1AuditAnnotations(inputValidations []v1.AuditAnnotation) []cel.ExpressionAccessor {
celExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))
for i, validation := range inputValidations {
validation := validating.AuditAnnotationCondition{
Key: validation.Key,
ValueExpression: validation.ValueExpression,
}
celExpressionAccessor[i] = &validation
}
return celExpressionAccessor
}
func convertv1beta1Variables(variables []v1.Variable) []cel.NamedExpressionAccessor {
namedExpressions := make([]cel.NamedExpressionAccessor, len(variables))
for i, variable := range variables {
namedExpressions[i] = &validating.Variable{Name: variable.Name, Expression: variable.Expression}
}
return namedExpressions
}
// EvalMatchCondition evaluates ValidatingAdmissionPolicies' match conditions.
// It returns the result of the matchCondition evaluation to tell the caller which one is evaluated as 'false'.
// This is a hack to be able to check the name of failed expressions in matchCondition.
//
// TODO: Remove this func after k/k's Validate func outputs the name of the failed matchCondition.
func (v *Validator) EvalMatchCondition(p ValidationParams) *matchconditions.MatchResult {
if v.matcher == nil {
panic("matcher is not defined")
}
ctx := context.Background()
versionedAttribute, _ := makeVersionedAttribute(p)
matchResults := v.matcher.Match(ctx, versionedAttribute, p.ParamObj, stubAuthz())
return &matchResults
}
// Validate evaluates ValidationAdmissionPolicies' validations.
// ValidationResult contains the result of each validation(Admit, Deny, Error)
// and the reason if it is evaluated as Deny or Error.
func (v *Validator) Validate(p ValidationParams) (*validating.ValidateResult, error) {
ctx := context.Background()
versionedAttribute, matchedResource := makeVersionedAttribute(p)
result := v.validator.Validate(
ctx,
matchedResource,
versionedAttribute,
p.ParamObj,
p.NamespaceObj,
celconfig.RuntimeCELCostBudget,
// Inject stub authorizer since this testing tool focuses on the validation logic.
stubAuthz(),
)
correctResult := correctValidateResult(result)
return &correctResult, nil
}
func makeVersionedAttribute(p ValidationParams) (*admission.VersionedAttributes, schema.GroupVersionResource) {
nameWithGVK, err := getNameWithGVK(p)
if err != nil {
return nil, schema.GroupVersionResource{}
}
groupVersionResource := schema.GroupVersionResource{
Group: nameWithGVK.gvk.Group,
Version: nameWithGVK.gvk.Version,
// NOTE: GVR.Resource is not populated
Resource: "",
}
return &admission.VersionedAttributes{
Attributes: admission.NewAttributesRecord(
p.Object,
p.OldObject,
nameWithGVK.gvk,
nameWithGVK.namespace,
nameWithGVK.name,
groupVersionResource,
// NOTE: subResource is not populated
"", // subResource
p.Operation(),
// NOTE: operationOptions is not populated
nil, // operationOptions
// NOTE: dryRun is always true
true, // dryRun
p.UserInfo,
),
VersionedOldObject: p.OldObject,
VersionedObject: p.Object,
VersionedKind: nameWithGVK.gvk,
Dirty: false,
}, groupVersionResource
}
type nameWithGVK struct {
namespace string
name string
gvk schema.GroupVersionKind
}
func getNameWithGVK(p ValidationParams) (*nameWithGVK, error) {
if isNil(p.Object) && isNil(p.OldObject) {
return nil, fmt.Errorf("object or oldObject must be set")
}
obj := p.Object
if isNil(obj) {
obj = p.OldObject
}
namer := meta.NewAccessor()
name, err := namer.Name(obj)
if err != nil {
return nil, fmt.Errorf("name is not valid: %w", err)
}
namespaceName, err := namer.Namespace(obj)
if err != nil {
return nil, fmt.Errorf("namespace is not valid: %w", err)
}
gvk := obj.GetObjectKind().GroupVersionKind()
return &nameWithGVK{
name: name,
namespace: namespaceName,
gvk: gvk,
}, nil
}
func isNil(obj runtime.Object) bool {
return obj == nil || reflect.ValueOf(obj).IsNil()
}
// Workaround to handle the case where the evaluation is not set.
// TODO: remove this workaround after https://github.com/kubernetes/kubernetes/pull/126867 is released.
func correctValidateResult(result validating.ValidateResult) validating.ValidateResult {
for i, decision := range result.Decisions {
if decision.Evaluation == "" {
decision.Evaluation = validating.EvalDeny
result.Decisions[i] = decision
}
}
return result
}