| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package ext |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding/base64" |
| 19 |
"math" |
| 20 |
|
| 21 |
"github.com/google/cel-go/cel" |
| 22 |
"github.com/google/cel-go/common/types" |
| 23 |
"github.com/google/cel-go/common/types/ref" |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
func Encoders(options ...EncodersOption) cel.EnvOption { |
| 52 |
l := &encoderLib{version: math.MaxUint32} |
| 53 |
for _, o := range options { |
| 54 |
l = o(l) |
| 55 |
} |
| 56 |
return cel.Lib(l) |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
type EncodersOption func(*encoderLib) *encoderLib |
| 61 |
|
| 62 |
|
| 63 |
func EncodersVersion(version uint32) EncodersOption { |
| 64 |
return func(lib *encoderLib) *encoderLib { |
| 65 |
lib.version = version |
| 66 |
return lib |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
type encoderLib struct { |
| 71 |
version uint32 |
| 72 |
} |
| 73 |
|
| 74 |
func (*encoderLib) LibraryName() string { |
| 75 |
return "cel.lib.ext.encoders" |
| 76 |
} |
| 77 |
|
| 78 |
func (*encoderLib) CompileOptions() []cel.EnvOption { |
| 79 |
return []cel.EnvOption{ |
| 80 |
cel.Function("base64.decode", |
| 81 |
cel.Overload("base64_decode_string", []*cel.Type{cel.StringType}, cel.BytesType, |
| 82 |
cel.UnaryBinding(func(str ref.Val) ref.Val { |
| 83 |
s := str.(types.String) |
| 84 |
return bytesOrError(base64DecodeString(string(s))) |
| 85 |
}))), |
| 86 |
cel.Function("base64.encode", |
| 87 |
cel.Overload("base64_encode_bytes", []*cel.Type{cel.BytesType}, cel.StringType, |
| 88 |
cel.UnaryBinding(func(bytes ref.Val) ref.Val { |
| 89 |
b := bytes.(types.Bytes) |
| 90 |
return stringOrError(base64EncodeBytes([]byte(b))) |
| 91 |
}))), |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
func (*encoderLib) ProgramOptions() []cel.ProgramOption { |
| 96 |
return []cel.ProgramOption{} |
| 97 |
} |
| 98 |
|
| 99 |
func base64DecodeString(str string) ([]byte, error) { |
| 100 |
b, err := base64.StdEncoding.DecodeString(str) |
| 101 |
if err == nil { |
| 102 |
return b, nil |
| 103 |
} |
| 104 |
if _, tryAltEncoding := err.(base64.CorruptInputError); tryAltEncoding { |
| 105 |
return base64.RawStdEncoding.DecodeString(str) |
| 106 |
} |
| 107 |
return nil, err |
| 108 |
} |
| 109 |
|
| 110 |
func base64EncodeBytes(bytes []byte) (string, error) { |
| 111 |
return base64.StdEncoding.EncodeToString(bytes), nil |
| 112 |
} |