Debian Codegraph @

pkg/admission/plugin/cel/condition.go

raw
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 cel
18
19 import (
20 "context"
21 "reflect"
22
23 admissionv1 "k8s.io/api/admission/v1"
24 authenticationv1 "k8s.io/api/authentication/v1"
25 v1 "k8s.io/api/core/v1"
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
28 "k8s.io/apimachinery/pkg/runtime"
29 "k8s.io/apiserver/pkg/admission"
30 "k8s.io/apiserver/pkg/cel/environment"
31 )
32
33 // conditionCompiler implement the interface ConditionCompiler.
34 type conditionCompiler struct {
35 compiler Compiler
36 }
37
38 func NewConditionCompiler(env *environment.EnvSet) ConditionCompiler {
39 return &conditionCompiler{compiler: NewCompiler(env)}
40 }
41
42 // CompileCondition compiles the cel expressions defined in the ExpressionAccessors into a ConditionEvaluator
43 func (c *conditionCompiler) CompileCondition(expressionAccessors []ExpressionAccessor, options OptionalVariableDeclarations, mode environment.Type) ConditionEvaluator {
44 compilationResults := make([]CompilationResult, len(expressionAccessors))
45 for i, expressionAccessor := range expressionAccessors {
46 if expressionAccessor == nil {
47 continue
48 }
49 compilationResults[i] = c.compiler.CompileCELExpression(expressionAccessor, options, mode)
50 }
51 return NewCondition(compilationResults)
52 }
53
54 // condition implements the ConditionEvaluator interface
55 type condition struct {
56 compilationResults []CompilationResult
57 }
58
59 func NewCondition(compilationResults []CompilationResult) ConditionEvaluator {
60 return &condition{
61 compilationResults,
62 }
63 }
64
65 func convertObjectToUnstructured(obj interface{}) (*unstructured.Unstructured, error) {
66 if obj == nil || reflect.ValueOf(obj).IsNil() {
67 return &unstructured.Unstructured{Object: nil}, nil
68 }
69 ret, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
70 if err != nil {
71 return nil, err
72 }
73 return &unstructured.Unstructured{Object: ret}, nil
74 }
75
76 func objectToResolveVal(r runtime.Object) (interface{}, error) {
77 if r == nil || reflect.ValueOf(r).IsNil() {
78 return nil, nil
79 }
80 v, err := convertObjectToUnstructured(r)
81 if err != nil {
82 return nil, err
83 }
84 return v.Object, nil
85 }
86
87 // ForInput evaluates the compiled CEL expressions converting them into CELEvaluations
88 // errors per evaluation are returned on the Evaluation object
89 // runtimeCELCostBudget was added for testing purpose only. Callers should always use const RuntimeCELCostBudget from k8s.io/apiserver/pkg/apis/cel/config.go as input.
90 func (c *condition) ForInput(ctx context.Context, versionedAttr *admission.VersionedAttributes, request *admissionv1.AdmissionRequest, inputs OptionalVariableBindings, namespace *v1.Namespace, runtimeCELCostBudget int64) ([]EvaluationResult, int64, error) {
91 // TODO: replace unstructured with ref.Val for CEL variables when native type support is available
92 evaluations := make([]EvaluationResult, len(c.compilationResults))
93 var err error
94
95 // if this activation supports composition, we will need the compositionCtx. It may be nil.
96 compositionCtx, _ := ctx.(CompositionContext)
97
98 activation, err := newActivation(compositionCtx, versionedAttr, request, inputs, namespace)
99 if err != nil {
100 return nil, -1, err
101 }
102
103 remainingBudget := runtimeCELCostBudget
104 for i, compilationResult := range c.compilationResults {
105 evaluations[i], remainingBudget, err = activation.Evaluate(ctx, compositionCtx, compilationResult, remainingBudget)
106 if err != nil {
107 return nil, -1, err
108 }
109 }
110
111 return evaluations, remainingBudget, nil
112 }
113
114 // TODO: to reuse https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/request/admissionreview.go#L154
115 func CreateAdmissionRequest(attr admission.Attributes, equivalentGVR metav1.GroupVersionResource, equivalentKind metav1.GroupVersionKind) *admissionv1.AdmissionRequest {
116 // Attempting to use same logic as webhook for constructing resource
117 // GVK, GVR, subresource
118 // Use the GVK, GVR that the matcher decided was equivalent to that of the request
119 // https://github.com/kubernetes/kubernetes/blob/90c362b3430bcbbf8f245fadbcd521dab39f1d7c/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go#L182-L210
120 gvk := equivalentKind
121 gvr := equivalentGVR
122 subresource := attr.GetSubresource()
123
124 requestGVK := attr.GetKind()
125 requestGVR := attr.GetResource()
126 requestSubResource := attr.GetSubresource()
127
128 aUserInfo := attr.GetUserInfo()
129 var userInfo authenticationv1.UserInfo
130 if aUserInfo != nil {
131 userInfo = authenticationv1.UserInfo{
132 Extra: make(map[string]authenticationv1.ExtraValue),
133 Groups: aUserInfo.GetGroups(),
134 UID: aUserInfo.GetUID(),
135 Username: aUserInfo.GetName(),
136 }
137 // Convert the extra information in the user object
138 for key, val := range aUserInfo.GetExtra() {
139 userInfo.Extra[key] = authenticationv1.ExtraValue(val)
140 }
141 }
142
143 dryRun := attr.IsDryRun()
144
145 return &admissionv1.AdmissionRequest{
146 Kind: metav1.GroupVersionKind{
147 Group: gvk.Group,
148 Kind: gvk.Kind,
149 Version: gvk.Version,
150 },
151 Resource: metav1.GroupVersionResource{
152 Group: gvr.Group,
153 Resource: gvr.Resource,
154 Version: gvr.Version,
155 },
156 SubResource: subresource,
157 RequestKind: &metav1.GroupVersionKind{
158 Group: requestGVK.Group,
159 Kind: requestGVK.Kind,
160 Version: requestGVK.Version,
161 },
162 RequestResource: &metav1.GroupVersionResource{
163 Group: requestGVR.Group,
164 Resource: requestGVR.Resource,
165 Version: requestGVR.Version,
166 },
167 RequestSubResource: requestSubResource,
168 Name: attr.GetName(),
169 Namespace: attr.GetNamespace(),
170 Operation: admissionv1.Operation(attr.GetOperation()),
171 UserInfo: userInfo,
172 // Leave Object and OldObject unset since we don't provide access to them via request
173 DryRun: &dryRun,
174 Options: runtime.RawExtension{
175 Object: attr.GetOperationOptions(),
176 },
177 }
178 }
179
180 // CreateNamespaceObject creates a Namespace object that is suitable for the CEL evaluation.
181 // If the namespace is nil, CreateNamespaceObject returns nil
182 func CreateNamespaceObject(namespace *v1.Namespace) *v1.Namespace {
183 if namespace == nil {
184 return nil
185 }
186
187 return &v1.Namespace{
188 Status: namespace.Status,
189 Spec: namespace.Spec,
190 ObjectMeta: metav1.ObjectMeta{
191 Name: namespace.Name,
192 GenerateName: namespace.GenerateName,
193 Namespace: namespace.Namespace,
194 UID: namespace.UID,
195 ResourceVersion: namespace.ResourceVersion,
196 Generation: namespace.Generation,
197 CreationTimestamp: namespace.CreationTimestamp,
198 DeletionTimestamp: namespace.DeletionTimestamp,
199 DeletionGracePeriodSeconds: namespace.DeletionGracePeriodSeconds,
200 Labels: namespace.Labels,
201 Annotations: namespace.Annotations,
202 Finalizers: namespace.Finalizers,
203 },
204 }
205 }
206
207 // CompilationErrors returns a list of all the errors from the compilation of the mutatingEvaluator
208 func (c *condition) CompilationErrors() []error {
209 compilationErrors := []error{}
210 for _, result := range c.compilationResults {
211 if result.Error != nil {
212 compilationErrors = append(compilationErrors, result.Error)
213 }
214 }
215 return compilationErrors
216 }