Skip to content

Commit 36e46c5

Browse files
l46kokcopybara-github
authored andcommitted
Fix bytes to string conversion to explicitly error on invalid code points
Fixes #716 PiperOrigin-RevId: 768102889
1 parent 78d9d93 commit 36e46c5

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

runtime/src/main/java/dev/cel/runtime/CelStandardFunctions.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -890,7 +890,18 @@ public enum Conversions implements StandardOverload {
890890
BYTES_TO_STRING(
891891
(bindingHelper) ->
892892
CelFunctionBinding.from(
893-
"bytes_to_string", ByteString.class, ByteString::toStringUtf8)),
893+
"bytes_to_string",
894+
ByteString.class,
895+
(byteStr) -> {
896+
if (!byteStr.isValidUtf8()) {
897+
throw new CelRuntimeException(
898+
new IllegalArgumentException(
899+
"invalid UTF-8 in bytes, cannot convert to string"),
900+
CelErrorCode.BAD_FORMAT);
901+
}
902+
903+
return byteStr.toStringUtf8();
904+
})),
894905
TIMESTAMP_TO_STRING(
895906
(bindingHelper) ->
896907
CelFunctionBinding.from(
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Source: string(b'\xff')
2+
=====>
3+
bindings: {}
4+
error: evaluation error at test_location:6: invalid UTF-8 in bytes, cannot convert to string
5+
error_code: BAD_FORMAT

testing/src/main/java/dev/cel/testing/BaseInterpreterTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,12 @@ public void stringConversions() {
16791679
runTest();
16801680
}
16811681

1682+
@Test
1683+
public void stringConversions_error() throws Exception {
1684+
source = "string(b'\\xff')";
1685+
runTest();
1686+
}
1687+
16821688
@Test
16831689
public void bytes() throws Exception {
16841690
source =

0 commit comments

Comments
 (0)