diff --git a/bmq-sdk/src/main/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtil.java b/bmq-sdk/src/main/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtil.java index 7882c606..05d3db6d 100644 --- a/bmq-sdk/src/main/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtil.java +++ b/bmq-sdk/src/main/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtil.java @@ -33,6 +33,10 @@ public static T decode(ByteBufferInputStream bbis, Type msgType) throws IOEx public static String getJsonFromInputStream(ByteBufferInputStream bbis) throws IOException { final int bytesAvailable = bbis.available(); + if (bytesAvailable == 0) { + throw new IOException("No bytes to decode"); + } + byte[] bytes = new byte[bytesAvailable]; final int bytesRead = bbis.read(bytes); @@ -48,7 +52,7 @@ public static String getJsonFromInputStream(ByteBufferInputStream bbis) throws I } final int padding = bytes[bytes.length - 1]; - if (padding < 0 || padding > 4) { + if (padding < 0 || padding > 4 || bytesAvailable <= padding) { throw new IOException("Invalid padding value encountered while decoding " + padding); } diff --git a/bmq-sdk/src/test/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtilTest.java b/bmq-sdk/src/test/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtilTest.java index dc1dc60e..e4a96a03 100644 --- a/bmq-sdk/src/test/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtilTest.java +++ b/bmq-sdk/src/test/java/com/bloomberg/bmq/impl/infr/codec/JsonDecoderUtilTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -231,6 +232,29 @@ void testDecodeStatus() throws IOException { assertEquals("Test", status.message()); } + @Test + void testGetJsonFromInvalidInput() { + assertThrows( + IOException.class, + () -> + JsonDecoderUtil.getJsonFromInputStream( + new ByteBufferInputStream(ByteBuffer.allocate(0)))); + + // Padding value is larger than the input + assertThrows( + IOException.class, + () -> + JsonDecoderUtil.getJsonFromInputStream( + new ByteBufferInputStream(ByteBuffer.wrap(new byte[] {'{', 3})))); + + // Input contains only padding + assertThrows( + IOException.class, + () -> + JsonDecoderUtil.getJsonFromInputStream( + new ByteBufferInputStream(ByteBuffer.wrap(new byte[] {2, 2})))); + } + @Test void testDecodeFromJsonFail() { JsonDecoderUtil.decodeFromJson("\"test_string\"", String.class);