Skip to content

Commit c6d02f2

Browse files
committed
Validate that ASCII Metadata values contain only printable ASCII character the same way grpc-go validates the Metadata.
closes #11679
1 parent e58c998 commit c6d02f2

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

Diff for: api/src/main/java/io/grpc/Metadata.java

+7-3
Original file line numberDiff line numberDiff line change
@@ -94,15 +94,19 @@ public byte[] parseBytes(byte[] serialized) {
9494
* Simple metadata marshaller that encodes strings as is.
9595
*
9696
* <p>This should be used with ASCII strings that only contain the characters listed in the class
97-
* comment of {@link AsciiMarshaller}. Otherwise the output may be considered invalid and
98-
* discarded by the transport, or the call may fail.
97+
* comment of {@link AsciiMarshaller}. Otherwise an {@link IllegalArgumentException} will be
98+
* thrown.
9999
*/
100100
public static final AsciiMarshaller<String> ASCII_STRING_MARSHALLER =
101101
new AsciiMarshaller<String>() {
102102

103103
@Override
104104
public String toAsciiString(String value) {
105-
return value;
105+
checkArgument(
106+
value.chars().allMatch(c -> c >= 0x20 && c <= 0x7E),
107+
"String \"%s\" contains non-printable ASCII characters",
108+
value);
109+
return value.trim();
106110
}
107111

108112
@Override

Diff for: api/src/test/java/io/grpc/MetadataTest.java

+11
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,17 @@ public void createFromPartial() {
478478
assertSame(anotherSalmon, h2.get(KEY_IMMUTABLE));
479479
}
480480

481+
@Test
482+
public void failNonPrintableAsciiCharacters() {
483+
String value = "José";
484+
485+
thrown.expect(IllegalArgumentException.class);
486+
thrown.expectMessage("String \"" + value + "\" contains non-printable ASCII characters");
487+
488+
Metadata metadata = new Metadata();
489+
metadata.put(Metadata.Key.of("test-non-printable", Metadata.ASCII_STRING_MARSHALLER), value);
490+
}
491+
481492
private static final class Fish {
482493
private String name;
483494

0 commit comments

Comments
 (0)