Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions src/main/java/io/getstream/chat/java/models/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@
import io.getstream.chat.java.services.AppService;
import io.getstream.chat.java.services.framework.Client;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
Expand Down Expand Up @@ -1535,22 +1533,40 @@ public static boolean verifySignature(

private static final byte[] GZIP_MAGIC = new byte[] {0x1f, (byte) 0x8b};

/**
* Maximum decompressed size, in bytes, of a gzip webhook, SQS or SNS payload. Defaults to 10 MiB.
* Decompression runs before the signature check, so without a cap an unsigned gzip bomb could
* exhaust memory. Raise it if your events are larger.
*/
public static long maxWebhookPayloadBytes = 10L * 1024 * 1024;

/**
* Returns {@code body} unchanged unless it starts with the gzip magic ({@code 1f 8b}, per RFC
* 1952), in which case the gzip stream is inflated and the decompressed bytes are returned.
*
* <p>Magic-byte detection (rather than relying on a header) lets the same handler stay correct
* when middleware auto-decompresses the request before your code sees it.
*
* @throws InvalidWebhookError when the gzip stream is malformed or decompresses to more than
* {@link #maxWebhookPayloadBytes}
*/
public static byte[] gunzipPayload(@NotNull byte[] body) {
if (body.length < 2 || body[0] != GZIP_MAGIC[0] || body[1] != GZIP_MAGIC[1]) {
return body;
}
long limit = maxWebhookPayloadBytes;
byte[] out;
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(body))) {
return readAll(in);
// One byte past the limit is enough to detect a bomb without inflating the rest of it.
out = in.readNBytes((int) Math.min(limit, Integer.MAX_VALUE - 1) + 1);
} catch (IOException e) {
throw new InvalidWebhookError(InvalidWebhookError.GZIP_FAILED, e);
}
if (out.length > limit) {
throw new InvalidWebhookError(
InvalidWebhookError.GZIP_FAILED + ": payload exceeds " + limit + " bytes");
}
return out;
}

/**
Expand Down Expand Up @@ -1690,16 +1706,6 @@ private static ObjectMapper buildWebhookObjectMapper() {
return parseEvent(decodeSnsPayload(notificationBody));
}

private static byte[] readAll(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
}
return out.toByteArray();
}

private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
Expand Down
75 changes: 75 additions & 0 deletions src/test/java/io/getstream/chat/java/WebhookCompressionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,81 @@ void gunzipPayload_truncatedGzipThrows() {
Assertions.assertEquals(InvalidWebhookError.GZIP_FAILED, ex.getMessage());
}

@Test
@DisplayName("gunzipPayload throws on corrupt deflate data")
void gunzipPayload_corruptDeflateThrows() throws Exception {
byte[] bad = gzip(JSON_BODY.getBytes(StandardCharsets.UTF_8));
for (int i = 10; i < 14; i++) {
bad[i] = (byte) 0xff;
}
InvalidWebhookError ex =
Assertions.assertThrows(InvalidWebhookError.class, () -> App.gunzipPayload(bad));
Assertions.assertEquals(InvalidWebhookError.GZIP_FAILED, ex.getMessage());
}

@Test
@DisplayName("gunzipPayload inflates a body of exactly the default 10 MiB limit")
void gunzipPayload_inflatesBodyAtLimit() throws Exception {
long limit = App.maxWebhookPayloadBytes;
Assertions.assertEquals(10L * 1024 * 1024, limit);
Assertions.assertEquals(limit, App.gunzipPayload(gzip(new byte[(int) limit])).length);
}

@Test
@DisplayName("gzip bomb is rejected before the signature check and on the SQS path")
void gunzipPayload_rejectsBomb() throws Exception {
long limit = App.maxWebhookPayloadBytes;
byte[] bomb = gzip(new byte[(int) limit + 1]);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests do not prove the bounded read. Swapping the readNBytes(...) call for in.readAllBytes() (inflate everything, then compare the length) keeps all 34 tests in this class green, so a later refactor could bring the gzip bomb back unnoticed.

A cheap test that fails on that regression: corrupt the trailer CRC and use a small cap. Only a read that stops at limit + 1 returns the size error; an unbounded read reaches the CRC check first and throws plain gzip decompression failed.

@Test
void gunzipPayload_stopsReadingPastLimit() throws Exception {
  long original = App.maxWebhookPayloadBytes;
  try {
    byte[] body = gzip(new byte[100]);
    body[body.length - 8] ^= 0x01; // corrupt CRC32 in the trailer
    App.maxWebhookPayloadBytes = 10;
    InvalidWebhookError ex =
        Assertions.assertThrows(InvalidWebhookError.class, () -> App.gunzipPayload(body));
    Assertions.assertEquals(
        InvalidWebhookError.GZIP_FAILED + ": payload exceeds 10 bytes", ex.getMessage());
  } finally {
    App.maxWebhookPayloadBytes = original;
  }
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 161bf84.

InvalidWebhookError ex =
Assertions.assertThrows(
InvalidWebhookError.class,
() -> App.verifyAndParseWebhook(bomb, "0".repeat(64), API_SECRET));
Assertions.assertEquals(
InvalidWebhookError.GZIP_FAILED + ": payload exceeds " + limit + " bytes", ex.getMessage());
ex = Assertions.assertThrows(InvalidWebhookError.class, () -> App.parseSqs(base64(bomb)));
Assertions.assertEquals(
InvalidWebhookError.GZIP_FAILED + ": payload exceeds " + limit + " bytes", ex.getMessage());
}

@Test
@DisplayName("gunzipPayload honours a custom limit and leaves uncompressed bodies unlimited")
void gunzipPayload_customLimit() throws Exception {
long original = App.maxWebhookPayloadBytes;
byte[] raw = JSON_BODY.getBytes(StandardCharsets.UTF_8);
try {
App.maxWebhookPayloadBytes = raw.length - 1;
InvalidWebhookError ex =
Assertions.assertThrows(InvalidWebhookError.class, () -> App.gunzipPayload(gzip(raw)));
Assertions.assertEquals(
InvalidWebhookError.GZIP_FAILED + ": payload exceeds " + (raw.length - 1) + " bytes",
ex.getMessage());
App.maxWebhookPayloadBytes = raw.length;
Assertions.assertArrayEquals(raw, App.gunzipPayload(gzip(raw)));
App.maxWebhookPayloadBytes = 1;
Assertions.assertArrayEquals(raw, App.gunzipPayload(raw));
} finally {
App.maxWebhookPayloadBytes = original;
}
}

@Test
@DisplayName("gunzipPayload stops inflating one byte past the limit")
void gunzipPayload_stopsReadingPastLimit() throws Exception {
long original = App.maxWebhookPayloadBytes;
try {
byte[] body = gzip(new byte[100]);
// A read that inflates to the end hits this corrupt trailer CRC and fails differently.
body[body.length - 8] ^= 0x01;
App.maxWebhookPayloadBytes = 10;
InvalidWebhookError ex =
Assertions.assertThrows(InvalidWebhookError.class, () -> App.gunzipPayload(body));
Assertions.assertEquals(
InvalidWebhookError.GZIP_FAILED + ": payload exceeds 10 bytes", ex.getMessage());
} finally {
App.maxWebhookPayloadBytes = original;
}
}

@Test
@DisplayName("decodeSqsPayload decodes base64 only when no compression")
void decodeSqsPayload_base64Only() {
Expand Down
Loading