Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ext/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ go_library(
"//common/types/traits:go_default_library",
"//interpreter:go_default_library",
"//parser:go_default_library",
"@org_golang_google_protobuf//encoding/protojson:go_default_library",
"@org_golang_google_protobuf//proto:go_default_library",
"@org_golang_google_protobuf//reflect/protoreflect:go_default_library",
"@org_golang_google_protobuf//types/known/structpb",
Expand Down
14 changes: 14 additions & 0 deletions ext/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,20 @@ Example:

base64.encode(b'hello') // return 'aGVsbG8='

### JSON.Encode

Introduced at version: 1

Encodes a CEL value to a JSON string.

json.encode(<dyn>) -> <string>

Examples:

json.encode('hello') // return '"hello"'
json.encode([1, 'two', true]) // return '[1,"two",true]'
json.encode({'items': [1, 'two', false]}) // return '{"items":[1,"two",false]}'

## Math

Math helper macros and functions.
Expand Down
45 changes: 43 additions & 2 deletions ext/encoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ package ext

import (
"encoding/base64"
"fmt"
"math"

"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"google.golang.org/protobuf/encoding/protojson"
Comment thread
TristonianJones marked this conversation as resolved.
"google.golang.org/protobuf/types/known/structpb"
)

// Encoders returns a cel.EnvOption to configure extended functions for string, byte, and object
Expand Down Expand Up @@ -48,6 +51,18 @@ import (
// Examples:
//
// base64.encode(b'hello') // return b'aGVsbG8='
//
// # JSON.Encode
//
// Introduced at version: 1
//
// Encodes a CEL value to a JSON string.
//
// json.encode(<dyn>) -> <string>
//
// Examples:
//
// json.encode({'hello': 'world'}) // return '{"hello":"world"}'
Comment thread
TristonianJones marked this conversation as resolved.
func Encoders(options ...EncodersOption) cel.EnvOption {
Comment thread
TristonianJones marked this conversation as resolved.
l := &encoderLib{version: math.MaxUint32}
for _, o := range options {
Expand Down Expand Up @@ -75,8 +90,8 @@ func (*encoderLib) LibraryName() string {
return "cel.lib.ext.encoders"
}

func (*encoderLib) CompileOptions() []cel.EnvOption {
return []cel.EnvOption{
func (lib *encoderLib) CompileOptions() []cel.EnvOption {
opts := []cel.EnvOption{
cel.Function("base64.decode",
cel.Overload("base64_decode_string", []*cel.Type{cel.StringType}, cel.BytesType,
cel.UnaryBinding(func(str ref.Val) ref.Val {
Expand All @@ -90,6 +105,16 @@ func (*encoderLib) CompileOptions() []cel.EnvOption {
return stringOrError(base64EncodeBytes([]byte(b)))
}))),
}
if lib.version >= 1 {
opts = append(opts,
cel.Function("json.encode",
cel.Overload("json_encode_dyn", []*cel.Type{cel.DynType}, cel.StringType,
cel.UnaryBinding(func(val ref.Val) ref.Val {
return stringOrError(jsonEncodeValue(val))
}))),
)
}
return opts
}

func (*encoderLib) ProgramOptions() []cel.ProgramOption {
Expand All @@ -110,3 +135,19 @@ func base64DecodeString(str string) ([]byte, error) {
func base64EncodeBytes(bytes []byte) (string, error) {
return base64.StdEncoding.EncodeToString(bytes), nil
}

func jsonEncodeValue(val ref.Val) (string, error) {
native, err := val.ConvertToNative(types.JSONValueType)
if err != nil {
return "", err
}
jsonValue, ok := native.(*structpb.Value)
if !ok {
return "", fmt.Errorf("cannot convert %T to JSON value", native)
}
jsonBytes, err := protojson.Marshal(jsonValue)
if err != nil {
return "", err
}
return string(jsonBytes), nil
}
19 changes: 18 additions & 1 deletion ext/encoders_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ func TestEncoders(t *testing.T) {
err: "no such overload",
parseOnly: true,
},
{expr: "json.encode('hello') == '\"hello\"'"},
{expr: "json.encode([1, 'two', true]) == '[1,\"two\",true]'"},
{expr: "json.encode({'items': [1, 'two', false]}) == '{\"items\":[1,\"two\",false]}'"},
}

env, err := cel.NewEnv(Encoders())
Expand Down Expand Up @@ -88,8 +91,22 @@ func TestEncoders(t *testing.T) {
}

func TestEncodersVersion(t *testing.T) {
_, err := cel.NewEnv(Encoders(EncodersVersion(0)))
env, err := cel.NewEnv(Encoders(EncodersVersion(0)))
if err != nil {
t.Fatalf("EncodersVersion(0) failed: %v", err)
}
if _, iss := env.Compile("base64.encode(b'hello')"); iss.Err() != nil {
t.Fatalf("base64.encode() got %v, wanted no error", iss.Err())
}
if _, iss := env.Compile("json.encode('hello')"); iss.Err() == nil {
t.Fatal("json.encode() got no error, wanted version-gated function to be unavailable")
}

env, err = cel.NewEnv(Encoders(EncodersVersion(1)))
if err != nil {
t.Fatalf("EncodersVersion(1) failed: %v", err)
}
if _, iss := env.Compile("json.encode('hello')"); iss.Err() != nil {
t.Fatalf("json.encode() got %v, wanted no error", iss.Err())
}
}