diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 421489f88e..27b9f7270c 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -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. diff --git a/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java b/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java index 36f5f0571f..93b012cb36 100644 --- a/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java +++ b/src/main/java/io/floci/aws/core/common/AwsJsonCborController.java @@ -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); } diff --git a/src/main/java/io/floci/aws/core/common/CloudWatchGzipReaderInterceptor.java b/src/main/java/io/floci/aws/core/common/CloudWatchGzipReaderInterceptor.java index ba7353bdea..342d5b53f2 100644 --- a/src/main/java/io/floci/aws/core/common/CloudWatchGzipReaderInterceptor.java +++ b/src/main/java/io/floci/aws/core/common/CloudWatchGzipReaderInterceptor.java @@ -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. * - *
The decompressed body is bounded as the CBOR protocol bounds it - * ({@link AwsJsonCborController#decodeBody}), and a body that is too large or cannot be + *
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));
}
diff --git a/src/test/java/io/floci/aws/core/common/AwsJsonGzipBodyLimitTest.java b/src/test/java/io/floci/aws/core/common/AwsJsonGzipBodyLimitTest.java
new file mode 100644
index 0000000000..3151cae541
--- /dev/null
+++ b/src/test/java/io/floci/aws/core/common/AwsJsonGzipBodyLimitTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/floci/aws/core/common/CloudWatchGzipIntegrationTest.java b/src/test/java/io/floci/aws/core/common/CloudWatchGzipIntegrationTest.java
new file mode 100644
index 0000000000..bc5c0fbca6
--- /dev/null
+++ b/src/test/java/io/floci/aws/core/common/CloudWatchGzipIntegrationTest.java
@@ -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