From 84c06d59e71ec0cf9f6371cb574eaf91e762cf3a Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Sun, 15 Nov 2026 14:27:48 -0600 Subject: [PATCH] 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. --- docs/services/cloudwatch.md | 10 +- .../metrics/CloudWatchMetricsJsonHandler.java | 90 +++++++- ...chConsolePutMetricDataIntegrationTest.java | 208 ++++++++++++++++++ .../CloudWatchJsonTargetIntegrationTest.java | 3 +- ...tchJsonTargetSignatureIntegrationTest.java | 32 +++ 5 files changed, 338 insertions(+), 5 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchConsolePutMetricDataIntegrationTest.java diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 27b9f7270c..bbf676c530 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -477,11 +477,19 @@ decompress their body. JSON 1.0 requests name their operation in `X-Amz-Target` with the `GraniteServiceVersion20100801.` prefix the AWS SDKs send, or with `CloudWatchVersion20130116.`, the prefix of the CloudWatch console's API. Both get the same signature validation and IAM checks. The console prefix serves -four operations on the same metrics and alarms, with these request members: `ListMetrics` +five operations on the same metrics and alarms, with these request members: `PutMetricData` +(`Namespace`, `MetricData`), `ListMetrics` (`Namespace`, `MetricName`, `Dimensions`, `NextToken`), `DescribeAlarms` (`AlarmNames`, `AlarmNamePrefix`, `MaxRecords`, `NextToken`), `GetMetricStatistics` (`Namespace`, `MetricName`, `Dimensions`, `StartTime`, `EndTime`, `Period`, `Statistics`, `Unit`) and `DeleteAlarms` (`AlarmNames`). Every result comes back at once, so `MaxRecords` and `NextToken` change nothing. +Console metric publication accepts a nonempty array of metric objects with either a finite +numeric `Value` or a complete numeric `StatisticValues` object (`SampleCount`, `Sum`, `Minimum`, +`Maximum`, with positive sample count), with string dimension names and values. Timestamps may +be finite numeric epochs or valid ISO-8601/epoch strings. It rejects malformed batches, conflicting +scalar/statistic-set readings, and unsupported datum fields such as `Values`, `Counts` and +`StorageResolution` before storing any metrics. This supported subset is not complete console +API parity. It returns HTTP 400 `UnsupportedOperation` for every other operation, such as the console's `GetMetricData` with `Defaults` and `Metrics`; for a request that sets any other member, such as `StateValue`, `ExtendedStatistics` or the console's `CountOnlyRequest`, to a value other than diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java index dfe5a6e7f8..d5388a4043 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java @@ -28,6 +28,7 @@ import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; import java.math.BigDecimal; +import java.time.DateTimeException; import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -53,12 +54,19 @@ public class CloudWatchMetricsJsonHandler { * stay refused here until the console's API is known to give them the same shapes. */ private static final Map> CONSOLE_TARGET_OPERATIONS = Map.of( + "PutMetricData", Set.of("Namespace", "MetricData"), "ListMetrics", Set.of("Namespace", "MetricName", "Dimensions", "NextToken"), "DescribeAlarms", Set.of("AlarmNames", "AlarmNamePrefix", "MaxRecords", "NextToken"), "GetMetricStatistics", Set.of("Namespace", "MetricName", "Dimensions", "StartTime", "EndTime", "Period", "Statistics", "Unit"), "DeleteAlarms", Set.of("AlarmNames")); + private static final Set CONSOLE_METRIC_DATUM_MEMBERS = Set.of( + "MetricName", "Dimensions", "Timestamp", "Unit", "Value", "StatisticValues"); + private static final Set CONSOLE_STATISTIC_MEMBERS = Set.of( + "SampleCount", "Sum", "Minimum", "Maximum"); + private static final Set CONSOLE_DIMENSION_MEMBERS = Set.of("Name", "Value"); + private final CloudWatchMetricsService metricsService; private final CloudWatchDashboardsService dashboardsService; private final CloudWatchMetricStreamsService metricStreamsService; @@ -117,8 +125,10 @@ public class CloudWatchMetricsJsonHandler { * {@code Alias} and {@code MetricName}. So only the operations and top-level members in * {@code CONSOLE_TARGET_OPERATIONS} are served: any other operation, and any other member set * to a value other than {@code null} or {@code false}, is refused rather than answered as if it - * were unset, and a top-level {@code null} member is dropped. Members nested inside the served - * ones are passed on unchecked, nulls included. A {@code DescribeAlarms} answer that would list + * were unset, and a top-level {@code null} member is dropped. {@code PutMetricData} also checks + * the complete batch for supported scalar or statistic-set shapes before storing any metrics; + * {@code Values} and {@code Counts} are refused because this handler does not parse them. + * Other operations pass nested members on unchecked, nulls included. A {@code DescribeAlarms} answer that would list * an alarm defined with {@code Metrics} is refused too, since the console's API gives those * items its own shape, with {@code Alias} instead of {@code Id} and {@code MetricStat}. The * name matches {@code DynamoDbJsonHandler.handleLegacy}, the entry point of the other JSON-only @@ -141,6 +151,17 @@ public class CloudWatchMetricsJsonHandler { return unsupportedWithConsoleTarget("Parameter " + member.getKey() + " of " + action); } } + if ("PutMetricData".equals(action)) { + if (!served.path("Namespace").isTextual() || !served.path("MetricData").isArray() + || served.path("MetricData").isEmpty()) { + return unsupportedWithConsoleTarget("PutMetricData request shape"); + } + for (JsonNode datum : served.path("MetricData")) { + if (!isSupportedConsoleMetricDatum(datum)) { + return unsupportedWithConsoleTarget("PutMetricData datum shape"); + } + } + } Response response = handle(action, served, region); if ("DescribeAlarms".equals(action) && response.getEntity() instanceof JsonNode body) { for (JsonNode alarm : body.path("MetricAlarms")) { @@ -153,6 +174,71 @@ public class CloudWatchMetricsJsonHandler { return response; } + private boolean isSupportedConsoleMetricDatum(JsonNode datum) { + if (!hasOnlyConsoleMembers(datum, CONSOLE_METRIC_DATUM_MEMBERS) + || !datum.path("MetricName").isTextual()) { + return false; + } + boolean scalar = datum.hasNonNull("Value"); + boolean statistics = datum.hasNonNull("StatisticValues"); + if (scalar == statistics || scalar && !isConsoleNumber(datum.path("Value"))) { + return false; + } + if (statistics) { + JsonNode values = datum.path("StatisticValues"); + if (!hasOnlyConsoleMembers(values, CONSOLE_STATISTIC_MEMBERS) + || !CONSOLE_STATISTIC_MEMBERS.stream().allMatch(name -> isConsoleNumber(values.path(name))) + || values.path("SampleCount").doubleValue() <= 0) { + return false; + } + } + if (datum.hasNonNull("Timestamp")) { + JsonNode timestamp = datum.path("Timestamp"); + if (!timestamp.isTextual() && !isConsoleNumber(timestamp)) { + return false; + } + try { + if (parseInstantNode(timestamp) == null) { + return false; + } + } catch (DateTimeException invalid) { + LOG.debug("Refusing a console metric timestamp outside the supported range", invalid); + return false; + } + } + JsonNode dimensions = datum.path("Dimensions"); + if (!dimensions.isMissingNode() && !dimensions.isNull()) { + if (!dimensions.isArray()) { + return false; + } + for (JsonNode dimension : dimensions) { + if (!hasOnlyConsoleMembers(dimension, CONSOLE_DIMENSION_MEMBERS) + || !dimension.path("Name").isTextual() || !dimension.path("Value").isTextual()) { + return false; + } + } + } + return !datum.hasNonNull("Unit") || datum.path("Unit").isTextual(); + } + + private static boolean hasOnlyConsoleMembers(JsonNode node, Set supported) { + if (!node.isObject()) { + return false; + } + for (Map.Entry member : node.properties()) { + JsonNode value = member.getValue(); + if (!supported.contains(member.getKey()) && !value.isNull() + && (!value.isBoolean() || value.booleanValue())) { + return false; + } + } + return true; + } + + private static boolean isConsoleNumber(JsonNode node) { + return node.isNumber() && Double.isFinite(node.doubleValue()); + } + private static Response unsupportedWithConsoleTarget(String subject) { return Response.status(400) .entity(new AwsErrorResponse("UnsupportedOperation", subject diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchConsolePutMetricDataIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchConsolePutMetricDataIntegrationTest.java new file mode 100644 index 0000000000..7d5a272e97 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchConsolePutMetricDataIntegrationTest.java @@ -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)); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java index 92a5e17887..f5c76fcb68 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java @@ -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"} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java index 8379d91dbf..4ddabd4108 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java @@ -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);