fix(cloudwatch): decompress gzip JSON PutMetricData bodies (#7123)

* fix(cloudwatch): decompress gzip JSON PutMetricData bodies

The AWS CLI and the SDKs that speak JSON 1.0 to CloudWatch gzip a
PutMetricData body of 10 KiB or more and send Content-Encoding: gzip.
AwsJsonController binds the body as a String, so Floci read the
compressed bytes as text and every such request failed with HTTP 400
SerializationException. The metrics were never stored.

Add a reader interceptor that decompresses that one operation's body
when the controller reads it. It runs after every request filter, so
the signature is still verified over the compressed bytes the client
signed, and IAM still decides the request from X-Amz-Target first,
which is sound because nothing in that decision comes from the body.
The decompressed body is bounded by the decoder the CBOR protocol
already uses: past 10 MiB it returns HTTP 413 PayloadTooLargeException,
and a body that cannot be decompressed returns HTTP 400
InvalidRequestException, both in the controller's JSON error format.

A name binding keeps the interceptor on AwsJsonController alone, so
every other resource reads its body as before. In the native image a
global reader interceptor breaks the tag endpoints that resources
inherit from AbstractTagsController, because Quarkus REST then looks
their methods up reflectively.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudwatch): publish a compressed metric batch through boto3

botocore gzips a PutMetricData body of 10 KiB or more, and with the
pinned boto3 it calls CloudWatch over JSON 1.0. The Python
compatibility suite only ever sent a handful of datums, so it never
sent a compressed request.

Send a 100-datum batch, check that botocore sent it as JSON 1.0 with
Content-Encoding: gzip, and check that all 100 metrics are listed
afterwards. Checking the content type keeps the test from passing
through the CBOR path, which already decompressed gzip, should a later
botocore prefer CBOR.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* chore(cloudwatch): reuse signed IAM test users

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-31 16:53:57 -04:00
1 parent 246473acf5
commit 3cb727a85e
6 files changed
+399

No files matched your search

