| 1 |
/* |
| 2 |
Copyright 2024 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 dynamic |
| 18 |
|
| 19 |
import ( |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"reflect" |
| 23 |
"strings" |
| 24 |
|
| 25 |
"github.com/google/cel-go/common/types" |
| 26 |
"github.com/google/cel-go/common/types/ref" |
| 27 |
"github.com/google/cel-go/common/types/traits" |
| 28 |
"google.golang.org/protobuf/types/known/structpb" |
| 29 |
) |
| 30 |
|
| 31 |
// ObjectType is the implementation of the Object type for use when compiling |
| 32 |
// CEL expressions without schema information about the object. |
| 33 |
// This is to provide CEL expressions with access to Object{} types constructors. |
| 34 |
type ObjectType struct { |
| 35 |
objectType *types.Type |
| 36 |
} |
| 37 |
|
| 38 |
func (o *ObjectType) HasTrait(trait int) bool { |
| 39 |
return o.objectType.HasTrait(trait) |
| 40 |
} |
| 41 |
|
| 42 |
// TypeName returns the name of this ObjectType. |
| 43 |
func (o *ObjectType) TypeName() string { |
| 44 |
return o.objectType.TypeName() |
| 45 |
} |
| 46 |
|
| 47 |
// Val returns an instance given the fields. |
| 48 |
func (o *ObjectType) Val(fields map[string]ref.Val) ref.Val { |
| 49 |
return NewObjectVal(o.objectType, fields) |
| 50 |
} |
| 51 |
|
| 52 |
func (o *ObjectType) Type() *types.Type { |
| 53 |
return o.objectType |
| 54 |
} |
| 55 |
|
| 56 |
// Field looks up the field by name. |
| 57 |
// This is the unstructured version that allows any name as the field name. |
| 58 |
// The returned field is of DynType type. |
| 59 |
func (o *ObjectType) Field(name string) (*types.FieldType, bool) { |
| 60 |
return &types.FieldType{ |
| 61 |
// for unstructured, we do not check for its type, |
| 62 |
// use DynType for all fields. |
| 63 |
Type: types.DynType, |
| 64 |
IsSet: func(target any) bool { |
| 65 |
if m, ok := target.(map[string]any); ok { |
| 66 |
_, isSet := m[name] |
| 67 |
return isSet |
| 68 |
} |
| 69 |
return false |
| 70 |
}, |
| 71 |
GetFrom: func(target any) (any, error) { |
| 72 |
if m, ok := target.(map[string]any); ok { |
| 73 |
return m[name], nil |
| 74 |
} |
| 75 |
return nil, fmt.Errorf("cannot get field %q", name) |
| 76 |
}, |
| 77 |
}, true |
| 78 |
} |
| 79 |
|
| 80 |
func (o *ObjectType) FieldNames() ([]string, bool) { |
| 81 |
return nil, true // Field names are not known for dynamic types. All field names are allowed. |
| 82 |
} |
| 83 |
|
| 84 |
// NewObjectType creates a ObjectType by the given field name. |
| 85 |
func NewObjectType(name string) *ObjectType { |
| 86 |
return &ObjectType{ |
| 87 |
objectType: types.NewObjectType(name), |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
// ObjectVal is the CEL Val for an object that is constructed via the Object{} in |
| 92 |
// CEL expressions without schema information about the object. |
| 93 |
type ObjectVal struct { |
| 94 |
objectType *types.Type |
| 95 |
fields map[string]ref.Val |
| 96 |
} |
| 97 |
|
| 98 |
// NewObjectVal creates an ObjectVal by its ResolvedType and its fields. |
| 99 |
func NewObjectVal(objectType *types.Type, fields map[string]ref.Val) *ObjectVal { |
| 100 |
return &ObjectVal{ |
| 101 |
objectType: objectType, |
| 102 |
fields: fields, |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
var _ ref.Val = (*ObjectVal)(nil) |
| 107 |
var _ traits.Zeroer = (*ObjectVal)(nil) |
| 108 |
|
| 109 |
// ConvertToNative converts the object to map[string]any. |
| 110 |
// All nested lists are converted into []any native type. |
| 111 |
// |
| 112 |
// It returns an error if the target type is not map[string]any, |
| 113 |
// or any recursive conversion fails. |
| 114 |
func (v *ObjectVal) ConvertToNative(typeDesc reflect.Type) (any, error) { |
| 115 |
result := make(map[string]any, len(v.fields)) |
| 116 |
for k, v := range v.fields { |
| 117 |
converted, err := convertField(v) |
| 118 |
if err != nil { |
| 119 |
return nil, fmt.Errorf("fail to convert field %q: %w", k, err) |
| 120 |
} |
| 121 |
result[k] = converted |
| 122 |
} |
| 123 |
if typeDesc == reflect.TypeOf(result) { |
| 124 |
return result, nil |
| 125 |
} |
| 126 |
// CEL's builtin data literal values all support conversion to structpb.Value, which |
| 127 |
// can then be serialized to JSON. This is convenient for CEL expressions that return |
| 128 |
// an arbitrary JSON value, such as our MutatingAdmissionPolicy JSON Patch valueExpression |
| 129 |
// field, so we support the conversion here, for Object data literals, as well. |
| 130 |
if typeDesc == reflect.TypeOf(&structpb.Value{}) { |
| 131 |
return structpb.NewStruct(result) |
| 132 |
} |
| 133 |
return nil, fmt.Errorf("unable to convert to %v", typeDesc) |
| 134 |
} |
| 135 |
|
| 136 |
// ConvertToType supports type conversions between CEL value types supported by the expression language. |
| 137 |
func (v *ObjectVal) ConvertToType(typeValue ref.Type) ref.Val { |
| 138 |
if v.objectType.TypeName() == typeValue.TypeName() { |
| 139 |
return v |
| 140 |
} |
| 141 |
if typeValue == types.TypeType { |
| 142 |
return types.NewTypeTypeWithParam(v.objectType) |
| 143 |
} |
| 144 |
return types.NewErr("unsupported conversion into %v", typeValue) |
| 145 |
} |
| 146 |
|
| 147 |
// Equal returns true if the `other` value has the same type and content as the implementing struct. |
| 148 |
func (v *ObjectVal) Equal(other ref.Val) ref.Val { |
| 149 |
if rhs, ok := other.(*ObjectVal); ok { |
| 150 |
if v.objectType.Equal(rhs.objectType) != types.True { |
| 151 |
return types.False |
| 152 |
} |
| 153 |
return types.Bool(reflect.DeepEqual(v.fields, rhs.fields)) |
| 154 |
} |
| 155 |
return types.False |
| 156 |
} |
| 157 |
|
| 158 |
// Type returns the TypeValue of the value. |
| 159 |
func (v *ObjectVal) Type() ref.Type { |
| 160 |
return types.NewObjectType(v.objectType.TypeName()) |
| 161 |
} |
| 162 |
|
| 163 |
// Value returns its value as a map[string]any. |
| 164 |
func (v *ObjectVal) Value() any { |
| 165 |
var result any |
| 166 |
var object map[string]any |
| 167 |
result, err := v.ConvertToNative(reflect.TypeOf(object)) |
| 168 |
if err != nil { |
| 169 |
return types.WrapErr(err) |
| 170 |
} |
| 171 |
return result |
| 172 |
} |
| 173 |
|
| 174 |
// CheckTypeNamesMatchFieldPathNames transitively checks the CEL object type names of this ObjectVal. Returns all |
| 175 |
// found type name mismatch errors. |
| 176 |
// Children ObjectVal types under <field> or this ObjectVal |
| 177 |
// must have type names of the form "<ObjectVal.TypeName>.<field>", children of that type must have type names of the |
| 178 |
// form "<ObjectVal.TypeName>.<field>.<field>" and so on. |
| 179 |
// Intermediate maps and lists are unnamed and ignored. |
| 180 |
func (v *ObjectVal) CheckTypeNamesMatchFieldPathNames() error { |
| 181 |
return errors.Join(typeCheck(v, []string{v.Type().TypeName()})...) |
| 182 |
|
| 183 |
} |
| 184 |
|
| 185 |
func typeCheck(v ref.Val, typeNamePath []string) []error { |
| 186 |
var errs []error |
| 187 |
if ov, ok := v.(*ObjectVal); ok { |
| 188 |
tn := ov.objectType.TypeName() |
| 189 |
if strings.Join(typeNamePath, ".") != tn { |
| 190 |
errs = append(errs, fmt.Errorf("unexpected type name %q, expected %q, which matches field name path from root Object type", tn, strings.Join(typeNamePath, "."))) |
| 191 |
} |
| 192 |
for k, f := range ov.fields { |
| 193 |
errs = append(errs, typeCheck(f, append(typeNamePath, k))...) |
| 194 |
} |
| 195 |
} |
| 196 |
value := v.Value() |
| 197 |
if listOfVal, ok := value.([]ref.Val); ok { |
| 198 |
for _, v := range listOfVal { |
| 199 |
errs = append(errs, typeCheck(v, typeNamePath)...) |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
if mapOfVal, ok := value.(map[ref.Val]ref.Val); ok { |
| 204 |
for _, v := range mapOfVal { |
| 205 |
errs = append(errs, typeCheck(v, typeNamePath)...) |
| 206 |
} |
| 207 |
} |
| 208 |
return errs |
| 209 |
} |
| 210 |
|
| 211 |
// IsZeroValue indicates whether the object is the zero value for the type. |
| 212 |
// For the ObjectVal, it is zero value if and only if the fields map is empty. |
| 213 |
func (v *ObjectVal) IsZeroValue() bool { |
| 214 |
return len(v.fields) == 0 |
| 215 |
} |
| 216 |
|
| 217 |
// convertField converts a referred ref.Val to its expected type. |
| 218 |
// For objects, the expected type is map[string]any |
| 219 |
// For lists, the expected type is []any |
| 220 |
// For maps, the expected type is map[string]any |
| 221 |
// For anything else, it is converted via value.Value() |
| 222 |
// |
| 223 |
// It will return an error if the request type is a map but the key |
| 224 |
// is not a string. |
| 225 |
func convertField(value ref.Val) (any, error) { |
| 226 |
// special handling for lists, where the elements are converted with Value() instead of ConvertToNative |
| 227 |
// to allow them to become native value of any type. |
| 228 |
if listOfVal, ok := value.Value().([]ref.Val); ok { |
| 229 |
var result []any |
| 230 |
for _, v := range listOfVal { |
| 231 |
result = append(result, v.Value()) |
| 232 |
} |
| 233 |
return result, nil |
| 234 |
} |
| 235 |
// unstructured maps, as seen in annotations |
| 236 |
// map keys must be strings |
| 237 |
if mapOfVal, ok := value.Value().(map[ref.Val]ref.Val); ok { |
| 238 |
result := make(map[string]any, len(mapOfVal)) |
| 239 |
for k, v := range mapOfVal { |
| 240 |
stringKey, ok := k.Value().(string) |
| 241 |
if !ok { |
| 242 |
return nil, fmt.Errorf("map key %q is of type %T, not string", k, k) |
| 243 |
} |
| 244 |
result[stringKey] = v.Value() |
| 245 |
} |
| 246 |
return result, nil |
| 247 |
} |
| 248 |
return value.Value(), nil |
| 249 |
} |