| 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 |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"strings" |
| 24 |
|
| 25 |
celtypes "github.com/google/cel-go/common/types" |
| 26 |
|
| 27 |
v1 "k8s.io/api/admissionregistration/v1" |
| 28 |
corev1 "k8s.io/api/core/v1" |
| 29 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 30 |
"k8s.io/apimachinery/pkg/runtime" |
| 31 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 32 |
"k8s.io/apiserver/pkg/admission" |
| 33 |
"k8s.io/apiserver/pkg/admission/plugin/cel" |
| 34 |
"k8s.io/apiserver/pkg/admission/plugin/webhook/matchconditions" |
| 35 |
celconfig "k8s.io/apiserver/pkg/apis/cel" |
| 36 |
"k8s.io/apiserver/pkg/authorization/authorizer" |
| 37 |
apiservercel "k8s.io/apiserver/pkg/cel" |
| 38 |
"k8s.io/klog/v2" |
| 39 |
) |
| 40 |
|
| 41 |
// validator implements the Validator interface |
| 42 |
type validator struct { |
| 43 |
celMatcher matchconditions.Matcher |
| 44 |
validationFilter cel.ConditionEvaluator |
| 45 |
auditAnnotationFilter cel.ConditionEvaluator |
| 46 |
messageFilter cel.ConditionEvaluator |
| 47 |
failPolicy *v1.FailurePolicyType |
| 48 |
} |
| 49 |
|
| 50 |
func NewValidator(validationFilter cel.ConditionEvaluator, celMatcher matchconditions.Matcher, auditAnnotationFilter, messageFilter cel.ConditionEvaluator, failPolicy *v1.FailurePolicyType) Validator { |
| 51 |
return &validator{ |
| 52 |
celMatcher: celMatcher, |
| 53 |
validationFilter: validationFilter, |
| 54 |
auditAnnotationFilter: auditAnnotationFilter, |
| 55 |
messageFilter: messageFilter, |
| 56 |
failPolicy: failPolicy, |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
func policyDecisionActionForError(f v1.FailurePolicyType) PolicyDecisionAction { |
| 61 |
if f == v1.Ignore { |
| 62 |
return ActionAdmit |
| 63 |
} |
| 64 |
return ActionDeny |
| 65 |
} |
| 66 |
|
| 67 |
func auditAnnotationEvaluationForError(f v1.FailurePolicyType) PolicyAuditAnnotationAction { |
| 68 |
if f == v1.Ignore { |
| 69 |
return AuditAnnotationActionExclude |
| 70 |
} |
| 71 |
return AuditAnnotationActionError |
| 72 |
} |
| 73 |
|
| 74 |
// Validate takes a list of Evaluation and a failure policy and converts them into actionable PolicyDecisions |
| 75 |
// runtimeCELCostBudget was added for testing purpose only. Callers should always use const RuntimeCELCostBudget from k8s.io/apiserver/pkg/apis/cel/config.go as input. |
| 76 |
|
| 77 |
func (v *validator) Validate(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *corev1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) ValidateResult { |
| 78 |
var f v1.FailurePolicyType |
| 79 |
if v.failPolicy == nil { |
| 80 |
f = v1.Fail |
| 81 |
} else { |
| 82 |
f = *v.failPolicy |
| 83 |
} |
| 84 |
if v.celMatcher != nil { |
| 85 |
matchResults := v.celMatcher.Match(ctx, versionedAttr, versionedParams, authz) |
| 86 |
if matchResults.Error != nil { |
| 87 |
return ValidateResult{ |
| 88 |
Decisions: []PolicyDecision{ |
| 89 |
{ |
| 90 |
Action: policyDecisionActionForError(f), |
| 91 |
Evaluation: EvalError, |
| 92 |
Message: matchResults.Error.Error(), |
| 93 |
}, |
| 94 |
}, |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
// if preconditions are not met, then do not return any validations |
| 99 |
if !matchResults.Matches { |
| 100 |
return ValidateResult{} |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
optionalVars := cel.OptionalVariableBindings{VersionedParams: versionedParams, Authorizer: authz} |
| 105 |
expressionOptionalVars := cel.OptionalVariableBindings{VersionedParams: versionedParams} |
| 106 |
admissionRequest := cel.CreateAdmissionRequest(versionedAttr.Attributes, metav1.GroupVersionResource(matchedResource), metav1.GroupVersionKind(versionedAttr.VersionedKind)) |
| 107 |
// Decide which fields are exposed |
| 108 |
ns := cel.CreateNamespaceObject(namespace) |
| 109 |
evalResults, remainingBudget, err := v.validationFilter.ForInput(ctx, versionedAttr, admissionRequest, optionalVars, ns, runtimeCELCostBudget) |
| 110 |
if err != nil { |
| 111 |
return ValidateResult{ |
| 112 |
Decisions: []PolicyDecision{ |
| 113 |
{ |
| 114 |
Action: policyDecisionActionForError(f), |
| 115 |
Evaluation: EvalError, |
| 116 |
Message: err.Error(), |
| 117 |
}, |
| 118 |
}, |
| 119 |
} |
| 120 |
} |
| 121 |
decisions := make([]PolicyDecision, len(evalResults)) |
| 122 |
messageResults, _, err := v.messageFilter.ForInput(ctx, versionedAttr, admissionRequest, expressionOptionalVars, ns, remainingBudget) |
| 123 |
for i, evalResult := range evalResults { |
| 124 |
var decision = &decisions[i] |
| 125 |
decision.Elapsed = evalResult.Elapsed |
| 126 |
// TODO: move this to generics |
| 127 |
validation, ok := evalResult.ExpressionAccessor.(*ValidationCondition) |
| 128 |
if !ok { |
| 129 |
klog.Error("Invalid type conversion to ValidationCondition") |
| 130 |
decision.Action = policyDecisionActionForError(f) |
| 131 |
decision.Evaluation = EvalError |
| 132 |
decision.Message = "Invalid type sent to validator, expected ValidationCondition" |
| 133 |
continue |
| 134 |
} |
| 135 |
|
| 136 |
var messageResult *cel.EvaluationResult |
| 137 |
if len(messageResults) > i { |
| 138 |
messageResult = &messageResults[i] |
| 139 |
} |
| 140 |
if evalResult.Error != nil { |
| 141 |
decision.Action = policyDecisionActionForError(f) |
| 142 |
decision.Evaluation = EvalError |
| 143 |
decision.Message = evalResult.Error.Error() |
| 144 |
} else if errors.Is(err, apiservercel.ErrInternal) || errors.Is(err, apiservercel.ErrOutOfBudget) { |
| 145 |
decision.Action = policyDecisionActionForError(f) |
| 146 |
decision.Evaluation = EvalError |
| 147 |
decision.Message = fmt.Sprintf("failed messageExpression: %s", err) |
| 148 |
} else if evalResult.EvalResult != celtypes.True { |
| 149 |
decision.Action = ActionDeny |
| 150 |
decision.Evaluation = EvalDeny |
| 151 |
if validation.Reason == nil { |
| 152 |
decision.Reason = metav1.StatusReasonInvalid |
| 153 |
} else { |
| 154 |
decision.Reason = *validation.Reason |
| 155 |
} |
| 156 |
// decide the failure message |
| 157 |
var message string |
| 158 |
// attempt to set message with messageExpression result |
| 159 |
if messageResult != nil && messageResult.Error == nil && messageResult.EvalResult != nil { |
| 160 |
// also fallback if the eval result is non-string (including null) or |
| 161 |
// whitespaces. |
| 162 |
if message, ok = messageResult.EvalResult.Value().(string); ok { |
| 163 |
message = strings.TrimSpace(message) |
| 164 |
// deny excessively long message from EvalResult |
| 165 |
if len(message) > celconfig.MaxEvaluatedMessageExpressionSizeBytes { |
| 166 |
klog.V(2).InfoS("excessively long message denied", "message", message) |
| 167 |
message = "" |
| 168 |
} |
| 169 |
// deny message that contains newlines |
| 170 |
if strings.ContainsAny(message, "\n") { |
| 171 |
klog.V(2).InfoS("multi-line message denied", "message", message) |
| 172 |
message = "" |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
if messageResult != nil && messageResult.Error != nil { |
| 177 |
// log any error with messageExpression |
| 178 |
klog.V(2).ErrorS(messageResult.Error, "error while evaluating messageExpression") |
| 179 |
} |
| 180 |
// fallback to set message to the custom message |
| 181 |
if message == "" && len(validation.Message) > 0 { |
| 182 |
message = strings.TrimSpace(validation.Message) |
| 183 |
} |
| 184 |
// fallback to use the expression to compose a message |
| 185 |
if message == "" { |
| 186 |
message = fmt.Sprintf("failed expression: %v", strings.TrimSpace(validation.Expression)) |
| 187 |
} |
| 188 |
decision.Message = message |
| 189 |
} else { |
| 190 |
decision.Action = ActionAdmit |
| 191 |
decision.Evaluation = EvalAdmit |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
options := cel.OptionalVariableBindings{VersionedParams: versionedParams} |
| 196 |
auditAnnotationEvalResults, _, err := v.auditAnnotationFilter.ForInput(ctx, versionedAttr, admissionRequest, options, namespace, runtimeCELCostBudget) |
| 197 |
if err != nil { |
| 198 |
return ValidateResult{ |
| 199 |
Decisions: []PolicyDecision{ |
| 200 |
{ |
| 201 |
Action: policyDecisionActionForError(f), |
| 202 |
Evaluation: EvalError, |
| 203 |
Message: err.Error(), |
| 204 |
}, |
| 205 |
}, |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
auditAnnotationResults := make([]PolicyAuditAnnotation, len(auditAnnotationEvalResults)) |
| 210 |
for i, evalResult := range auditAnnotationEvalResults { |
| 211 |
if evalResult.ExpressionAccessor == nil { |
| 212 |
continue |
| 213 |
} |
| 214 |
var auditAnnotationResult = &auditAnnotationResults[i] |
| 215 |
auditAnnotationResult.Elapsed = evalResult.Elapsed |
| 216 |
// TODO: move this to generics |
| 217 |
validation, ok := evalResult.ExpressionAccessor.(*AuditAnnotationCondition) |
| 218 |
if !ok { |
| 219 |
klog.Error("Invalid type conversion to AuditAnnotationCondition") |
| 220 |
auditAnnotationResult.Action = auditAnnotationEvaluationForError(f) |
| 221 |
auditAnnotationResult.Error = fmt.Sprintf("Invalid type sent to validator, expected AuditAnnotationCondition but got %T", evalResult.ExpressionAccessor) |
| 222 |
continue |
| 223 |
} |
| 224 |
auditAnnotationResult.Key = validation.Key |
| 225 |
|
| 226 |
if evalResult.Error != nil { |
| 227 |
auditAnnotationResult.Action = auditAnnotationEvaluationForError(f) |
| 228 |
auditAnnotationResult.Error = evalResult.Error.Error() |
| 229 |
} else { |
| 230 |
switch evalResult.EvalResult.Type() { |
| 231 |
case celtypes.StringType: |
| 232 |
value := strings.TrimSpace(evalResult.EvalResult.Value().(string)) |
| 233 |
if len(value) == 0 { |
| 234 |
auditAnnotationResult.Action = AuditAnnotationActionExclude |
| 235 |
} else { |
| 236 |
auditAnnotationResult.Action = AuditAnnotationActionPublish |
| 237 |
auditAnnotationResult.Value = value |
| 238 |
} |
| 239 |
case celtypes.NullType: |
| 240 |
auditAnnotationResult.Action = AuditAnnotationActionExclude |
| 241 |
default: |
| 242 |
auditAnnotationResult.Action = AuditAnnotationActionError |
| 243 |
auditAnnotationResult.Error = fmt.Sprintf("valueExpression '%v' resulted in unsupported return type: %v. "+ |
| 244 |
"Return type must be either string or null.", validation.ValueExpression, evalResult.EvalResult.Type()) |
| 245 |
} |
| 246 |
} |
| 247 |
} |
| 248 |
return ValidateResult{Decisions: decisions, AuditAnnotations: auditAnnotationResults} |
| 249 |
} |