| 1 | // Copyright 2022 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package ext |
| 16 | |
| 17 | import ( |
| 18 | "errors" |
| 19 | "fmt" |
| 20 | "math" |
| 21 | "reflect" |
| 22 | "strings" |
| 23 | "time" |
| 24 | |
| 25 | "google.golang.org/protobuf/proto" |
| 26 | "google.golang.org/protobuf/reflect/protoreflect" |
| 27 | |
| 28 | "github.com/google/cel-go/cel" |
| 29 | "github.com/google/cel-go/common/types" |
| 30 | "github.com/google/cel-go/common/types/pb" |
| 31 | "github.com/google/cel-go/common/types/ref" |
| 32 | "github.com/google/cel-go/common/types/traits" |
| 33 | |
| 34 | structpb "google.golang.org/protobuf/types/known/structpb" |
| 35 | ) |
| 36 | |
| 37 | var ( |
| 38 | nativeObjTraitMask = traits.FieldTesterType | traits.IndexerType |
| 39 | jsonValueType = reflect.TypeOf(&structpb.Value{}) |
| 40 | jsonStructType = reflect.TypeOf(&structpb.Struct{}) |
| 41 | ) |
| 42 | |
| 43 | // NativeTypes creates a type provider which uses reflect.Type and reflect.Value instances |
| 44 | // to produce type definitions that can be used within CEL. |
| 45 | // |
| 46 | // All struct types in Go are exposed to CEL via their simple package name and struct type name: |
| 47 | // |
| 48 | // ```go |
| 49 | // package identity |
| 50 | // |
| 51 | // type Account struct { |
| 52 | // ID int |
| 53 | // } |
| 54 | // |
| 55 | // ``` |
| 56 | // |
| 57 | // The type `identity.Account` would be exported to CEL using the same qualified name, e.g. |
| 58 | // `identity.Account{ID: 1234}` would create a new `Account` instance with the `ID` field |
| 59 | // populated. |
| 60 | // |
| 61 | // Only exported fields are exposed via NativeTypes, and the type-mapping between Go and CEL |
| 62 | // is as follows: |
| 63 | // |
| 64 | // | Go type | CEL type | |
| 65 | // |-------------------------------------|-----------| |
| 66 | // | bool | bool | |
| 67 | // | []byte | bytes | |
| 68 | // | float32, float64 | double | |
| 69 | // | int, int8, int16, int32, int64 | int | |
| 70 | // | string | string | |
| 71 | // | uint, uint8, uint16, uint32, uint64 | uint | |
| 72 | // | time.Duration | duration | |
| 73 | // | time.Time | timestamp | |
| 74 | // | array, slice | list | |
| 75 | // | map | map | |
| 76 | // |
| 77 | // Please note, if you intend to configure support for proto messages in addition to native |
| 78 | // types, you will need to provide the protobuf types before the golang native types. The |
| 79 | // same advice holds if you are using custom type adapters and type providers. The native type |
| 80 | // provider composes over whichever type adapter and provider is configured in the cel.Env at |
| 81 | // the time that it is invoked. |
| 82 | // |
| 83 | // There is also the possibility to rename the fields of native structs by setting the `cel` tag |
| 84 | // for fields you want to override. In order to enable this feature, pass in the `ParseStructTags(true)` |
| 85 | // option. Here is an example to see it in action: |
| 86 | // |
| 87 | // ```go |
| 88 | // package identity |
| 89 | // |
| 90 | // type Account struct { |
| 91 | // ID int |
| 92 | // OwnerName string `cel:"owner"` |
| 93 | // } |
| 94 | // |
| 95 | // ``` |
| 96 | // |
| 97 | // The `OwnerName` field is now accessible in CEL via `owner`, e.g. `identity.Account{owner: 'bob'}`. |
| 98 | // In case there are duplicated field names in the struct, an error will be returned. |
| 99 | func NativeTypes(args ...any) cel.EnvOption { |
| 100 | return func(env *cel.Env) (*cel.Env, error) { |
| 101 | nativeTypes := make([]any, 0, len(args)) |
| 102 | tpOptions := nativeTypeOptions{ |
| 103 | version: math.MaxUint32, |
| 104 | } |
| 105 | |
| 106 | for _, v := range args { |
| 107 | switch v := v.(type) { |
| 108 | case NativeTypesOption: |
| 109 | err := v(&tpOptions) |
| 110 | if err != nil { |
| 111 | return nil, err |
| 112 | } |
| 113 | default: |
| 114 | nativeTypes = append(nativeTypes, v) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | tp, err := newNativeTypeProvider(tpOptions, env.CELTypeAdapter(), env.CELTypeProvider(), nativeTypes...) |
| 119 | if err != nil { |
| 120 | return nil, err |
| 121 | } |
| 122 | |
| 123 | env, err = cel.CustomTypeAdapter(tp)(env) |
| 124 | if err != nil { |
| 125 | return nil, err |
| 126 | } |
| 127 | return cel.CustomTypeProvider(tp)(env) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // NativeTypesOption is a functional interface for configuring handling of native types. |
| 132 | type NativeTypesOption func(*nativeTypeOptions) error |
| 133 | |
| 134 | // NativeTypesVersion sets the native types version support for native extensions functions. |
| 135 | func NativeTypesVersion(version uint32) NativeTypesOption { |
| 136 | return func(opts *nativeTypeOptions) error { |
| 137 | opts.version = version |
| 138 | return nil |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | // NativeTypesFieldNameHandler is a handler for mapping a reflect.StructField to a CEL field name. |
| 143 | // This can be used to override the default Go struct field to CEL field name mapping. |
| 144 | type NativeTypesFieldNameHandler = func(field reflect.StructField) string |
| 145 | |
| 146 | func fieldNameByTag(structTagToParse string) func(field reflect.StructField) string { |
| 147 | return func(field reflect.StructField) string { |
| 148 | tag, found := field.Tag.Lookup(structTagToParse) |
| 149 | if found { |
| 150 | splits := strings.Split(tag, ",") |
| 151 | if len(splits) > 0 { |
| 152 | // We make the assumption that the leftmost entry in the tag is the name. |
| 153 | // This seems to be true for most tags that have the concept of a name/key, such as: |
| 154 | // https://pkg.go.dev/encoding/xml#Marshal |
| 155 | // https://pkg.go.dev/encoding/json#Marshal |
| 156 | // https://pkg.go.dev/go.mongodb.org/mongo-driver/bson#hdr-Structs |
| 157 | // https://pkg.go.dev/go.yaml.in/yaml/v3#Marshal |
| 158 | name := splits[0] |
| 159 | return name |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | return field.Name |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | type nativeTypeOptions struct { |
| 168 | // fieldNameHandler controls how CEL should perform struct field renames. |
| 169 | // This is most commonly used for switching to parsing based off the struct field tag, |
| 170 | // such as "cel" or "json". |
| 171 | fieldNameHandler NativeTypesFieldNameHandler |
| 172 | |
| 173 | // version is the native types library version. |
| 174 | version uint32 |
| 175 | } |
| 176 | |
| 177 | // ParseStructTags configures if native types field names should be overridable by CEL struct tags. |
| 178 | // This is equivalent to ParseStructTag("cel") |
| 179 | func ParseStructTags(enabled bool) NativeTypesOption { |
| 180 | return func(ntp *nativeTypeOptions) error { |
| 181 | if enabled { |
| 182 | ntp.fieldNameHandler = fieldNameByTag("cel") |
| 183 | } else { |
| 184 | ntp.fieldNameHandler = nil |
| 185 | } |
| 186 | return nil |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | // ParseStructTag configures the struct tag to parse. The 0th item in the tag is used as the name of the CEL field. |
| 191 | // For example: |
| 192 | // If the tag to parse is "cel" and the struct field has tag cel:"foo", the CEL struct field will be "foo". |
| 193 | // If the tag to parse is "json" and the struct field has tag json:"foo,omitempty", the CEL struct field will be "foo". |
| 194 | func ParseStructTag(tag string) NativeTypesOption { |
| 195 | return func(ntp *nativeTypeOptions) error { |
| 196 | ntp.fieldNameHandler = fieldNameByTag(tag) |
| 197 | return nil |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // ParseStructField configures how to parse Go struct fields. It can be used to customize struct field parsing. |
| 202 | func ParseStructField(handler NativeTypesFieldNameHandler) NativeTypesOption { |
| 203 | return func(ntp *nativeTypeOptions) error { |
| 204 | ntp.fieldNameHandler = handler |
| 205 | return nil |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | func newNativeTypeProvider(tpOptions nativeTypeOptions, adapter types.Adapter, provider types.Provider, refTypes ...any) (*nativeTypeProvider, error) { |
| 210 | nativeTypes := make(map[string]*nativeType, len(refTypes)) |
| 211 | for _, refType := range refTypes { |
| 212 | switch rt := refType.(type) { |
| 213 | case reflect.Type: |
| 214 | result, err := newNativeTypes(tpOptions.fieldNameHandler, rt) |
| 215 | if err != nil { |
| 216 | return nil, err |
| 217 | } |
| 218 | for idx := range result { |
| 219 | nativeTypes[result[idx].TypeName()] = result[idx] |
| 220 | } |
| 221 | case reflect.Value: |
| 222 | result, err := newNativeTypes(tpOptions.fieldNameHandler, rt.Type()) |
| 223 | if err != nil { |
| 224 | return nil, err |
| 225 | } |
| 226 | for idx := range result { |
| 227 | nativeTypes[result[idx].TypeName()] = result[idx] |
| 228 | } |
| 229 | default: |
| 230 | return nil, fmt.Errorf("unsupported native type: %v (%T) must be reflect.Type or reflect.Value", rt, rt) |
| 231 | } |
| 232 | } |
| 233 | return &nativeTypeProvider{ |
| 234 | nativeTypes: nativeTypes, |
| 235 | baseAdapter: adapter, |
| 236 | baseProvider: provider, |
| 237 | options: tpOptions, |
| 238 | }, nil |
| 239 | } |
| 240 | |
| 241 | type nativeTypeProvider struct { |
| 242 | nativeTypes map[string]*nativeType |
| 243 | baseAdapter types.Adapter |
| 244 | baseProvider types.Provider |
| 245 | options nativeTypeOptions |
| 246 | } |
| 247 | |
| 248 | // EnumValue proxies to the types.Provider configured at the times the NativeTypes |
| 249 | // option was configured. |
| 250 | func (tp *nativeTypeProvider) EnumValue(enumName string) ref.Val { |
| 251 | return tp.baseProvider.EnumValue(enumName) |
| 252 | } |
| 253 | |
| 254 | // FindIdent looks up natives type instances by qualified identifier, and if not found |
| 255 | // proxies to the composed types.Provider. |
| 256 | func (tp *nativeTypeProvider) FindIdent(typeName string) (ref.Val, bool) { |
| 257 | if t, found := tp.nativeTypes[typeName]; found { |
| 258 | return t, true |
| 259 | } |
| 260 | return tp.baseProvider.FindIdent(typeName) |
| 261 | } |
| 262 | |
| 263 | // FindStructType looks up the CEL type definition by qualified identifier, and if not found |
| 264 | // proxies to the composed types.Provider. |
| 265 | func (tp *nativeTypeProvider) FindStructType(typeName string) (*types.Type, bool) { |
| 266 | if _, found := tp.nativeTypes[typeName]; found { |
| 267 | return types.NewTypeTypeWithParam(types.NewObjectType(typeName)), true |
| 268 | } |
| 269 | if celType, found := tp.baseProvider.FindStructType(typeName); found { |
| 270 | return celType, true |
| 271 | } |
| 272 | return tp.baseProvider.FindStructType(typeName) |
| 273 | } |
| 274 | |
| 275 | func toFieldName(fieldNameHandler NativeTypesFieldNameHandler, f reflect.StructField) string { |
| 276 | if fieldNameHandler == nil { |
| 277 | return f.Name |
| 278 | } |
| 279 | |
| 280 | return fieldNameHandler(f) |
| 281 | } |
| 282 | |
| 283 | // FindStructFieldNames looks up the type definition first from the native types, then from |
| 284 | // the backing provider type set. If found, a set of field names corresponding to the type |
| 285 | // will be returned. |
| 286 | func (tp *nativeTypeProvider) FindStructFieldNames(typeName string) ([]string, bool) { |
| 287 | if t, found := tp.nativeTypes[typeName]; found { |
| 288 | fieldCount := t.refType.NumField() |
| 289 | fields := make([]string, fieldCount) |
| 290 | for i := 0; i < fieldCount; i++ { |
| 291 | fields[i] = toFieldName(tp.options.fieldNameHandler, t.refType.Field(i)) |
| 292 | } |
| 293 | return fields, true |
| 294 | } |
| 295 | if celTypeFields, found := tp.baseProvider.FindStructFieldNames(typeName); found { |
| 296 | return celTypeFields, true |
| 297 | } |
| 298 | return tp.baseProvider.FindStructFieldNames(typeName) |
| 299 | } |
| 300 | |
| 301 | // FindStructFieldType looks up a native type's field definition, and if the type name is not a native |
| 302 | // type then proxies to the composed types.Provider |
| 303 | func (tp *nativeTypeProvider) FindStructFieldType(typeName, fieldName string) (*types.FieldType, bool) { |
| 304 | t, found := tp.nativeTypes[typeName] |
| 305 | if !found { |
| 306 | return tp.baseProvider.FindStructFieldType(typeName, fieldName) |
| 307 | } |
| 308 | refField, isDefined := t.hasField(fieldName) |
| 309 | if !found || !isDefined { |
| 310 | return nil, false |
| 311 | } |
| 312 | celType, ok := convertToCelType(refField.Type) |
| 313 | if !ok { |
| 314 | return nil, false |
| 315 | } |
| 316 | return &types.FieldType{ |
| 317 | Type: celType, |
| 318 | IsSet: func(obj any) bool { |
| 319 | refVal := reflect.Indirect(reflect.ValueOf(obj)) |
| 320 | refField := refVal.FieldByName(refField.Name) |
| 321 | return !refField.IsZero() |
| 322 | }, |
| 323 | GetFrom: func(obj any) (any, error) { |
| 324 | refVal := reflect.Indirect(reflect.ValueOf(obj)) |
| 325 | refField := refVal.FieldByName(refField.Name) |
| 326 | return getFieldValue(refField), nil |
| 327 | }, |
| 328 | }, true |
| 329 | } |
| 330 | |
| 331 | // NewValue implements the ref.TypeProvider interface method. |
| 332 | func (tp *nativeTypeProvider) NewValue(typeName string, fields map[string]ref.Val) ref.Val { |
| 333 | t, found := tp.nativeTypes[typeName] |
| 334 | if !found { |
| 335 | return tp.baseProvider.NewValue(typeName, fields) |
| 336 | } |
| 337 | refPtr := reflect.New(t.refType) |
| 338 | refVal := refPtr.Elem() |
| 339 | for fieldName, val := range fields { |
| 340 | refFieldDef, isDefined := t.hasField(fieldName) |
| 341 | if !isDefined { |
| 342 | return types.NewErr("no such field: %s", fieldName) |
| 343 | } |
| 344 | fieldVal, err := val.ConvertToNative(refFieldDef.Type) |
| 345 | if err != nil { |
| 346 | return types.NewErrFromString(err.Error()) |
| 347 | } |
| 348 | refField := refVal.FieldByIndex(refFieldDef.Index) |
| 349 | refFieldVal := reflect.ValueOf(fieldVal) |
| 350 | refField.Set(refFieldVal) |
| 351 | } |
| 352 | return tp.NativeToValue(refPtr.Interface()) |
| 353 | } |
| 354 | |
| 355 | // NewValue adapts native values to CEL values and will proxy to the composed type adapter |
| 356 | // for non-native types. |
| 357 | func (tp *nativeTypeProvider) NativeToValue(val any) ref.Val { |
| 358 | if val == nil { |
| 359 | return types.NullValue |
| 360 | } |
| 361 | if v, ok := val.(ref.Val); ok { |
| 362 | return v |
| 363 | } |
| 364 | rawVal := reflect.ValueOf(val) |
| 365 | refVal := rawVal |
| 366 | if refVal.Kind() == reflect.Ptr { |
| 367 | refVal = reflect.Indirect(refVal) |
| 368 | } |
| 369 | // This isn't quite right if you're also supporting proto, |
| 370 | // but maybe an acceptable limitation. |
| 371 | switch refVal.Kind() { |
| 372 | case reflect.Array, reflect.Slice: |
| 373 | switch val := val.(type) { |
| 374 | case []byte: |
| 375 | return tp.baseAdapter.NativeToValue(val) |
| 376 | default: |
| 377 | if refVal.Type().Elem() == reflect.TypeOf(byte(0)) { |
| 378 | return tp.baseAdapter.NativeToValue(val) |
| 379 | } |
| 380 | return types.NewDynamicList(tp, val) |
| 381 | } |
| 382 | case reflect.Map: |
| 383 | return types.NewDynamicMap(tp, val) |
| 384 | case reflect.Struct: |
| 385 | switch val := val.(type) { |
| 386 | case proto.Message, *pb.Map, protoreflect.List, protoreflect.Message, protoreflect.Value, |
| 387 | time.Time: |
| 388 | return tp.baseAdapter.NativeToValue(val) |
| 389 | default: |
| 390 | return tp.newNativeObject(val, rawVal) |
| 391 | } |
| 392 | default: |
| 393 | return tp.baseAdapter.NativeToValue(val) |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | func convertToCelType(refType reflect.Type) (*cel.Type, bool) { |
| 398 | switch refType.Kind() { |
| 399 | case reflect.Bool: |
| 400 | return cel.BoolType, true |
| 401 | case reflect.Float32, reflect.Float64: |
| 402 | return cel.DoubleType, true |
| 403 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 404 | if refType == durationType { |
| 405 | return cel.DurationType, true |
| 406 | } |
| 407 | return cel.IntType, true |
| 408 | case reflect.String: |
| 409 | return cel.StringType, true |
| 410 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
| 411 | return cel.UintType, true |
| 412 | case reflect.Array, reflect.Slice: |
| 413 | refElem := refType.Elem() |
| 414 | if refElem == reflect.TypeOf(byte(0)) { |
| 415 | return cel.BytesType, true |
| 416 | } |
| 417 | elemType, ok := convertToCelType(refElem) |
| 418 | if !ok { |
| 419 | return nil, false |
| 420 | } |
| 421 | return cel.ListType(elemType), true |
| 422 | case reflect.Map: |
| 423 | keyType, ok := convertToCelType(refType.Key()) |
| 424 | if !ok { |
| 425 | return nil, false |
| 426 | } |
| 427 | // Ensure the key type is a int, bool, uint, string |
| 428 | elemType, ok := convertToCelType(refType.Elem()) |
| 429 | if !ok { |
| 430 | return nil, false |
| 431 | } |
| 432 | return cel.MapType(keyType, elemType), true |
| 433 | case reflect.Struct: |
| 434 | if refType == timestampType { |
| 435 | return cel.TimestampType, true |
| 436 | } |
| 437 | return cel.ObjectType( |
| 438 | fmt.Sprintf("%s.%s", simplePkgAlias(refType.PkgPath()), refType.Name()), |
| 439 | ), true |
| 440 | case reflect.Pointer: |
| 441 | if refType.Implements(pbMsgInterfaceType) { |
| 442 | pbMsg := reflect.New(refType.Elem()).Interface().(protoreflect.ProtoMessage) |
| 443 | return cel.ObjectType(string(pbMsg.ProtoReflect().Descriptor().FullName())), true |
| 444 | } |
| 445 | return convertToCelType(refType.Elem()) |
| 446 | } |
| 447 | return nil, false |
| 448 | } |
| 449 | |
| 450 | func (tp *nativeTypeProvider) newNativeObject(val any, refValue reflect.Value) ref.Val { |
| 451 | valType, err := newNativeType(tp.options.fieldNameHandler, refValue.Type()) |
| 452 | if err != nil { |
| 453 | return types.NewErrFromString(err.Error()) |
| 454 | } |
| 455 | return &nativeObj{ |
| 456 | Adapter: tp, |
| 457 | val: val, |
| 458 | valType: valType, |
| 459 | refValue: refValue, |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | type nativeObj struct { |
| 464 | types.Adapter |
| 465 | val any |
| 466 | valType *nativeType |
| 467 | refValue reflect.Value |
| 468 | } |
| 469 | |
| 470 | // ConvertToNative implements the ref.Val interface method. |
| 471 | // |
| 472 | // CEL does not have a notion of pointers, so whether a field is a pointer or value |
| 473 | // is handled as part of this conversion step. |
| 474 | func (o *nativeObj) ConvertToNative(typeDesc reflect.Type) (any, error) { |
| 475 | if o.refValue.Type() == typeDesc { |
| 476 | return o.val, nil |
| 477 | } |
| 478 | if o.refValue.Kind() == reflect.Pointer && o.refValue.Type().Elem() == typeDesc { |
| 479 | return o.refValue.Elem().Interface(), nil |
| 480 | } |
| 481 | if typeDesc.Kind() == reflect.Pointer && o.refValue.Type() == typeDesc.Elem() { |
| 482 | ptr := reflect.New(typeDesc.Elem()) |
| 483 | ptr.Elem().Set(o.refValue) |
| 484 | return ptr.Interface(), nil |
| 485 | } |
| 486 | switch typeDesc { |
| 487 | case jsonValueType: |
| 488 | jsonStruct, err := o.ConvertToNative(jsonStructType) |
| 489 | if err != nil { |
| 490 | return nil, err |
| 491 | } |
| 492 | return structpb.NewStructValue(jsonStruct.(*structpb.Struct)), nil |
| 493 | case jsonStructType: |
| 494 | refVal := reflect.Indirect(o.refValue) |
| 495 | refType := refVal.Type() |
| 496 | fields := make(map[string]*structpb.Value, refVal.NumField()) |
| 497 | for i := 0; i < refVal.NumField(); i++ { |
| 498 | fieldType := refType.Field(i) |
| 499 | fieldValue := refVal.Field(i) |
| 500 | if !fieldValue.IsValid() || fieldValue.IsZero() { |
| 501 | continue |
| 502 | } |
| 503 | fieldName := toFieldName(o.valType.fieldNameHandler, fieldType) |
| 504 | fieldCELVal := o.NativeToValue(fieldValue.Interface()) |
| 505 | fieldJSONVal, err := fieldCELVal.ConvertToNative(jsonValueType) |
| 506 | if err != nil { |
| 507 | return nil, err |
| 508 | } |
| 509 | fields[fieldName] = fieldJSONVal.(*structpb.Value) |
| 510 | } |
| 511 | return &structpb.Struct{Fields: fields}, nil |
| 512 | } |
| 513 | return nil, fmt.Errorf("type conversion error from '%v' to '%v'", o.Type(), typeDesc) |
| 514 | } |
| 515 | |
| 516 | // ConvertToType implements the ref.Val interface method. |
| 517 | func (o *nativeObj) ConvertToType(typeVal ref.Type) ref.Val { |
| 518 | switch typeVal { |
| 519 | case types.TypeType: |
| 520 | return o.valType |
| 521 | default: |
| 522 | if typeVal.TypeName() == o.valType.typeName { |
| 523 | return o |
| 524 | } |
| 525 | } |
| 526 | return types.NewErr("type conversion error from '%s' to '%s'", o.Type(), typeVal) |
| 527 | } |
| 528 | |
| 529 | // Equal implements the ref.Val interface method. |
| 530 | // |
| 531 | // Note, that in Golang a pointer to a value is not equal to the value it contains. |
| 532 | // In CEL pointers and values to which they point are equal. |
| 533 | func (o *nativeObj) Equal(other ref.Val) ref.Val { |
| 534 | otherNtv, ok := other.(*nativeObj) |
| 535 | if !ok { |
| 536 | return types.False |
| 537 | } |
| 538 | val := o.val |
| 539 | otherVal := otherNtv.val |
| 540 | refVal := o.refValue |
| 541 | otherRefVal := otherNtv.refValue |
| 542 | if refVal.Kind() != otherRefVal.Kind() { |
| 543 | if refVal.Kind() == reflect.Pointer { |
| 544 | val = refVal.Elem().Interface() |
| 545 | } else if otherRefVal.Kind() == reflect.Pointer { |
| 546 | otherVal = otherRefVal.Elem().Interface() |
| 547 | } |
| 548 | } |
| 549 | return types.Bool(reflect.DeepEqual(val, otherVal)) |
| 550 | } |
| 551 | |
| 552 | // IsZeroValue indicates whether the contained Golang value is a zero value. |
| 553 | // |
| 554 | // Golang largely follows proto3 semantics for zero values. |
| 555 | func (o *nativeObj) IsZeroValue() bool { |
| 556 | return reflect.Indirect(o.refValue).IsZero() |
| 557 | } |
| 558 | |
| 559 | // IsSet tests whether a field which is defined is set to a non-default value. |
| 560 | func (o *nativeObj) IsSet(field ref.Val) ref.Val { |
| 561 | refField, refErr := o.getReflectedField(field) |
| 562 | if refErr != nil { |
| 563 | return refErr |
| 564 | } |
| 565 | return types.Bool(!refField.IsZero()) |
| 566 | } |
| 567 | |
| 568 | // Get returns the value fo a field name. |
| 569 | func (o *nativeObj) Get(field ref.Val) ref.Val { |
| 570 | refField, refErr := o.getReflectedField(field) |
| 571 | if refErr != nil { |
| 572 | return refErr |
| 573 | } |
| 574 | return adaptFieldValue(o, refField) |
| 575 | } |
| 576 | |
| 577 | func (o *nativeObj) getReflectedField(field ref.Val) (reflect.Value, ref.Val) { |
| 578 | fieldName, ok := field.(types.String) |
| 579 | if !ok { |
| 580 | return reflect.Value{}, types.MaybeNoSuchOverloadErr(field) |
| 581 | } |
| 582 | fieldNameStr := string(fieldName) |
| 583 | refField, isDefined := o.valType.hasField(fieldNameStr) |
| 584 | if !isDefined { |
| 585 | return reflect.Value{}, types.NewErr("no such field: %s", fieldName) |
| 586 | } |
| 587 | refVal := reflect.Indirect(o.refValue) |
| 588 | return refVal.FieldByIndex(refField.Index), nil |
| 589 | } |
| 590 | |
| 591 | // Type implements the ref.Val interface method. |
| 592 | func (o *nativeObj) Type() ref.Type { |
| 593 | return o.valType |
| 594 | } |
| 595 | |
| 596 | // Value implements the ref.Val interface method. |
| 597 | func (o *nativeObj) Value() any { |
| 598 | return o.val |
| 599 | } |
| 600 | |
| 601 | func newNativeTypes(fieldNameHandler NativeTypesFieldNameHandler, rawType reflect.Type) ([]*nativeType, error) { |
| 602 | nt, err := newNativeType(fieldNameHandler, rawType) |
| 603 | if err != nil { |
| 604 | return nil, err |
| 605 | } |
| 606 | result := []*nativeType{nt} |
| 607 | |
| 608 | alreadySeen := make(map[string]struct{}) |
| 609 | var iterateStructMembers func(reflect.Type) |
| 610 | iterateStructMembers = func(t reflect.Type) { |
| 611 | if k := t.Kind(); k == reflect.Pointer || k == reflect.Slice || k == reflect.Array || k == reflect.Map { |
| 612 | iterateStructMembers(t.Elem()) |
| 613 | return |
| 614 | } |
| 615 | if t.Kind() != reflect.Struct { |
| 616 | return |
| 617 | } |
| 618 | if _, seen := alreadySeen[t.String()]; seen { |
| 619 | return |
| 620 | } |
| 621 | alreadySeen[t.String()] = struct{}{} |
| 622 | nt, ntErr := newNativeType(fieldNameHandler, t) |
| 623 | if ntErr != nil { |
| 624 | err = ntErr |
| 625 | return |
| 626 | } |
| 627 | result = append(result, nt) |
| 628 | |
| 629 | for idx := 0; idx < t.NumField(); idx++ { |
| 630 | iterateStructMembers(t.Field(idx).Type) |
| 631 | } |
| 632 | } |
| 633 | iterateStructMembers(rawType) |
| 634 | |
| 635 | return result, err |
| 636 | } |
| 637 | |
| 638 | var ( |
| 639 | errDuplicatedFieldName = errors.New("field name already exists in struct") |
| 640 | ) |
| 641 | |
| 642 | func newNativeType(fieldNameHandler NativeTypesFieldNameHandler, rawType reflect.Type) (*nativeType, error) { |
| 643 | refType := rawType |
| 644 | if refType.Kind() == reflect.Pointer { |
| 645 | refType = refType.Elem() |
| 646 | } |
| 647 | if !isValidObjectType(refType) { |
| 648 | return nil, fmt.Errorf("unsupported reflect.Type %v, must be reflect.Struct", rawType) |
| 649 | } |
| 650 | |
| 651 | // Since naming collisions can only happen with struct tag parsing, we only check for them if it is enabled. |
| 652 | if fieldNameHandler != nil { |
| 653 | fieldNames := make(map[string]struct{}) |
| 654 | |
| 655 | for idx := 0; idx < refType.NumField(); idx++ { |
| 656 | field := refType.Field(idx) |
| 657 | fieldName := toFieldName(fieldNameHandler, field) |
| 658 | |
| 659 | if _, found := fieldNames[fieldName]; found { |
| 660 | return nil, fmt.Errorf("invalid field name `%s` in struct `%s`: %w", fieldName, refType.Name(), errDuplicatedFieldName) |
| 661 | } else { |
| 662 | fieldNames[fieldName] = struct{}{} |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | return &nativeType{ |
| 668 | typeName: fmt.Sprintf("%s.%s", simplePkgAlias(refType.PkgPath()), refType.Name()), |
| 669 | refType: refType, |
| 670 | fieldNameHandler: fieldNameHandler, |
| 671 | }, nil |
| 672 | } |
| 673 | |
| 674 | type nativeType struct { |
| 675 | typeName string |
| 676 | refType reflect.Type |
| 677 | fieldNameHandler NativeTypesFieldNameHandler |
| 678 | } |
| 679 | |
| 680 | // ConvertToNative implements ref.Val.ConvertToNative. |
| 681 | func (t *nativeType) ConvertToNative(typeDesc reflect.Type) (any, error) { |
| 682 | return nil, fmt.Errorf("type conversion error for type to '%v'", typeDesc) |
| 683 | } |
| 684 | |
| 685 | // ConvertToType implements ref.Val.ConvertToType. |
| 686 | func (t *nativeType) ConvertToType(typeVal ref.Type) ref.Val { |
| 687 | switch typeVal { |
| 688 | case types.TypeType: |
| 689 | return types.TypeType |
| 690 | } |
| 691 | return types.NewErr("type conversion error from '%s' to '%s'", types.TypeType, typeVal) |
| 692 | } |
| 693 | |
| 694 | // Equal returns true of both type names are equal to each other. |
| 695 | func (t *nativeType) Equal(other ref.Val) ref.Val { |
| 696 | otherType, ok := other.(ref.Type) |
| 697 | return types.Bool(ok && t.TypeName() == otherType.TypeName()) |
| 698 | } |
| 699 | |
| 700 | // HasTrait implements the ref.Type interface method. |
| 701 | func (t *nativeType) HasTrait(trait int) bool { |
| 702 | return nativeObjTraitMask&trait == trait |
| 703 | } |
| 704 | |
| 705 | // String implements the strings.Stringer interface method. |
| 706 | func (t *nativeType) String() string { |
| 707 | return t.typeName |
| 708 | } |
| 709 | |
| 710 | // Type implements the ref.Val interface method. |
| 711 | func (t *nativeType) Type() ref.Type { |
| 712 | return types.TypeType |
| 713 | } |
| 714 | |
| 715 | // TypeName implements the ref.Type interface method. |
| 716 | func (t *nativeType) TypeName() string { |
| 717 | return t.typeName |
| 718 | } |
| 719 | |
| 720 | // Value implements the ref.Val interface method. |
| 721 | func (t *nativeType) Value() any { |
| 722 | return t.typeName |
| 723 | } |
| 724 | |
| 725 | // fieldByName returns the corresponding reflect.StructField for the give name either by matching |
| 726 | // field tag or field name. |
| 727 | func (t *nativeType) fieldByName(fieldName string) (reflect.StructField, bool) { |
| 728 | if t.fieldNameHandler == nil { |
| 729 | return t.refType.FieldByName(fieldName) |
| 730 | } |
| 731 | |
| 732 | for i := 0; i < t.refType.NumField(); i++ { |
| 733 | f := t.refType.Field(i) |
| 734 | if toFieldName(t.fieldNameHandler, f) == fieldName { |
| 735 | return f, true |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | return reflect.StructField{}, false |
| 740 | } |
| 741 | |
| 742 | // hasField returns whether a field name has a corresponding Golang reflect.StructField |
| 743 | func (t *nativeType) hasField(fieldName string) (reflect.StructField, bool) { |
| 744 | f, found := t.fieldByName(fieldName) |
| 745 | if !found || !f.IsExported() || !isSupportedType(f.Type) { |
| 746 | return reflect.StructField{}, false |
| 747 | } |
| 748 | return f, true |
| 749 | } |
| 750 | |
| 751 | func adaptFieldValue(adapter types.Adapter, refField reflect.Value) ref.Val { |
| 752 | return adapter.NativeToValue(getFieldValue(refField)) |
| 753 | } |
| 754 | |
| 755 | func getFieldValue(refField reflect.Value) any { |
| 756 | if refField.IsZero() { |
| 757 | switch refField.Kind() { |
| 758 | case reflect.Struct: |
| 759 | if refField.Type() == timestampType { |
| 760 | return time.Unix(0, 0) |
| 761 | } |
| 762 | case reflect.Pointer: |
| 763 | return reflect.New(refField.Type().Elem()).Interface() |
| 764 | } |
| 765 | } |
| 766 | return refField.Interface() |
| 767 | } |
| 768 | |
| 769 | func simplePkgAlias(pkgPath string) string { |
| 770 | paths := strings.Split(pkgPath, "/") |
| 771 | if len(paths) == 0 { |
| 772 | return "" |
| 773 | } |
| 774 | return paths[len(paths)-1] |
| 775 | } |
| 776 | |
| 777 | func isValidObjectType(refType reflect.Type) bool { |
| 778 | return refType.Kind() == reflect.Struct |
| 779 | } |
| 780 | |
| 781 | func isSupportedType(refType reflect.Type) bool { |
| 782 | switch refType.Kind() { |
| 783 | case reflect.Chan, reflect.Complex64, reflect.Complex128, reflect.Func, reflect.UnsafePointer, reflect.Uintptr: |
| 784 | return false |
| 785 | case reflect.Array, reflect.Slice: |
| 786 | return isSupportedType(refType.Elem()) |
| 787 | case reflect.Map: |
| 788 | return isSupportedType(refType.Key()) && isSupportedType(refType.Elem()) |
| 789 | } |
| 790 | return true |
| 791 | } |
| 792 | |
| 793 | var ( |
| 794 | pbMsgInterfaceType = reflect.TypeOf((*protoreflect.ProtoMessage)(nil)).Elem() |
| 795 | timestampType = reflect.TypeOf(time.Now()) |
| 796 | durationType = reflect.TypeOf(time.Nanosecond) |
| 797 | ) |