| 1 | // Copyright 2019 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 cel |
| 16 | |
| 17 | import ( |
| 18 | "errors" |
| 19 | "fmt" |
| 20 | "reflect" |
| 21 | |
| 22 | "google.golang.org/protobuf/proto" |
| 23 | |
| 24 | "github.com/google/cel-go/common" |
| 25 | "github.com/google/cel-go/common/ast" |
| 26 | "github.com/google/cel-go/common/types" |
| 27 | "github.com/google/cel-go/common/types/ref" |
| 28 | "github.com/google/cel-go/common/types/traits" |
| 29 | "github.com/google/cel-go/parser" |
| 30 | |
| 31 | celpb "cel.dev/expr" |
| 32 | exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 33 | anypb "google.golang.org/protobuf/types/known/anypb" |
| 34 | ) |
| 35 | |
| 36 | // CheckedExprToAst converts a checked expression proto message to an Ast. |
| 37 | func CheckedExprToAst(checkedExpr *exprpb.CheckedExpr) *Ast { |
| 38 | checked, _ := CheckedExprToAstWithSource(checkedExpr, nil) |
| 39 | return checked |
| 40 | } |
| 41 | |
| 42 | // CheckedExprToAstWithSource converts a checked expression proto message to an Ast, |
| 43 | // using the provided Source as the textual contents. |
| 44 | // |
| 45 | // In general the source is not necessary unless the AST has been modified between the |
| 46 | // `Parse` and `Check` calls as an `Ast` created from the `Parse` step will carry the source |
| 47 | // through future calls. |
| 48 | // |
| 49 | // Prefer CheckedExprToAst if loading expressions from storage. |
| 50 | func CheckedExprToAstWithSource(checkedExpr *exprpb.CheckedExpr, src Source) (*Ast, error) { |
| 51 | checked, err := ast.ToAST(checkedExpr) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | return &Ast{source: src, impl: checked}, nil |
| 56 | } |
| 57 | |
| 58 | // AstToCheckedExpr converts an Ast to an protobuf CheckedExpr value. |
| 59 | // |
| 60 | // If the Ast.IsChecked() returns false, this conversion method will return an error. |
| 61 | func AstToCheckedExpr(a *Ast) (*exprpb.CheckedExpr, error) { |
| 62 | if !a.IsChecked() { |
| 63 | return nil, fmt.Errorf("cannot convert unchecked ast") |
| 64 | } |
| 65 | return ast.ToProto(a.NativeRep()) |
| 66 | } |
| 67 | |
| 68 | // ParsedExprToAst converts a parsed expression proto message to an Ast. |
| 69 | func ParsedExprToAst(parsedExpr *exprpb.ParsedExpr) *Ast { |
| 70 | return ParsedExprToAstWithSource(parsedExpr, nil) |
| 71 | } |
| 72 | |
| 73 | // ParsedExprToAstWithSource converts a parsed expression proto message to an Ast, |
| 74 | // using the provided Source as the textual contents. |
| 75 | // |
| 76 | // In general you only need this if you need to recheck a previously checked |
| 77 | // expression, or if you need to separately check a subset of an expression. |
| 78 | // |
| 79 | // Prefer ParsedExprToAst if loading expressions from storage. |
| 80 | func ParsedExprToAstWithSource(parsedExpr *exprpb.ParsedExpr, src Source) *Ast { |
| 81 | info, _ := ast.ProtoToSourceInfo(parsedExpr.GetSourceInfo()) |
| 82 | if src == nil { |
| 83 | src = common.NewInfoSource(parsedExpr.GetSourceInfo()) |
| 84 | } |
| 85 | e, _ := ast.ProtoToExpr(parsedExpr.GetExpr()) |
| 86 | return &Ast{source: src, impl: ast.NewAST(e, info)} |
| 87 | } |
| 88 | |
| 89 | // AstToParsedExpr converts an Ast to an protobuf ParsedExpr value. |
| 90 | func AstToParsedExpr(a *Ast) (*exprpb.ParsedExpr, error) { |
| 91 | return &exprpb.ParsedExpr{ |
| 92 | Expr: a.Expr(), |
| 93 | SourceInfo: a.SourceInfo(), |
| 94 | }, nil |
| 95 | } |
| 96 | |
| 97 | // AstToString converts an Ast back to a string if possible. |
| 98 | // |
| 99 | // Note, the conversion may not be an exact replica of the original expression, but will produce |
| 100 | // a string that is semantically equivalent and whose textual representation is stable. |
| 101 | func AstToString(a *Ast) (string, error) { |
| 102 | return ExprToString(a.NativeRep().Expr(), a.NativeRep().SourceInfo()) |
| 103 | } |
| 104 | |
| 105 | // ExprToString converts an AST Expr node back to a string using macro call tracking metadata from |
| 106 | // source info if any macros are encountered within the expression. |
| 107 | func ExprToString(e ast.Expr, info *ast.SourceInfo) (string, error) { |
| 108 | return parser.Unparse(e, info) |
| 109 | } |
| 110 | |
| 111 | // RefValueToValue converts between ref.Val and google.api.expr.v1alpha1.Value. |
| 112 | // The result Value is the serialized proto form. The ref.Val must not be error or unknown. |
| 113 | func RefValueToValue(res ref.Val) (*exprpb.Value, error) { |
| 114 | return ValueAsAlphaProto(res) |
| 115 | } |
| 116 | |
| 117 | // ValueAsAlphaProto converts between ref.Val and google.api.expr.v1alpha1.Value. |
| 118 | // The result Value is the serialized proto form. The ref.Val must not be error or unknown. |
| 119 | func ValueAsAlphaProto(res ref.Val) (*exprpb.Value, error) { |
| 120 | canonical, err := ValueAsProto(res) |
| 121 | if err != nil { |
| 122 | return nil, err |
| 123 | } |
| 124 | alpha := &exprpb.Value{} |
| 125 | err = convertProto(canonical, alpha) |
| 126 | return alpha, err |
| 127 | } |
| 128 | |
| 129 | // RefValToExprValue converts between ref.Val and google.api.expr.v1alpha1.ExprValue. |
| 130 | // The result ExprValue is the serialized proto form. |
| 131 | func RefValToExprValue(res ref.Val) (*exprpb.ExprValue, error) { |
| 132 | return ExprValueAsAlphaProto(res) |
| 133 | } |
| 134 | |
| 135 | // ExprValueAsAlphaProto converts between ref.Val and google.api.expr.v1alpha1.ExprValue. |
| 136 | // The result ExprValue is the serialized proto form. |
| 137 | func ExprValueAsAlphaProto(res ref.Val) (*exprpb.ExprValue, error) { |
| 138 | canonical, err := ExprValueAsProto(res) |
| 139 | if err != nil { |
| 140 | return nil, err |
| 141 | } |
| 142 | alpha := &exprpb.ExprValue{} |
| 143 | err = convertProto(canonical, alpha) |
| 144 | return alpha, err |
| 145 | } |
| 146 | |
| 147 | // ExprValueAsProto converts between ref.Val and cel.expr.ExprValue. |
| 148 | // The result ExprValue is the serialized proto form. |
| 149 | func ExprValueAsProto(res ref.Val) (*celpb.ExprValue, error) { |
| 150 | switch res := res.(type) { |
| 151 | case *types.Unknown: |
| 152 | return &celpb.ExprValue{ |
| 153 | Kind: &celpb.ExprValue_Unknown{ |
| 154 | Unknown: &celpb.UnknownSet{ |
| 155 | Exprs: res.IDs(), |
| 156 | }, |
| 157 | }}, nil |
| 158 | case *types.Err: |
| 159 | return &celpb.ExprValue{ |
| 160 | Kind: &celpb.ExprValue_Error{ |
| 161 | Error: &celpb.ErrorSet{ |
| 162 | // Keeping the error code as UNKNOWN since there's no error codes associated with |
| 163 | // Cel-Go runtime errors. |
| 164 | Errors: []*celpb.Status{{Code: 2, Message: res.Error()}}, |
| 165 | }, |
| 166 | }, |
| 167 | }, nil |
| 168 | default: |
| 169 | val, err := ValueAsProto(res) |
| 170 | if err != nil { |
| 171 | return nil, err |
| 172 | } |
| 173 | return &celpb.ExprValue{ |
| 174 | Kind: &celpb.ExprValue_Value{Value: val}}, nil |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | // ValueAsProto converts between ref.Val and cel.expr.Value. |
| 179 | // The result Value is the serialized proto form. The ref.Val must not be error or unknown. |
| 180 | func ValueAsProto(res ref.Val) (*celpb.Value, error) { |
| 181 | switch res.Type() { |
| 182 | case types.BoolType: |
| 183 | return &celpb.Value{ |
| 184 | Kind: &celpb.Value_BoolValue{BoolValue: res.Value().(bool)}}, nil |
| 185 | case types.BytesType: |
| 186 | return &celpb.Value{ |
| 187 | Kind: &celpb.Value_BytesValue{BytesValue: res.Value().([]byte)}}, nil |
| 188 | case types.DoubleType: |
| 189 | return &celpb.Value{ |
| 190 | Kind: &celpb.Value_DoubleValue{DoubleValue: res.Value().(float64)}}, nil |
| 191 | case types.IntType: |
| 192 | return &celpb.Value{ |
| 193 | Kind: &celpb.Value_Int64Value{Int64Value: res.Value().(int64)}}, nil |
| 194 | case types.ListType: |
| 195 | l := res.(traits.Lister) |
| 196 | sz := l.Size().(types.Int) |
| 197 | elts := make([]*celpb.Value, 0, int64(sz)) |
| 198 | for i := types.Int(0); i < sz; i++ { |
| 199 | v, err := ValueAsProto(l.Get(i)) |
| 200 | if err != nil { |
| 201 | return nil, err |
| 202 | } |
| 203 | elts = append(elts, v) |
| 204 | } |
| 205 | return &celpb.Value{ |
| 206 | Kind: &celpb.Value_ListValue{ |
| 207 | ListValue: &celpb.ListValue{Values: elts}}}, nil |
| 208 | case types.MapType: |
| 209 | mapper := res.(traits.Mapper) |
| 210 | sz := mapper.Size().(types.Int) |
| 211 | entries := make([]*celpb.MapValue_Entry, 0, int64(sz)) |
| 212 | for it := mapper.Iterator(); it.HasNext().(types.Bool); { |
| 213 | k := it.Next() |
| 214 | v := mapper.Get(k) |
| 215 | kv, err := ValueAsProto(k) |
| 216 | if err != nil { |
| 217 | return nil, err |
| 218 | } |
| 219 | vv, err := ValueAsProto(v) |
| 220 | if err != nil { |
| 221 | return nil, err |
| 222 | } |
| 223 | entries = append(entries, &celpb.MapValue_Entry{Key: kv, Value: vv}) |
| 224 | } |
| 225 | return &celpb.Value{ |
| 226 | Kind: &celpb.Value_MapValue{ |
| 227 | MapValue: &celpb.MapValue{Entries: entries}}}, nil |
| 228 | case types.NullType: |
| 229 | return &celpb.Value{ |
| 230 | Kind: &celpb.Value_NullValue{}}, nil |
| 231 | case types.StringType: |
| 232 | return &celpb.Value{ |
| 233 | Kind: &celpb.Value_StringValue{StringValue: res.Value().(string)}}, nil |
| 234 | case types.TypeType: |
| 235 | typeName := res.(ref.Type).TypeName() |
| 236 | return &celpb.Value{Kind: &celpb.Value_TypeValue{TypeValue: typeName}}, nil |
| 237 | case types.UintType: |
| 238 | return &celpb.Value{ |
| 239 | Kind: &celpb.Value_Uint64Value{Uint64Value: res.Value().(uint64)}}, nil |
| 240 | default: |
| 241 | any, err := res.ConvertToNative(anyPbType) |
| 242 | if err != nil { |
| 243 | return nil, err |
| 244 | } |
| 245 | return &celpb.Value{ |
| 246 | Kind: &celpb.Value_ObjectValue{ObjectValue: any.(*anypb.Any)}}, nil |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | var ( |
| 251 | typeNameToTypeValue = map[string]ref.Val{ |
| 252 | "bool": types.BoolType, |
| 253 | "bytes": types.BytesType, |
| 254 | "double": types.DoubleType, |
| 255 | "null_type": types.NullType, |
| 256 | "int": types.IntType, |
| 257 | "list": types.ListType, |
| 258 | "map": types.MapType, |
| 259 | "string": types.StringType, |
| 260 | "type": types.TypeType, |
| 261 | "uint": types.UintType, |
| 262 | } |
| 263 | |
| 264 | anyPbType = reflect.TypeOf(&anypb.Any{}) |
| 265 | ) |
| 266 | |
| 267 | // ValueToRefValue converts between google.api.expr.v1alpha1.Value and ref.Val. |
| 268 | func ValueToRefValue(adapter types.Adapter, v *exprpb.Value) (ref.Val, error) { |
| 269 | return AlphaProtoAsValue(adapter, v) |
| 270 | } |
| 271 | |
| 272 | // AlphaProtoAsValue converts between google.api.expr.v1alpha1.Value and ref.Val. |
| 273 | func AlphaProtoAsValue(adapter types.Adapter, v *exprpb.Value) (ref.Val, error) { |
| 274 | canonical := &celpb.Value{} |
| 275 | if err := convertProto(v, canonical); err != nil { |
| 276 | return nil, err |
| 277 | } |
| 278 | return ProtoAsValue(adapter, canonical) |
| 279 | } |
| 280 | |
| 281 | // ProtoAsValue converts between cel.expr.Value and ref.Val. |
| 282 | func ProtoAsValue(adapter types.Adapter, v *celpb.Value) (ref.Val, error) { |
| 283 | switch v.Kind.(type) { |
| 284 | case *celpb.Value_NullValue: |
| 285 | return types.NullValue, nil |
| 286 | case *celpb.Value_BoolValue: |
| 287 | return types.Bool(v.GetBoolValue()), nil |
| 288 | case *celpb.Value_Int64Value: |
| 289 | return types.Int(v.GetInt64Value()), nil |
| 290 | case *celpb.Value_Uint64Value: |
| 291 | return types.Uint(v.GetUint64Value()), nil |
| 292 | case *celpb.Value_DoubleValue: |
| 293 | return types.Double(v.GetDoubleValue()), nil |
| 294 | case *celpb.Value_StringValue: |
| 295 | return types.String(v.GetStringValue()), nil |
| 296 | case *celpb.Value_BytesValue: |
| 297 | return types.Bytes(v.GetBytesValue()), nil |
| 298 | case *celpb.Value_ObjectValue: |
| 299 | any := v.GetObjectValue() |
| 300 | msg, err := anypb.UnmarshalNew(any, proto.UnmarshalOptions{DiscardUnknown: true}) |
| 301 | if err != nil { |
| 302 | return nil, err |
| 303 | } |
| 304 | return adapter.NativeToValue(msg), nil |
| 305 | case *celpb.Value_MapValue: |
| 306 | m := v.GetMapValue() |
| 307 | entries := make(map[ref.Val]ref.Val) |
| 308 | for _, entry := range m.Entries { |
| 309 | key, err := ProtoAsValue(adapter, entry.Key) |
| 310 | if err != nil { |
| 311 | return nil, err |
| 312 | } |
| 313 | pb, err := ProtoAsValue(adapter, entry.Value) |
| 314 | if err != nil { |
| 315 | return nil, err |
| 316 | } |
| 317 | entries[key] = pb |
| 318 | } |
| 319 | return adapter.NativeToValue(entries), nil |
| 320 | case *celpb.Value_ListValue: |
| 321 | l := v.GetListValue() |
| 322 | elts := make([]ref.Val, len(l.Values)) |
| 323 | for i, e := range l.Values { |
| 324 | rv, err := ProtoAsValue(adapter, e) |
| 325 | if err != nil { |
| 326 | return nil, err |
| 327 | } |
| 328 | elts[i] = rv |
| 329 | } |
| 330 | return adapter.NativeToValue(elts), nil |
| 331 | case *celpb.Value_TypeValue: |
| 332 | typeName := v.GetTypeValue() |
| 333 | tv, ok := typeNameToTypeValue[typeName] |
| 334 | if ok { |
| 335 | return tv, nil |
| 336 | } |
| 337 | return types.NewObjectTypeValue(typeName), nil |
| 338 | } |
| 339 | return nil, errors.New("unknown value") |
| 340 | } |
| 341 | |
| 342 | func convertProto(src, dst proto.Message) error { |
| 343 | pb, err := proto.Marshal(src) |
| 344 | if err != nil { |
| 345 | return err |
| 346 | } |
| 347 | err = proto.Unmarshal(pb, dst) |
| 348 | return err |
| 349 | } |