diff --git a/compatibility-tests/sdk-test-python/tests/test_cloudwatch.py b/compatibility-tests/sdk-test-python/tests/test_cloudwatch.py index 6baa1736ab..bd30465579 100644 --- a/compatibility-tests/sdk-test-python/tests/test_cloudwatch.py +++ b/compatibility-tests/sdk-test-python/tests/test_cloudwatch.py @@ -157,6 +157,41 @@ class TestCloudWatchMetrics: assert dp["Maximum"] == 40.0 assert dp["Average"] == 30.0 # sum / sampleCount + def test_put_metric_data_compressed_batch(self, cloudwatch_client, unique_name): + """Test a PutMetricData body past 10 KiB, which botocore sends gzip-compressed.""" + namespace = f"TestApp/CompressedBatch/{unique_name}" + now = datetime.datetime.now(datetime.timezone.utc) + metric_data = [ + { + "MetricName": "BatchRequests", + "Value": 1.0, + "Unit": "Count", + "Timestamp": now, + "Dimensions": [{"Name": "Host", "Value": f"host-{i:03d}-" + "x" * 60}], + } + for i in range(100) + ] + names = ("Content-Encoding", "Content-Type") + sent = [] + + def record_headers(request, **kwargs): + sent.append({name: request.headers.get(name) for name in names}) + + event = "before-send.cloudwatch.PutMetricData" + cloudwatch_client.meta.events.register(event, record_headers) + try: + cloudwatch_client.put_metric_data(Namespace=namespace, MetricData=metric_data) + finally: + cloudwatch_client.meta.events.unregister(event, record_headers) + + assert len(sent) == 1 + headers = {name: v.decode() if isinstance(v, bytes) else v for name, v in sent[0].items()} + assert headers["Content-Encoding"] == "gzip" + # JSON 1.0 is the path this covers; a CBOR request would reach a decoder that predates it. + assert headers["Content-Type"] == "application/x-amz-json-1.0" + response = cloudwatch_client.list_metrics(Namespace=namespace, MetricName="BatchRequests") + assert len(response["Metrics"]) == 100 + class TestCloudWatchAlarms: """Test CloudWatch alarm operations.""" diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index b18199acc9..cf34032aa6 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -369,6 +369,15 @@ legacy `2009-05-15` API, which supports only `ListMetrics` and `GetMetricStatist An invalid version or action returns HTTP 404 `InvalidAction`; an absent action returns HTTP 404 `UnknownOperationException`. IAM policies use the `cloudwatch` action prefix. +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 +`InvalidRequestException`, and an empty body reads as no input. Other JSON operations do not +decompress their body. + **Endpoint:** `http://localhost:4566/`. Query: GET or POST; JSON: POST. JSON 1.0 requests name their operation in `X-Amz-Target` with the `GraniteServiceVersion20100801.` diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java index 515da6aedb..80dca3800e 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java @@ -36,10 +36,14 @@ import org.jboss.logging.Logger; * - DynamoDB (DynamoDB_20120810.*) * - SQS (AmazonSQS.*) *
+ * A gzip-encoded CloudWatch {@code PutMetricData} body arrives here decompressed, by + * {@link CloudWatchGzipReaderInterceptor}. + *
* Requests run on virtual threads: SQS ReceiveMessage and Step Functions GetActivityTask wait up * to 20 and 60 seconds for work, and that wait must not hold one of the shared request workers. */ @Path("/") +@CloudWatchGzipBody public class AwsJsonController { public static final String CONTENT_TYPE_AWS_JSON_1_0 = "application/x-amz-json-1.0"; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/CloudWatchGzipBody.java b/src/main/java/io/github/hectorvent/floci/core/common/CloudWatchGzipBody.java new file mode 100644 index 0000000000..d1d98e2c61 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/CloudWatchGzipBody.java @@ -0,0 +1,21 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.ws.rs.NameBinding; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Binds {@link CloudWatchGzipReaderInterceptor} to the resources annotated with it; every other + * resource reads its body with no reader interceptor. For each intercepted read Quarkus REST + * builds an interceptor context and looks up the resource method's parameter annotations + * reflectively, a lookup that fails in Floci's native image for the tag endpoints resources + * inherit from {@link AbstractTagsController}. + */ +@NameBinding +@Target({ElementType.TYPE, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface CloudWatchGzipBody { +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/CloudWatchGzipReaderInterceptor.java b/src/main/java/io/github/hectorvent/floci/core/common/CloudWatchGzipReaderInterceptor.java new file mode 100644 index 0000000000..fec9b66229 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/CloudWatchGzipReaderInterceptor.java @@ -0,0 +1,79 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.annotation.Priority; +import jakarta.inject.Inject; +import jakarta.ws.rs.Priorities; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.ext.Provider; +import jakarta.ws.rs.ext.ReaderInterceptor; +import jakarta.ws.rs.ext.ReaderInterceptorContext; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +/** + * Decompresses a gzip-encoded JSON 1.0 {@code PutMetricData} body for {@link AwsJsonController}. + * It is the one operation the AWS CLI and the SDKs that call CloudWatch over JSON compress, which + * by default they do for any body of 10 KiB or more. + * + *
An entity interceptor runs when the resource method reads its body, after every request + * filter. By then {@link SigV4HeaderSignatureFilter} has verified the signature over the + * compressed bytes as sent, which are the bytes the client signed, and {@link IamEnforcementFilter} + * has decided the request from its {@code X-Amz-Target}. Deciding before decompression is sound + * only because nothing in the {@code PutMetricData} decision comes from the body: its resource is + * {@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
+ * decompressed is refused in the controller's JSON error format. Every other request reads its
+ * body as sent.
+ */
+@Provider
+@CloudWatchGzipBody
+@Priority(Priorities.ENTITY_CODER)
+public class CloudWatchGzipReaderInterceptor implements ReaderInterceptor {
+
+ private static final MediaType AWS_JSON_1_0 =
+ MediaType.valueOf(AwsJsonController.CONTENT_TYPE_AWS_JSON_1_0);
+
+ private final ResolvedServiceCatalog catalog;
+
+ @Inject
+ public CloudWatchGzipReaderInterceptor(ResolvedServiceCatalog catalog) {
+ this.catalog = catalog;
+ }
+
+ @Override
+ public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException {
+ MultivaluedMap Signature validation and IAM enforcement come from {@link SignedIamEnforcementProfile}.
+ */
+@QuarkusTest
+@TestProfile(SignedIamEnforcementProfile.class)
+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 AwsRequestSigner ROOT = AwsRequestSigner.signedAs("test", "test", "monitoring");
+
+ @TestHTTPResource("/")
+ URI endpoint;
+
+ @BeforeAll
+ static void configureAwsContentTypes() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"none", "gzip", "GZIP"})
+ void aCompressedPublicationIsStoredLikeAPlainOne(String encoding) throws Exception {
+ String namespace = namespace();
+ byte[] plain = publication(namespace);
+ boolean compressed = !"none".equals(encoding);
+ request(ROOT, "PutMetricData", compressed ? gzip(plain) : plain, compressed ? encoding : null)
+ .then().statusCode(200);
+ 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));
+ }
+
+ @Test
+ void anOperationNameTheHandlerUpperCasesIsDecompressedToo() throws Exception {
+ String namespace = namespace();
+ request(ROOT, "putMetricData", gzip(publication(namespace)), "gzip").then().statusCode(200);
+ list(namespace).then().statusCode(200).body("Metrics[0].MetricName", equalTo("Compressed"));
+ }
+
+ @Test
+ void aBodyThatDecompressesToTheLimitIsAccepted() throws Exception {
+ String namespace = namespace();
+ request(ROOT, "PutMetricData", gzip(paddedPublication(namespace, DECOMPRESSED_LIMIT)), "gzip")
+ .then().statusCode(200);
+ list(namespace).then().statusCode(200).body("Metrics[0].MetricName", equalTo("Compressed"));
+ }
+
+ @Test
+ void aBodyThatDecompressesPastTheLimitIsRefused() throws Exception {
+ 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"));
+ assertAbsent(namespace);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"invalid-header", "truncated", "invalid-crc"})
+ void aBodyThatIsNotValidGzipIsRefused(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)
+ .header("x-amzn-query-error", "InvalidRequestException;Sender")
+ .body("__type", equalTo("InvalidRequestException"));
+ assertAbsent(namespace);
+ }
+
+ @Test
+ void anEmptyBodyMarkedGzipReadsAsNoInputLikeAnEmptyPlainBody() throws Exception {
+ Response plain = request(ROOT, "PutMetricData", new byte[0], null);
+ request(ROOT, "PutMetricData", new byte[0], "gzip").then()
+ .statusCode(plain.statusCode())
+ .body(equalTo(plain.asString()));
+ }
+
+ @Test
+ void aDecompressedBodyThatIsNotJsonIsASerializationError() throws Exception {
+ request(ROOT, "PutMetricData", gzip("{".getBytes(StandardCharsets.UTF_8)), "gzip")
+ .then().statusCode(400).body("__type", equalTo("SerializationException"));
+ }
+
+ @Test
+ void theSignatureIsCheckedOverTheCompressedBytesBeforeTheyAreDecompressed() throws Exception {
+ String namespace = namespace();
+ byte[] plain = publication(namespace);
+ Map