Skip to content
Open
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
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"
"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"}'
func Encoders(options ...EncodersOption) cel.EnvOption {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make sure to add a new version bump for the added encoder.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Added json.encode as encoder version 1, gated it behind EncodersVersion(1), and added version tests.

go test ./ext passes locally.

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())
}
}