@@ -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."""
+9
View File
@@ -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.`
@@ -36,10 +36,14 @@ import org.jboss.logging.Logger;
* - DynamoDB (DynamoDB_20120810.*)
* - SQS (AmazonSQS.*)
* <p>
* A gzip-encoded CloudWatch {@code PutMetricData} body arrives here decompressed, by
* {@link CloudWatchGzipReaderInterceptor}.
* <p>
* 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";
@@ -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 {
}
@@ -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.
*
* <p>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.
*
* <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
* 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<String, String> headers = context.getHeaders();
if (!AwsJsonCborController.isGZipped(headers.get(HttpHeaders.CONTENT_ENCODING))
|| context.getMediaType() == null || !context.getMediaType().isCompatible(AWS_JSON_1_0)
|| !isMetricPublication(headers.getFirst("X-Amz-Target"))) {
return context.proceed();
}
byte[] body = context.getInputStream().readAllBytes();
// 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);
} catch (AwsException e) {
throw new WebApplicationException(JsonErrorResponseUtils.createErrorResponse(e));
}
}
context.setInputStream(new ByteArrayInputStream(body));
return context.proceed();
}
private boolean isMetricPublication(String target) {
return catalog.matchTarget(target)
.filter(match -> "monitoring".equals(match.descriptor().externalKey()))
.map(ServiceCatalog.TargetMatch::action)
// CloudWatchMetricsJsonHandler runs putMetricData as PutMetricData too.
.filter(action -> "PutMetricData".equals(action) || "putMetricData".equals(action))
.isPresent();
}
}
@@ -0,0 +1,251 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SignedIamEnforcementProfile;
import io.github.hectorvent.floci.testing.SignedIamUsers;
import io.github.hectorvent.floci.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.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
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.zip.GZIPOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
/**
* Verifies that a JSON 1.0 {@code PutMetricData} whose body is gzip-compressed, as the AWS CLI and
* SDKs send any body of 10 KiB or more, is authenticated over the compressed bytes as sent, decided
* by IAM, and only then decompressed for the handler, within the 10 MiB the CBOR protocol already
* allows a decompressed body.
*
* <p>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<String, String> signed = signedHeaders("PutMetricData", "gzip");
given().headers(signed).headers(ROOT.headersFor("POST", endpoint, signed, plain))
.contentType(JSON_1_0).body(gzip(plain)).post(endpoint)
.then().statusCode(403).body("__type", equalTo("InvalidSignatureException"));
request(ROOT.withSecret("wrong-secret"), "PutMetricData", new byte[]{1, 2, 3}, "gzip")
.then().statusCode(403).body("__type", equalTo("InvalidSignatureException"));
assertAbsent(namespace);
}
@Test
void iamDecidesACompressedPublicationBeforeItIsDecompressed() throws Exception {
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "cw-gzip-denied-")) {
AwsRequestSigner signer = user.signer("monitoring");
String denied = namespace();
request(signer, "PutMetricData", gzip(publication(denied)), "gzip")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
request(signer, "PutMetricData", new byte[]{1, 2, 3}, "gzip")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
assertAbsent(denied);
}
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "cw-gzip-allowed-", "publish-metrics", """
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "cloudwatch:PutMetricData",
"Resource": "*"
}
]
}
""")) {
AwsRequestSigner signer = user.signer("monitoring");
String allowed = namespace();
request(signer, "PutMetricData", gzip(publication(allowed)), "gzip").then().statusCode(200);
list(allowed).then().statusCode(200).body("Metrics[0].MetricName", equalTo("Compressed"));
}
}
@Test
void otherCloudWatchOperationsAreNotDecompressed() throws Exception {
request(ROOT, "ListMetrics", gzip("{}".getBytes(StandardCharsets.UTF_8)), "gzip")
.then().statusCode(400).body("__type", equalTo("SerializationException"));
}
@Test
void aPublicationSentAsPlainJsonIsNotDecompressed() throws Exception {
byte[] body = {1, 2, 3};
Map<String, String> signed = signedHeaders("PutMetricData", "gzip");
given().headers(signed).headers(ROOT.headersFor("POST", endpoint, signed, body))
.contentType("application/json").body(body).post(endpoint)
.then().statusCode(404).body("__type", equalTo("UnknownOperationException"));
}
@ParameterizedTest
@ValueSource(strings = {"AWSStepFunctions.ListStateMachines", "TrentService.ListKeys"})
void otherJsonServicesAreNotDecompressed(String target) throws Exception {
boolean kms = target.startsWith("TrentService.");
byte[] body = gzip("{}".getBytes(StandardCharsets.UTF_8));
Map<String, String> signed = Map.of("content-encoding", "gzip", "x-amz-target", target);
given().headers(signed)
.headers(AwsRequestSigner.signedAs("test", "test", kms ? "kms" : "states")
.headersFor("POST", endpoint, signed, body))
.contentType(kms ? "application/x-amz-json-1.1" : JSON_1_0).body(body).post(endpoint)
.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 {
Map<String, String> signed = signedHeaders(operation, encoding);
return given().headers(signed).headers(signer.headersFor("POST", endpoint, signed, body))
.contentType(JSON_1_0).body(body).post(endpoint);
}
private static Map<String, String> signedHeaders(String operation, String encoding) {
Map<String, String> signed = new HashMap<>();
signed.put("x-amz-target", TARGET + operation);
if (encoding != null) {
signed.put("content-encoding", encoding);
}
return signed;
}
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);
}
/** The publication followed by spaces up to {@code size} bytes, which JSON reads as whitespace. */
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;
}
private static byte[] gzip(byte[] plain) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try (GZIPOutputStream compressed = new GZIPOutputStream(result)) {
compressed.write(plain);
}
return result.toByteArray();
}
}