Skip to content

Commit

Permalink
Validate that ASCII Metadata values contain only printable ASCII char…
Browse files Browse the repository at this point in the history
…acter the same way grpc-go validates the Metadata.

closes grpc#11679
  • Loading branch information
CoolTomatos committed Nov 19, 2024
1 parent e58c998 commit c6d02f2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
10 changes: 7 additions & 3 deletions api/src/main/java/io/grpc/Metadata.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,19 @@ public byte[] parseBytes(byte[] serialized) {
* Simple metadata marshaller that encodes strings as is.
*
* <p>This should be used with ASCII strings that only contain the characters listed in the class
* comment of {@link AsciiMarshaller}. Otherwise the output may be considered invalid and
* discarded by the transport, or the call may fail.
* comment of {@link AsciiMarshaller}. Otherwise an {@link IllegalArgumentException} will be
* thrown.
*/
public static final AsciiMarshaller<String> ASCII_STRING_MARSHALLER =
new AsciiMarshaller<String>() {

@Override
public String toAsciiString(String value) {
return value;
checkArgument(
value.chars().allMatch(c -> c >= 0x20 && c <= 0x7E),
"String \"%s\" contains non-printable ASCII characters",
value);
return value.trim();
}

@Override
Expand Down
11 changes: 11 additions & 0 deletions api/src/test/java/io/grpc/MetadataTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,17 @@ public void createFromPartial() {
assertSame(anotherSalmon, h2.get(KEY_IMMUTABLE));
}

@Test
public void failNonPrintableAsciiCharacters() {
String value = "José";

thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("String \"" + value + "\" contains non-printable ASCII characters");

Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("test-non-printable", Metadata.ASCII_STRING_MARSHALLER), value);
}

private static final class Fish {
private String name;

Expand Down

0 comments on commit c6d02f2

Please sign in to comment.