fix(cloudwatch): bound inflated metric request bodies (#8490)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-15 14:51:29 -04:00
1 parent b13db563c9
commit dbfe6e0769
7 files changed
+292 -21

No files matched your search

+3 -3
View File
@@ -466,9 +466,9 @@ HTTP 404 `UnknownOperationException`. IAM policies use the `cloudwatch` action p
JSON `PutMetricData` accepts a gzip-compressed body (`Content-Encoding: gzip`), which the AWS
CLI, boto3 and the other SDKs that call CloudWatch over JSON send by default for any body of
10 KiB or more. With signature validation and IAM enforcement on, the signature is checked over
the compressed bytes as sent and IAM decides the request before the body is decompressed. As on
the CBOR protocol, the decompressed body is limited to 10 MiB: a larger one returns HTTP 413
`PayloadTooLargeException`, a body that cannot be decompressed returns HTTP 400
the compressed bytes as sent and IAM decides the request before the body is decompressed. The
decompressed body is limited to 5 MiB: a larger one returns HTTP 413
`RequestEntityTooLargeException`, a body that cannot be decompressed returns HTTP 400
`InvalidRequestException`, and an empty body reads as no input. Other JSON operations do not
decompress their body.
@@ -473,17 +473,20 @@ public class AwsJsonCborController {
}
static byte[] decodeBody(byte[] compressed) {
return decodeBody(compressed, 10 * 1024 * 1024, "PayloadTooLargeException");
}
static byte[] decodeBody(byte[] compressed, int maxRead, String tooLargeErrorCode) {
int buffSize = 64 * 1024;
byte[] buffer = new byte[buffSize]; // 10 MB limit max over all aws services, to avoid OOM. AWS services should not send more than 10 MB in a single request.
int totalRead = 0;
int maxRead = 10 * 1024 * 1024; // 10 MB limit max over all aws services, to avoid OOM. AWS services should not send more than 10 MB in a single request.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
int read;
while ((read = gis.read(buffer)) != -1) {
totalRead += read;
if (totalRead > maxRead) {
throw new AwsException("PayloadTooLargeException", "Payload Too Large", 413);
throw new AwsException(tooLargeErrorCode, "Payload Too Large", 413);
}
baos.write(buffer, 0, read);
}
@@ -27,8 +27,7 @@ import java.io.IOException;
* {@code *}. A condition key read from the body, such as {@code cloudwatch:namespace}, would need
* the body decompressed before IAM.
*
* <p>The decompressed body is bounded as the CBOR protocol bounds it
* ({@link AwsJsonCborController#decodeBody}), and a body that is too large or cannot be
* <p>The decompressed metric publication is bounded at 5 MiB, and a body that is too large or cannot be
* decompressed is refused in the controller's JSON error format. Every other request reads its
* body as sent.
*/
@@ -37,6 +36,8 @@ import java.io.IOException;
@Priority(Priorities.ENTITY_CODER)
public class CloudWatchGzipReaderInterceptor implements ReaderInterceptor {
private static final int DECOMPRESSED_LIMIT = 5 * 1024 * 1024;
private static final MediaType AWS_JSON_1_0 =
MediaType.valueOf(AwsJsonController.CONTENT_TYPE_AWS_JSON_1_0);
@@ -59,7 +60,7 @@ public class CloudWatchGzipReaderInterceptor implements ReaderInterceptor {
// No payload is an operation without input, as on the CBOR protocol, not a malformed gzip stream.
if (body.length > 0) {
try {
body = AwsJsonCborController.decodeBody(body);
body = AwsJsonCborController.decodeBody(body, DECOMPRESSED_LIMIT, "RequestEntityTooLargeException");
} catch (AwsException e) {
throw new WebApplicationException(JsonErrorResponseUtils.createErrorResponse(e));
}
@@ -0,0 +1,40 @@
package io.floci.aws.core.common;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static io.floci.aws.testing.GzipFixtures.gzip;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AwsJsonGzipBodyLimitTest {
@Test
void cloudWatchAcceptsItsExactLimit() throws IOException {
byte[] body = new byte[5 * 1024 * 1024];
assertArrayEquals(body, AwsJsonCborController.decodeBody(
gzip(body), body.length, "RequestEntityTooLargeException"));
}
@Test
void cloudWatchRejectsOneByteOverItsLimit() throws IOException {
byte[] body = new byte[5 * 1024 * 1024 + 1];
byte[] compressed = gzip(body);
AwsException error = assertThrows(AwsException.class, () ->
AwsJsonCborController.decodeBody(compressed, body.length - 1, "RequestEntityTooLargeException"));
assertEquals("RequestEntityTooLargeException", error.getErrorCode());
assertEquals(413, error.getHttpStatus());
}
@Test
void cborRetainsItsLargerLimitAndError() throws IOException {
byte[] body = new byte[10 * 1024 * 1024];
assertArrayEquals(body, AwsJsonCborController.decodeBody(gzip(body)));
byte[] compressed = gzip(new byte[body.length + 1]);
AwsException error = assertThrows(AwsException.class, () -> AwsJsonCborController.decodeBody(compressed));
assertEquals("PayloadTooLargeException", error.getErrorCode());
assertEquals(413, error.getHttpStatus());
}
}
@@ -0,0 +1,216 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.SignedIamEnforcementProfile;
import io.floci.aws.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import static io.floci.aws.testing.GzipFixtures.gzip;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
class CloudWatchGzipIntegrationTest {
private static final String JSON_1_0 = "application/x-amz-json-1.0";
private static final String TARGET = "GraniteServiceVersion20100801.";
private static final AwsRequestSigner ROOT = AwsRequestSigner.signedAs("test", "test", "monitoring");
@TestHTTPResource("/")
URI endpoint;
@BeforeAll
static void configureAwsContentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void compressedAndPlainPublicationStoreTheMetric(boolean compressed) throws Exception {
String namespace = namespace();
byte[] plain = publication(namespace);
request(ROOT, "PutMetricData", compressed ? gzip(plain) : plain, compressed ? "gzip" : null)
.then().statusCode(200);
list(namespace).then().statusCode(200).body("Metrics[0].MetricName", equalTo("Compressed"));
long now = Instant.now().getEpochSecond();
byte[] statistics = ("""
{"Namespace":"%s","MetricName":"Compressed","StartTime":%d,"EndTime":%d,
"Period":60,"Statistics":["Sum"]}
""".formatted(namespace, now - 120, now + 120)).getBytes(StandardCharsets.UTF_8);
request(ROOT, "GetMetricStatistics", statistics, null).then().statusCode(200)
.body("Datapoints[0].Sum", equalTo(7.0F));
}
@ParameterizedTest
@ValueSource(ints = {1024 * 1024 + 1, 5 * 1024 * 1024})
void decodedBodiesWithinTheLimitAreAccepted(int size) throws Exception {
String namespace = namespace();
request(ROOT, "PutMetricData", gzip(paddedPublication(namespace, size)), "gzip")
.then().statusCode(200);
list(namespace).then().body("Metrics[0].MetricName", equalTo("Compressed"));
}
@Test
void anOversizeDecodedBodyCannotPublishAMetric() throws Exception {
String namespace = namespace();
request(ROOT, "PutMetricData", gzip(paddedPublication(namespace, 5 * 1024 * 1024 + 1)), "gzip")
.then().statusCode(413).body("__type", equalTo("RequestEntityTooLargeException"));
assertAbsent(namespace);
}
@ParameterizedTest
@ValueSource(strings = {"invalid-header", "truncated", "invalid-crc"})
void malformedCompressedBodiesCannotPublishAMetric(String corruption) throws Exception {
String namespace = namespace();
byte[] body = gzip(publication(namespace));
switch (corruption) {
case "invalid-header" -> body[0] = 0;
case "truncated" -> body = Arrays.copyOf(body, body.length - 5);
case "invalid-crc" -> body[body.length - 8] ^= 1;
default -> throw new IllegalArgumentException(corruption);
}
request(ROOT, "PutMetricData", body, "gzip").then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
assertAbsent(namespace);
}
@Test
void decodedInvalidJsonRetainsTheSerializationError() throws Exception {
request(ROOT, "PutMetricData", gzip("{".getBytes(StandardCharsets.UTF_8)), "gzip")
.then().statusCode(400).body("__type", equalTo("SerializationException"));
}
@Test
void authenticationRejectsMalformedCompressedBytesBeforeDecoding() throws Exception {
request(ROOT.withSecret("wrong-secret"), "PutMetricData", new byte[]{1, 2, 3}, "gzip")
.then().statusCode(403).body("__type", equalTo("InvalidSignatureException"));
}
@Test
void iamStillDeniesPublicationAndAllowsOnlyTheGrantedRegion() throws Exception {
String user = "gzip-" + UUID.randomUUID();
String key = null;
iam("CreateUser", Map.of("UserName", user)).then().statusCode(200);
try {
Response credentials = iam("CreateAccessKey", Map.of("UserName", user));
credentials.then().statusCode(200);
key = credentials.xmlPath().getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
String secret = credentials.xmlPath()
.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey");
AwsRequestSigner signer = AwsRequestSigner.signedAs(key, secret, "monitoring");
String denied = namespace();
request(signer, "PutMetricData", gzip(publication(denied)), "gzip").then().statusCode(400)
.body("__type", equalTo("AccessDeniedException"));
assertAbsent(denied);
iam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "regional-publication", "PolicyDocument", """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Action":"cloudwatch:PutMetricData","Resource":"*",
"Condition":{"StringEquals":{"aws:RequestedRegion":"us-east-1"}}
}]}
""")).then().statusCode(200);
String allowed = namespace();
request(signer, "PutMetricData", gzip(publication(allowed)), "gzip").then().statusCode(200);
list(allowed).then().body("Metrics[0].MetricName", equalTo("Compressed"));
String wrongRegion = namespace();
request(signer.inRegion("us-west-2"), "PutMetricData", gzip(publication(wrongRegion)), "gzip")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
request(ROOT.inRegion("us-west-2"), "ListMetrics",
("{\"Namespace\":\"" + wrongRegion + "\"}").getBytes(StandardCharsets.UTF_8), null)
.then().body("Metrics", empty());
} finally {
if (key != null) {
iam("DeleteAccessKey", Map.of("UserName", user, "AccessKeyId", key)).then().statusCode(200);
}
iam("DeleteUserPolicy", Map.of("UserName", user, "PolicyName", "regional-publication"));
iam("DeleteUser", Map.of("UserName", user)).then().statusCode(200);
}
}
@Test
void otherCloudWatchOperationsKeepTheirExistingBodyHandling() throws Exception {
request(ROOT, "ListMetrics", gzip("{}".getBytes(StandardCharsets.UTF_8)), "gzip")
.then().statusCode(400).body("__type", equalTo("SerializationException"));
}
@ParameterizedTest
@ValueSource(strings = {"AWSStepFunctions.ListStateMachines", "TrentService.ListKeys"})
void otherServicesKeepTheirExistingBodyHandling(String target) throws Exception {
String service = target.startsWith("TrentService") ? "kms" : "states";
String contentType = service.equals("kms") ? "application/x-amz-json-1.1" : JSON_1_0;
byte[] body = gzip("{}".getBytes(StandardCharsets.UTF_8));
signedPost(AwsRequestSigner.signedAs("test", "test", service), target, contentType, body, "gzip")
.then().statusCode(400)
.body("__type", equalTo("SerializationException"));
}
private Response list(String namespace) throws Exception {
return request(ROOT, "ListMetrics",
("{\"Namespace\":\"" + namespace + "\"}").getBytes(StandardCharsets.UTF_8), null);
}
private void assertAbsent(String namespace) throws Exception {
list(namespace).then().statusCode(200).body("Metrics", empty());
}
private Response request(AwsRequestSigner signer, String operation, byte[] body, String encoding) throws Exception {
return signedPost(signer, TARGET + operation, JSON_1_0, body, encoding);
}
private Response signedPost(AwsRequestSigner signer, String target, String contentType,
byte[] body, String encoding) throws Exception {
Map<String, String> signed = new HashMap<>();
signed.put("x-amz-target", target);
if (encoding != null) {
signed.put("content-encoding", encoding);
}
return given().headers(signed).headers(signer.headersFor("POST", endpoint, signed, body))
.contentType(contentType).body(body).post(endpoint);
}
private Response iam(String action, Map<String, String> parameters) throws Exception {
String body = "Action=" + action + "&Version=2010-05-08&" + parameters.entrySet().stream()
.map(entry -> URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "="
+ URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
return given().headers(AwsRequestSigner.signedAs("test", "test", "iam")
.headersFor("POST", endpoint, Map.of(), body.getBytes(StandardCharsets.UTF_8)))
.contentType("application/x-www-form-urlencoded").body(body).post(endpoint);
}
private static String namespace() {
return "Floci/Gzip/" + UUID.randomUUID();
}
private static byte[] publication(String namespace) {
return ("{\"Namespace\":\"" + namespace
+ "\",\"MetricData\":[{\"MetricName\":\"Compressed\",\"Value\":7,\"Unit\":\"Count\"}]}")
.getBytes(StandardCharsets.UTF_8);
}
private static byte[] paddedPublication(String namespace, int size) {
byte[] plain = publication(namespace);
byte[] padded = Arrays.copyOf(plain, size);
Arrays.fill(padded, plain.length, padded.length, (byte) ' ');
return padded;
}
}
@@ -13,7 +13,6 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
@@ -22,8 +21,8 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.zip.GZIPOutputStream;
import static io.floci.aws.testing.GzipFixtures.gzip;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
@@ -42,7 +41,7 @@ class CloudWatchMetricsGzipJsonIntegrationTest {
private static final String JSON_1_0 = "application/x-amz-json-1.0";
private static final String TARGET = "GraniteServiceVersion20100801.";
private static final int DECOMPRESSED_LIMIT = 10 * 1024 * 1024;
private static final int DECOMPRESSED_LIMIT = 5 * 1024 * 1024;
private static final AwsRequestSigner ROOT = AwsRequestSigner.signedAs("test", "test", "monitoring");
@TestHTTPResource("/")
@@ -90,8 +89,8 @@ class CloudWatchMetricsGzipJsonIntegrationTest {
String namespace = namespace();
request(ROOT, "PutMetricData", gzip(paddedPublication(namespace, DECOMPRESSED_LIMIT + 1)), "gzip")
.then().statusCode(413)
.header("x-amzn-query-error", "PayloadTooLargeException;Sender")
.body("__type", equalTo("PayloadTooLargeException"));
.header("x-amzn-query-error", "RequestEntityTooLargeException;Sender")
.body("__type", equalTo("RequestEntityTooLargeException"));
assertAbsent(namespace);
}
@@ -240,12 +239,4 @@ class CloudWatchMetricsGzipJsonIntegrationTest {
Arrays.fill(padded, plain.length, padded.length, (byte) ' ');
return padded;
}
private static byte[] gzip(byte[] plain) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try (GZIPOutputStream compressed = new GZIPOutputStream(result)) {
compressed.write(plain);
}
return result.toByteArray();
}
}
@@ -0,0 +1,20 @@
package io.floci.aws.testing;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
/** Gzip request bodies shared by protocol and decoded-size tests. */
public final class GzipFixtures {
private GzipFixtures() {
}
public static byte[] gzip(byte[] body) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (GZIPOutputStream stream = new GZIPOutputStream(output)) {
stream.write(body);
}
return output.toByteArray();
}
}