fix(cloudwatch): accept validated console metric publication (#8499)

CloudWatch's console target (CloudWatchVersion20130116.) now serves
PutMetricData, which it used to answer with UnsupportedOperation. It
accepts a nonempty MetricData array whose datums carry a finite numeric
Value or a complete StatisticValues set with a positive SampleCount,
string dimensions and a valid timestamp, and checks the whole batch
before storing anything: a malformed or conflicting datum, or a member
the handler does not parse such as Values, Counts or StorageResolution,
refuses the request without a partial write. Signature validation and
IAM checks are the same as on the SDK prefix.
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-15 16:27:48 -04:00
1 parent e257640516
commit 84c06d59e7
5 files changed
+338 -5

No files matched your search

@@ -0,0 +1,208 @@
package io.floci.aws.services.cloudwatch.metrics;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import io.restassured.parsing.Parser;
import io.restassured.specification.RequestSpecification;
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.time.Instant;
import java.util.UUID;
import static io.restassured.RestAssured.config;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
@QuarkusTest
class CloudWatchConsolePutMetricDataIntegrationTest {
private static final String JSON = "application/x-amz-json-1.0";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261115/us-east-1/monitoring/aws4_request";
@BeforeAll
static void registerParser() {
RestAssured.registerParser(JSON, Parser.JSON);
}
private static RequestSpecification request(String target) {
return given().header("Authorization", AUTH)
.contentType(JSON)
.config(config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs(JSON, ContentType.TEXT)))
.header("X-Amz-Target", target);
}
private static RequestSpecification put() {
return request("CloudWatchVersion20130116.PutMetricData");
}
private static String namespace() {
return "LegacyPut/" + UUID.randomUUID();
}
private static void assertEmpty(String namespace) {
request("GraniteServiceVersion20100801.ListMetrics")
.body("{\"Namespace\":\"" + namespace + "\"}")
.when().post("/")
.then().statusCode(200).body("Metrics", empty());
}
private static void assertSum(String namespace, String metric, long timestamp, float sum) {
request("GraniteServiceVersion20100801.GetMetricStatistics")
.body("""
{"Namespace":"%s","MetricName":"%s","StartTime":%d,"EndTime":%d,
"Period":60,"Statistics":["Sum"]}
""".formatted(namespace, metric, timestamp - 120, timestamp + 120))
.when().post("/")
.then().statusCode(200).body("Datapoints.Sum", hasItem(sum));
}
@Test
void sharedDatumShapesAreStoredAndReadableThroughTheStandardProtocol() {
String namespace = namespace();
long timestamp = Instant.now().getEpochSecond();
put().body("""
{"Namespace":"%s","MetricData":[
{"MetricName":"Single","Value":7,"Unit":"Count","Timestamp":%d},
{"MetricName":"Statistics","Timestamp":%d,
"StatisticValues":{"SampleCount":2,"Sum":6,"Minimum":2,"Maximum":4}}]}
""".formatted(namespace, timestamp, timestamp))
.when().post("/")
.then().statusCode(200);
assertSum(namespace, "Single", timestamp, 7);
assertSum(namespace, "Statistics", timestamp, 6);
request("GraniteServiceVersion20100801.GetMetricStatistics")
.body("""
{"Namespace":"%s","MetricName":"Statistics","StartTime":%d,"EndTime":%d,
"Period":60,"Statistics":["Minimum","Maximum","SampleCount"]}
""".formatted(namespace, timestamp - 120, timestamp + 120))
.when().post("/")
.then().statusCode(200)
.body("Datapoints.Minimum", hasItem(2f))
.body("Datapoints.Maximum", hasItem(4f))
.body("Datapoints.SampleCount", hasItem(2f));
}
@Test
void unsupportedTopLevelShapeIsRejectedWithoutStoringTheValidDatum() {
String namespace = namespace();
put().body("""
{"Namespace":"%s","MetricData":[{"MetricName":"Valid","Value":7}],
"EntityMetricData":[{"MetricData":[{"MetricName":"Entity","Value":2}]}]}
""".formatted(namespace))
.when().post("/")
.then().statusCode(400).body("__type", equalTo("UnsupportedOperation"));
assertEmpty(namespace);
}
@ParameterizedTest
@ValueSource(strings = {"\"StorageResolution\":1", "\"Values\":[2,5]", "\"Counts\":[2,1]"})
void unsupportedDatumShapeRejectsTheEntireRequestBeforeAnyMetricIsStored(String unsupported) {
String namespace = namespace();
put().body("""
{"Namespace":"%s","MetricData":[{"MetricName":"Valid","Value":7},
{"MetricName":"Unsupported","Value":2,%s}]}
""".formatted(namespace, unsupported))
.when().post("/")
.then().statusCode(400).body("__type", equalTo("UnsupportedOperation"));
assertEmpty(namespace);
}
@Test
void unsetUnsupportedDatumMembersKeepTheExistingLegacyNullAndFalseSemantics() {
String namespace = namespace();
long timestamp = Instant.now().getEpochSecond();
put().body("""
{"Namespace":"%s","MetricData":[
{"MetricName":"NullMember","Value":3,"Timestamp":%d,"Unsupported":null,
"StatisticValues":null,"Dimensions":null,"Unit":null},
{"MetricName":"FalseMember","Value":4,"Timestamp":%d,"Unsupported":false}]}
""".formatted(namespace, timestamp, timestamp))
.when().post("/")
.then().statusCode(200);
assertSum(namespace, "NullMember", timestamp, 3);
assertSum(namespace, "FalseMember", timestamp, 4);
}
@ParameterizedTest
@ValueSource(strings = {
"{}",
"\"wrong\"",
"null",
"[]",
"[7]",
"[{\"MetricName\":\"Bad\",\"Value\":[1,2]}]",
"[{\"MetricName\":\"Bad\",\"Value\":{}}]",
"[{\"MetricName\":\"Bad\",\"Value\":\"2\"}]",
"[{\"MetricName\":\"Bad\",\"Value\":true}]"
})
void malformedBatchIsRejectedWithoutPublishingMetrics(String data) {
String namespace = namespace();
put().body("{\"Namespace\":\"" + namespace + "\",\"MetricData\":" + data + "}")
.when().post("/")
.then().statusCode(400).body("__type", equalTo("UnsupportedOperation"));
assertEmpty(namespace);
}
@ParameterizedTest
@ValueSource(strings = {
"\"Value\":[1,2]",
"\"Value\":1,\"Dimensions\":{}",
"\"Value\":1,\"Dimensions\":[7]",
"\"Value\":1,\"Dimensions\":[{\"Name\":12,\"Value\":\"x\"}]",
"\"Value\":1,\"Dimensions\":[{\"Name\":\"x\",\"Value\":12}]",
"\"Value\":1,\"Dimensions\":[{\"Name\":\"x\"}]",
"\"Value\":1,\"Dimensions\":[{\"Name\":\"x\",\"Value\":null}]",
"\"StatisticValues\":{\"SampleCount\":2,\"Sum\":6,\"Minimum\":2}",
"\"StatisticValues\":{\"Sum\":6,\"Minimum\":2,\"Maximum\":4}",
"\"StatisticValues\":{\"SampleCount\":2,\"Minimum\":2,\"Maximum\":4}",
"\"StatisticValues\":{\"SampleCount\":2,\"Sum\":6,\"Maximum\":4}",
"\"StatisticValues\":{\"SampleCount\":2,\"Sum\":6,\"Minimum\":2,\"Maximum\":\"4\"}",
"\"StatisticValues\":[]",
"\"StatisticValues\":{\"SampleCount\":0,\"Sum\":0,\"Minimum\":2,\"Maximum\":4}",
"\"Value\":7,\"StatisticValues\":{\"SampleCount\":2,\"Sum\":6,\"Minimum\":2,\"Maximum\":4}",
"\"Value\":1e1000",
"\"Value\":1,\"Timestamp\":[]",
"\"Value\":1,\"Timestamp\":\"wrong\"",
"\"Value\":1,\"Timestamp\":1e30",
"\"Value\":1,\"Unit\":7"
})
void malformedDatumRejectsTheWholeBatchBeforePublishingTheValidDatum(String fields) {
String namespace = namespace();
put().body("""
{"Namespace":"%s","MetricData":[{"MetricName":"Valid","Value":7},
{"MetricName":"Bad",%s}]}
""".formatted(namespace, fields))
.when().post("/")
.then().statusCode(400).body("__type", equalTo("UnsupportedOperation"));
assertEmpty(namespace);
}
@Test
void stringDimensionsKeepTheirIdentity() {
String namespace = namespace();
long timestamp = Instant.now().getEpochSecond();
put().body("""
{"Namespace":"%s","MetricData":[{"MetricName":"Dimensioned","Value":5,"Timestamp":"%s",
"Dimensions":[{"Name":"Worker","Value":"12"}]}]}
""".formatted(namespace, Instant.ofEpochSecond(timestamp)))
.when().post("/")
.then().statusCode(200);
request("GraniteServiceVersion20100801.GetMetricStatistics")
.body("""
{"Namespace":"%s","MetricName":"Dimensioned","StartTime":%d,"EndTime":%d,
"Period":60,"Statistics":["Sum"],"Dimensions":[{"Name":"Worker","Value":"12"}]}
""".formatted(namespace, timestamp - 120, timestamp + 120))
.when().post("/")
.then().statusCode(200).body("Datapoints.Sum", hasItem(5f));
}
}
@@ -27,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* CloudWatch JSON 1.0 requests name their operation with either target prefix: the
* {@code GraniteServiceVersion20100801.} prefix of the AWS SDKs, or the
* {@code CloudWatchVersion20130116.} prefix of the CloudWatch console's API. The console prefix
* reaches the same metrics and alarms for four operations and the request members the handler
* reaches the same metrics and alarms for five operations and the request members the handler
* honours for them. It refuses the other operations, other members that are set, and a
* {@code DescribeAlarms} answer listing an alarm defined with {@code Metrics}, which the handler
* would otherwise ignore or answer in a shape the console's API does not have; top-level
@@ -130,7 +130,6 @@ class CloudWatchJsonTargetIntegrationTest {
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
PutMetricData | {"Namespace":"Example/JsonTarget","MetricData":[{"MetricName":"Requests","Value":1}]}
SetAlarmState | {"AlarmName":"json-target-none","StateValue":"OK","StateReason":"test"}
PutDashboard | {"DashboardName":"json-target-none","DashboardBody":"{}"}
ListTagsForResource | {"ResourceARN":"arn:aws:cloudwatch:us-east-1:000000000000:alarm:json-target-none"}
@@ -18,6 +18,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
@@ -90,6 +91,37 @@ class CloudWatchJsonTargetSignatureIntegrationTest {
}
}
@ParameterizedTest
@ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET})
void putMetricDataChecksSignaturesAndPermissionsBeforeStoringMetrics(String prefix) throws Exception {
String namespace = "cw-put-permissions-" + Long.toString(System.nanoTime(), 36);
String body = """
{"Namespace":"%s","MetricData":[{"MetricName":"Requests","Value":7}]}
""".formatted(namespace);
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "monitoring");
json(prefix, "PutMetricData").body(body).post("/")
.then().statusCode(403).body("__type", equalTo("MissingAuthenticationTokenException"));
json(prefix, "PutMetricData").body(body).filter(root.withSecret("wrong-secret")).post("/")
.then().statusCode(403).body("__type", equalTo("InvalidSignatureException"));
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "cw-put-permissions-", "list-only", """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Action":"cloudwatch:ListMetrics","Resource":"*"
}]}
""")) {
json(prefix, "PutMetricData").body(body).filter(user.signer("monitoring")).post("/")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
}
json(CURRENT_TARGET, "ListMetrics").body("{\"Namespace\":\"" + namespace + "\"}")
.filter(root).post("/").then().statusCode(200).body("Metrics", empty());
json(prefix, "PutMetricData").body(body).filter(root).post("/")
.then().statusCode(200);
json(CURRENT_TARGET, "ListMetrics").body("{\"Namespace\":\"" + namespace + "\"}")
.filter(root).post("/").then().statusCode(200)
.body("Metrics[0].MetricName", equalTo("Requests"));
}
@Test
void alarmActionPermissionsAreCheckedBeforeChangingTheAlarm() throws Exception {
String name = "cw-action-permissions-" + Long.toString(System.nanoTime(), 36);