diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 7fe0e7fee2..d7c8b1c244 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -370,6 +370,26 @@ HTTP 404 `UnknownOperationException`. IAM policies use the `cloudwatch` action p **Endpoint:** `http://localhost:4566/`. Query: GET or POST; JSON: POST. +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` +(`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. +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 +`false` or `null`; and for a `DescribeAlarms` answer that would list an alarm defined with +`Metrics`, whose items the console's API shapes differently. Such an alarm makes every listing +that includes it fail, so filter by `AlarmNames` or `AlarmNamePrefix` to list the others. +The console prefix is JSON only: a CBOR request naming it returns HTTP 404 +`UnknownOperationException`, and a Smithy RPC v2 request HTTP 404. Only the bare prefix over +`application/x-amz-json-1.0` is accepted; the fully qualified +`com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116.` form over `application/json` +returns HTTP 404. + ### Supported Actions | Action | Description | 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 7445604edb..515da6aedb 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 @@ -176,7 +176,9 @@ public class AwsJsonController { case "sns" -> snsJsonHandler.handle(action, request, region); case "states" -> sfnJsonHandler.handle(action, request, region); case "swf" -> swfJsonHandler.handle(action, request, region); - case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region); + case "monitoring" -> targetMatch.jsonOnly() + ? cloudWatchMetricsJsonHandler.handleLegacy(action, request, region) + : cloudWatchMetricsJsonHandler.handle(action, request, region); case "cloudcontrol" -> cloudControlJsonHandler.handle( action, request, region, regionResolver.getAccountId()); case "network-firewall" -> networkFirewallJsonHandler.handle( diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index a72dc18aeb..08c3004005 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -269,7 +269,7 @@ public class ResolvedServiceCatalog { config.storage().services().cloudwatchmetrics().flushIntervalMs(), AwsNamespaces.CW, ServiceProtocol.QUERY, protocols(ServiceProtocol.QUERY, ServiceProtocol.JSON, ServiceProtocol.CBOR), Set.of("GraniteServiceVersion20100801."), Set.of("monitoring"), - Set.of("GraniteServiceVersion20100801"), Set.of()), + Set.of("GraniteServiceVersion20100801"), Set.of(), "CloudWatchVersion20130116."), descriptor("secretsmanager", "secretsmanager", config.services().secretsmanager().enabled(), true, "secretsmanager", storageMode(config.storage().services().secretsmanager().mode(), config.storage().mode()), config.storage().services().secretsmanager().flushIntervalMs(), null, ServiceProtocol.JSON, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java index 32225a8e48..c56f8df244 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; /** * Handles CloudWatch Metrics requests via the JSON 1.0 protocol. @@ -38,6 +39,20 @@ import java.util.Map; public class CloudWatchMetricsJsonHandler { private static final Logger LOG = Logger.getLogger(CloudWatchMetricsJsonHandler.class); + + /** + * The operations served through the console's {@code CloudWatchVersion20130116.} target, each + * with the request members accepted there: the ones this handler honours, plus + * {@code NextToken} and {@code MaxRecords}, which change nothing because every result comes + * back at once. + */ + private static final Map> CONSOLE_TARGET_OPERATIONS = Map.of( + "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 final CloudWatchMetricsService metricsService; private final CloudWatchDashboardsService dashboardsService; private final CloudWatchMetricStreamsService metricStreamsService; @@ -85,6 +100,57 @@ public class CloudWatchMetricsJsonHandler { }; } + /** + * Handles an operation named with the {@code CloudWatchVersion20130116.} target of the + * CloudWatch console's API. The console's model gives many operations and members shapes of + * their own, which this handler would silently misread or ignore, such as {@code GetMetricData} + * with {@code Defaults} and {@code Metrics}, or {@code PutMetricAlarm} metric items with + * {@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 + * 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 + * target. + */ + public Response handleLegacy(String action, JsonNode request, String region) { + Set servedMembers = CONSOLE_TARGET_OPERATIONS.get(action); + if (servedMembers == null) { + return unsupportedWithConsoleTarget("Operation " + action); + } + ObjectNode served = objectMapper.createObjectNode(); + for (Map.Entry member : request.properties()) { + JsonNode value = member.getValue(); + if (value.isNull()) { + continue; + } + if (servedMembers.contains(member.getKey())) { + served.set(member.getKey(), value); + } else if (!value.isBoolean() || value.booleanValue()) { + return unsupportedWithConsoleTarget("Parameter " + member.getKey() + " of " + action); + } + } + Response response = handle(action, served, region); + if ("DescribeAlarms".equals(action) && response.getEntity() instanceof JsonNode body) { + for (JsonNode alarm : body.path("MetricAlarms")) { + if (alarm.has("Metrics")) { + return unsupportedWithConsoleTarget("DescribeAlarms of alarm " + + alarm.path("AlarmName").asText() + ", which is defined with Metrics,"); + } + } + } + return response; + } + + private static Response unsupportedWithConsoleTarget(String subject) { + return Response.status(400) + .entity(new AwsErrorResponse("UnsupportedOperation", subject + + " is not supported by CloudWatch JSON with the CloudWatchVersion20130116 target.")) + .build(); + } + private Response handlePutMetricData(JsonNode request, String region) { String namespace = request.path("Namespace").asText(); List datums = parseMetricDataJson(request.path("MetricData"), "MetricData"); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java index e5f33dd9b9..a649ef3722 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java @@ -40,6 +40,17 @@ class ServiceCatalogRoutingIntegrationTest { assertEquals("monitoring", catalog.byCborSdkServiceId("GraniteServiceVersion20100801").orElseThrow().externalKey()); } + @Test + void consoleCloudWatchTargetIsJsonOnly() { + ServiceCatalog.TargetMatch match = catalog.matchTarget("CloudWatchVersion20130116.ListMetrics") + .orElseThrow(); + + assertEquals("monitoring", match.descriptor().externalKey()); + assertEquals("ListMetrics", match.action()); + assertTrue(match.jsonOnly()); + assertTrue(catalog.byCborSdkServiceId("CloudWatchVersion20130116").isEmpty()); + } + @Test void rpcV2ServiceNamesDeriveFromTargetPrefixes() { // The smithy-rpc-v2 path segment is the service shape name == target prefix diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java new file mode 100644 index 0000000000..5e3d879c4f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java @@ -0,0 +1,289 @@ +package io.github.hectorvent.floci.services.cloudwatch.metrics; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +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.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.time.Instant; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +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 + * 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 + * {@code null} members count as unset. Only JSON 1.0 requests with the bare prefix reach it: CBOR, + * Smithy RPC v2 and the console API's other wire forms stay unknown. + */ +@QuarkusTest +class CloudWatchJsonTargetIntegrationTest { + + private static final String CURRENT_TARGET = "GraniteServiceVersion20100801."; + private static final String CONSOLE_TARGET = "CloudWatchVersion20130116."; + private static final String AUTHORIZATION = + "AWS4-HMAC-SHA256 Credential=test/20261022/us-east-1/monitoring/aws4_request"; + + @BeforeAll + static void configureAwsJson() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET}) + void listMetricsThroughEitherTargetSeesTheSameMetrics(String prefix) { + String namespace = "json-target-" + UUID.randomUUID(); + json(CURRENT_TARGET, "PutMetricData", """ + {"Namespace":"%s","MetricData":[{"MetricName":"Requests","Value":1}]} + """.formatted(namespace)).then().statusCode(200); + + json(prefix, "ListMetrics", "{\"Namespace\":\"" + namespace + "\"}") + .then().statusCode(200).contentType(containsString("json")) + .body("Metrics.MetricName", contains("Requests")); + } + + @ParameterizedTest + @ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET}) + void getMetricStatisticsThroughEitherTargetSeesTheSameDatapoints(String prefix) { + String namespace = "json-target-" + UUID.randomUUID(); + long now = Instant.now().getEpochSecond(); + json(CURRENT_TARGET, "PutMetricData", """ + {"Namespace":"%s","MetricData":[{"MetricName":"Requests","Value":5,"Timestamp":%d}]} + """.formatted(namespace, now)).then().statusCode(200); + + Response statistics = json(prefix, "GetMetricStatistics", """ + {"Namespace":"%s","MetricName":"Requests","StartTime":%d,"EndTime":%d, + "Period":60,"Statistics":["Sum"]} + """.formatted(namespace, now - 300, now + 300)); + statistics.then().statusCode(200).contentType(containsString("json")); + assertEquals(5.0, statistics.jsonPath().getDouble("Datapoints[0].Sum")); + } + + @ParameterizedTest + @ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET}) + void describeAlarmsThroughEitherTargetSeesTheSameAlarm(String prefix) { + String alarm = "json-target-" + UUID.randomUUID(); + putAlarm(alarm); + try { + json(prefix, "DescribeAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}") + .then().statusCode(200).contentType(containsString("json")) + .body("MetricAlarms.AlarmName", contains(alarm)); + } finally { + json(CURRENT_TARGET, "DeleteAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}") + .then().statusCode(200); + } + } + + @Test + void deleteAlarmsThroughTheConsoleTargetRemovesTheAlarm() { + String alarm = "json-target-" + UUID.randomUUID(); + putAlarm(alarm); + try { + json(CONSOLE_TARGET, "DeleteAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}") + .then().statusCode(200); + json(CURRENT_TARGET, "DescribeAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}") + .then().statusCode(200).body("MetricAlarms", empty()); + } finally { + json(CURRENT_TARGET, "DeleteAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}"); + } + } + + @Test + void consoleGetMetricDataIsRefusedRatherThanAnsweredWithNoResults() { + json(CONSOLE_TARGET, "GetMetricData", """ + {"Defaults":{"Period":60,"Stat":"Sum","Range":{"StartTime":1761091200,"EndTime":1761094800}}, + "Metrics":[{"Alias":"m1","Namespace":"Example/JsonTarget","MetricName":"Requests"}]} + """).then().statusCode(400).body("__type", equalTo("UnsupportedOperation")); + } + + @Test + void consolePutMetricAlarmIsRefusedAndStoresNothing() { + String alarm = "json-target-" + UUID.randomUUID(); + json(CONSOLE_TARGET, "PutMetricAlarm", """ + {"AlarmName":"%s","EvaluationPeriods":1,"Threshold":1, + "ComparisonOperator":"GreaterThanThreshold", + "Metrics":[{"Alias":"m1","Namespace":"Example/JsonTarget","MetricName":"Requests", + "Stat":"Sum","Period":60,"ReturnData":true}]} + """.formatted(alarm)).then().statusCode(400).body("__type", equalTo("UnsupportedOperation")); + + json(CURRENT_TARGET, "DescribeAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}") + .then().statusCode(200).body("MetricAlarms", empty()); + } + + @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"} + ListMetricStreams | {} + getMetricData | {} + """) + void operationsTheConsoleTargetDoesNotShareAreRefused(String operation, String body) { + json(CONSOLE_TARGET, operation, body).then().statusCode(400) + .body("__type", equalTo("UnsupportedOperation")); + } + + @ParameterizedTest + @ValueSource(strings = { + """ + [{"Id":"m1","ReturnData":false,"MetricStat":{"Metric":{"Namespace":"Example/JsonTarget", + "MetricName":"Requests"},"Period":60,"Stat":"Sum"}}, + {"Id":"e1","Expression":"m1*2","Label":"doubled","ReturnData":true}] + """, + """ + [{"Id":"m1","ReturnData":true,"MetricStat":{"Metric":{"Namespace":"Example/JsonTarget", + "MetricName":"Requests"},"Period":60,"Stat":"Sum"}}] + """}) + void consoleDescribeAlarmsRefusesAnAlarmDefinedWithMetrics(String metrics) { + String alarm = "json-target-" + UUID.randomUUID(); + json(CURRENT_TARGET, "PutMetricAlarm", """ + {"AlarmName":"%s","EvaluationPeriods":1,"Threshold":1, + "ComparisonOperator":"GreaterThanThreshold","Metrics":%s} + """.formatted(alarm, metrics)).then().statusCode(200); + try { + json(CONSOLE_TARGET, "DescribeAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}") + .then().statusCode(400).body("__type", equalTo("UnsupportedOperation")) + .body("message", containsString(alarm)); + json(CURRENT_TARGET, "DescribeAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}") + .then().statusCode(200).body("MetricAlarms[0].Metrics.Id", hasItem("m1")); + } finally { + json(CURRENT_TARGET, "DeleteAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}"); + } + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + ListMetrics | {"CountOnlyRequest":true} + ListMetrics | {"SegmentId":1} + ListMetrics | {"TotalSegments":2} + ListMetrics | {"Namespace":"json-target-none","RecentlyActive":"PT3H"} + ListMetrics | {"Namespace":"json-target-none","OwningAccount":"000000000000"} + ListMetrics | {"Namespace":"json-target-none","IncludeLinkedAccounts":true} + DescribeAlarms | {"AlarmNames":["json-target-none"],"ExcludeAutoscalingAlarms":true} + DescribeAlarms | {"AlarmNames":["json-target-none"],"ExcludeManagedAlarms":true} + DescribeAlarms | {"AlarmNames":["json-target-none"],"StateValue":"ALARM"} + DescribeAlarms | {"AlarmNames":["json-target-none"],"AlarmTypes":["MetricAlarm"]} + DescribeAlarms | {"AlarmNames":["json-target-none"],"ActionPrefix":"arn:"} + DescribeAlarms | {"ChildrenOfAlarmName":"json-target-none"} + DescribeAlarms | {"ParentsOfAlarmName":"json-target-none"} + GetMetricStatistics | {"Namespace":"Example/JsonTarget","MetricName":"Requests","Period":60,"ExtendedStatistics":["p99"]} + GetMetricStatistics | {"Namespace":"Example/JsonTarget","MetricName":"Requests","Period":60,"Unexpected":"x"} + DeleteAlarms | {"AlarmNames":["json-target-none"],"Unexpected":"x"} + """) + void membersTheConsoleTargetDoesNotServeAreRefused(String operation, String body) { + json(CONSOLE_TARGET, operation, body).then().statusCode(400) + .body("__type", equalTo("UnsupportedOperation")); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + ListMetrics | {"Namespace":"json-target-none","MetricName":"Requests","Dimensions":[{"Name":"Host","Value":"a"}],"NextToken":"t"} + DescribeAlarms | {"AlarmNames":["json-target-none"],"MaxRecords":10,"NextToken":"t"} + DescribeAlarms | {"AlarmNamePrefix":"json-target-none-","MaxRecords":10} + GetMetricStatistics | {"Namespace":"json-target-none","MetricName":"Requests","Dimensions":[{"Name":"Host","Value":"a"}],"StartTime":1761091200,"EndTime":1761094800,"Period":60,"Statistics":["Sum"],"Unit":"Count"} + DeleteAlarms | {"AlarmNames":["json-target-none"]} + """) + void everyServedMemberIsAccepted(String operation, String body) { + json(CONSOLE_TARGET, operation, body).then().statusCode(200); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + ListMetrics | {"Namespace":"json-target-none","CountOnlyRequest":false,"IncludeLinkedAccounts":false} + DescribeAlarms | {"AlarmNames":["json-target-none"],"ExcludeAutoscalingAlarms":false,"ExcludeManagedAlarms":null,"StateValue":null} + """) + void membersLeftUnsetAreServed(String operation, String body) { + json(CONSOLE_TARGET, operation, body).then().statusCode(200); + } + + @Test + void nullServedMembersCountAsUnset() { + String namespace = "json-target-" + UUID.randomUUID(); + String metric = "Requests-" + UUID.randomUUID(); + json(CURRENT_TARGET, "PutMetricData", """ + {"Namespace":"%s","MetricData":[{"MetricName":"%s","Value":1}]} + """.formatted(namespace, metric)).then().statusCode(200); + + json(CONSOLE_TARGET, "ListMetrics", "{\"Namespace\":null,\"MetricName\":\"" + metric + "\"}") + .then().statusCode(200).body("Metrics.Namespace", contains(namespace)); + } + + @ParameterizedTest + @ValueSource(strings = {"CloudWatchVersion20100801.", "CloudWatchVersion19000101.", "CloudWatchVersion."}) + void otherCloudWatchVersionsStayUnknown(String prefix) { + json(prefix, "ListMetrics", "{}").then().statusCode(404) + .body("__type", equalTo("UnknownOperationException")); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + application/json | CloudWatchVersion20130116. + application/json | com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116. + application/x-amz-json-1.0 | com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116. + application/x-amz-json-1.1 | CloudWatchVersion20130116. + """) + void otherWireFormsOfTheConsoleTargetStayUnknown(String contentType, String prefix) { + given().contentType(contentType) + .header("Authorization", AUTHORIZATION) + .header("Content-Encoding", "amz-1.0") + .header("X-Amz-Target", prefix + "ListMetrics") + .body("{}").post("/") + .then().statusCode(404).body("__type", equalTo("UnknownOperationException")); + } + + @Test + void cborRequestsCannotNameTheConsoleTarget() throws Exception { + byte[] response = given().contentType("application/x-amz-cbor-1.1") + .header("Authorization", AUTHORIZATION) + .header("X-Amz-Target", CONSOLE_TARGET + "ListMetrics") + .body(new ObjectMapper(new CBORFactory()).writeValueAsBytes(Map.of())) + .post("/").then().statusCode(404).contentType("application/x-amz-cbor-1.1") + .extract().asByteArray(); + + assertEquals("UnknownOperationException", + new ObjectMapper(new CBORFactory()).readTree(response).path("__type").asText()); + } + + @Test + void smithyRpcV2CannotNameTheConsoleService() throws Exception { + given().contentType("application/cbor").header("smithy-protocol", "rpc-v2-cbor") + .header("Authorization", AUTHORIZATION) + .body(new ObjectMapper(new CBORFactory()).writeValueAsBytes(Map.of())) + .post("/service/CloudWatchVersion20130116/operation/ListMetrics") + .then().statusCode(404); + } + + private static void putAlarm(String alarm) { + json(CURRENT_TARGET, "PutMetricAlarm", """ + {"AlarmName":"%s","Namespace":"Example/JsonTarget","MetricName":"Requests", + "Statistic":"Sum","Period":60,"EvaluationPeriods":1,"Threshold":1, + "ComparisonOperator":"GreaterThanThreshold"} + """.formatted(alarm)).then().statusCode(200); + } + + private static Response json(String prefix, String operation, String body) { + return given().contentType("application/x-amz-json-1.0") + .header("Authorization", AUTHORIZATION) + .header("X-Amz-Target", prefix + operation) + .body(body).post("/"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java new file mode 100644 index 0000000000..52ed64d6a5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java @@ -0,0 +1,97 @@ +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.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +/** + * A CloudWatch JSON request is authenticated and then decided by IAM the same way whichever target + * prefix names its operation: the console API's {@code CloudWatchVersion20130116.} prefix gets the + * header and presigned signature checks, the unsigned-call refusal and the {@code cloudwatch:} + * action of the operation it names, exactly as the SDKs' {@code GraniteServiceVersion20100801.} + * prefix does. + */ +@QuarkusTest +@TestProfile(SignedIamEnforcementProfile.class) +class CloudWatchJsonTargetSignatureIntegrationTest { + + private static final String CURRENT_TARGET = "GraniteServiceVersion20100801."; + private static final String CONSOLE_TARGET = "CloudWatchVersion20130116."; + + @TestHTTPResource("/") + URI endpoint; + + @BeforeAll + static void configureAwsJson() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET}) + void genuineSignaturesAreServedAndTamperingIsRefused(String prefix) { + AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "monitoring"); + json(prefix, "ListMetrics").filter(root).post("/") + .then().statusCode(200).body("Metrics", notNullValue()); + json(prefix, "ListMetrics").filter(root.withSecret("wrong-secret")).post("/") + .then().statusCode(403).body("__type", equalTo("InvalidSignatureException")); + } + + @ParameterizedTest + @ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET}) + void presignedRequestsAreServedAndWrongSecretsAreRefused(String prefix) throws Exception { + AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "monitoring"); + byte[] body = "{}".getBytes(StandardCharsets.UTF_8); + json(prefix, "ListMetrics").urlEncodingEnabled(false) + .post(root.presignedUri("POST", endpoint, Map.of(), body)) + .then().statusCode(200).body("Metrics", notNullValue()); + json(prefix, "ListMetrics").urlEncodingEnabled(false) + .post(root.withSecret("wrong-secret").presignedUri("POST", endpoint, Map.of(), body)) + .then().statusCode(403).body("__type", equalTo("InvalidSignatureException")); + } + + @ParameterizedTest + @ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET}) + void unsignedRequestsAreRefused(String prefix) { + json(prefix, "ListMetrics").post("/") + .then().statusCode(403).body("__type", equalTo("MissingAuthenticationTokenException")); + } + + @ParameterizedTest + @ValueSource(strings = {CURRENT_TARGET, CONSOLE_TARGET}) + void iamDecidesEachOperationByItsCloudWatchAction(String prefix) throws Exception { + try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "cw-json-target-", "list-metrics", """ + {"Version":"2012-10-17","Statement":[{ + "Effect":"Allow","Action":"cloudwatch:ListMetrics","Resource":"*" + }]} + """)) { + AwsRequestSigner signer = user.signer("monitoring"); + + json(prefix, "ListMetrics").filter(signer).post("/") + .then().statusCode(200).body("Metrics", notNullValue()); + json(prefix, "DescribeAlarms").filter(signer).post("/") + .then().statusCode(400).body("__type", equalTo("AccessDeniedException")); + } + } + + private static RequestSpecification json(String prefix, String operation) { + return given().contentType("application/x-amz-json-1.0") + .header("X-Amz-Target", prefix + operation) + .body("{}"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchQueryGetSignatureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchQueryGetSignatureIntegrationTest.java index 1a7448d289..2eaa42404e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchQueryGetSignatureIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchQueryGetSignatureIntegrationTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics; import io.github.hectorvent.floci.testing.SignedIamEnforcementProfile; +import io.github.hectorvent.floci.testing.SignedIamUsers; import io.github.hectorvent.floci.testutil.AwsRequestSigner; import io.github.hectorvent.floci.testutil.S3RequestSigner; import io.quarkus.test.common.http.TestHTTPResource; @@ -53,48 +54,37 @@ class CloudWatchQueryGetSignatureIntegrationTest { @ParameterizedTest @ValueSource(booleans = {false, true}) void regionalWritesAndIamConditionsUseTheSigningRegion(boolean presigned) throws Exception { - String user = "cw-query-" + UUID.randomUUID(); String alarm = "cw-query-" + UUID.randomUUID(); - String key = null; AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "monitoring").inRegion("us-west-2"); - 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"); - iam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "regional-cloudwatch", "PolicyDocument", """ - {"Version":"2012-10-17","Statement":[{ - "Effect":"Allow","Action":["cloudwatch:PutMetricAlarm","cloudwatch:DescribeAlarms"], - "Resource":"*","Condition":{"StringEquals":{ - "aws:RequestedRegion":"us-west-2","aws:PrincipalAccount":"000000000000"}} - }]} - """)).then().statusCode(200); - AwsRequestSigner signer = AwsRequestSigner.signedAs(key, secret, "monitoring").inRegion("us-west-2"); - request(signer, Map.of("Action", "PutMetricAlarm", "Version", "2010-08-01", "AlarmName", alarm, - "Namespace", "Example/QueryGet", "MetricName", "Requests", "Statistic", "Sum", "Period", "60", - "EvaluationPeriods", "1", "Threshold", "1", "ComparisonOperator", "GreaterThanThreshold"), presigned) - .then().statusCode(200); - Map describe = Map.of("Action", "DescribeAlarms", "Version", "2010-08-01", - "AlarmNames.member.1", alarm); - request(signer, describe, presigned).then().statusCode(200) - .body(containsString("arn:aws:cloudwatch:us-west-2:000000000000:alarm:" + alarm)); - request(signer.inRegion("us-east-1"), describe, presigned).then().statusCode(403) - .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); - request(root.inRegion("us-east-1"), describe, presigned).then().statusCode(200) - .body(not(containsString(alarm))); - request(signer, Map.of("Action", "DeleteAlarms", "Version", "2010-08-01", - "AlarmNames.member.1", alarm), presigned).then().statusCode(403) - .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); - request(signer, describe, presigned).then().statusCode(200).body(containsString(alarm)); - } finally { - request(root, Map.of("Action", "DeleteAlarms", "Version", "2010-08-01", - "AlarmNames.member.1", alarm), false).then().statusCode(200); - if (key != null) { - iam("DeleteAccessKey", Map.of("UserName", user, "AccessKeyId", key)).then().statusCode(200); + try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "cw-query-", "regional-cloudwatch", """ + {"Version":"2012-10-17","Statement":[{ + "Effect":"Allow","Action":["cloudwatch:PutMetricAlarm","cloudwatch:DescribeAlarms"], + "Resource":"*","Condition":{"StringEquals":{ + "aws:RequestedRegion":"us-west-2","aws:PrincipalAccount":"000000000000"}} + }]} + """)) { + AwsRequestSigner signer = user.signer("monitoring").inRegion("us-west-2"); + try { + request(signer, Map.of("Action", "PutMetricAlarm", "Version", "2010-08-01", "AlarmName", alarm, + "Namespace", "Example/QueryGet", "MetricName", "Requests", "Statistic", "Sum", "Period", "60", + "EvaluationPeriods", "1", "Threshold", "1", "ComparisonOperator", "GreaterThanThreshold"), + presigned).then().statusCode(200); + Map describe = Map.of("Action", "DescribeAlarms", "Version", "2010-08-01", + "AlarmNames.member.1", alarm); + request(signer, describe, presigned).then().statusCode(200) + .body(containsString("arn:aws:cloudwatch:us-west-2:000000000000:alarm:" + alarm)); + request(signer.inRegion("us-east-1"), describe, presigned).then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + request(root.inRegion("us-east-1"), describe, presigned).then().statusCode(200) + .body(not(containsString(alarm))); + request(signer, Map.of("Action", "DeleteAlarms", "Version", "2010-08-01", + "AlarmNames.member.1", alarm), presigned).then().statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + request(signer, describe, presigned).then().statusCode(200).body(containsString(alarm)); + } finally { + request(root, Map.of("Action", "DeleteAlarms", "Version", "2010-08-01", + "AlarmNames.member.1", alarm), false).then().statusCode(200); } - iam("DeleteUserPolicy", Map.of("UserName", user, "PolicyName", "regional-cloudwatch")); - iam("DeleteUser", Map.of("UserName", user)).then().statusCode(200); } } @@ -112,13 +102,6 @@ class CloudWatchQueryGetSignatureIntegrationTest { return given().urlEncodingEnabled(false).headers(signer.headersFor("GET", uri, Map.of(), new byte[0])).get(uri); } - private Response iam(String action, Map parameters) throws Exception { - String body = "Action=" + action + "&Version=2010-05-08&" + encode(parameters); - return given().headers(AwsRequestSigner.signedAs("test", "test", "iam") - .headersFor("POST", endpoint, Map.of(), body.getBytes(StandardCharsets.UTF_8))) - .contentType("application/x-www-form-urlencoded").body(body).post(endpoint); - } - private static String encode(Map parameters) { return parameters.entrySet().stream().map(entry -> URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)).collect(Collectors.joining("&")); diff --git a/src/test/java/io/github/hectorvent/floci/testing/SignedIamEnforcementProfile.java b/src/test/java/io/github/hectorvent/floci/testing/SignedIamEnforcementProfile.java index ed328df9be..ead44ae802 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/SignedIamEnforcementProfile.java +++ b/src/test/java/io/github/hectorvent/floci/testing/SignedIamEnforcementProfile.java @@ -15,14 +15,16 @@ import java.util.Map; *
  • {@code floci.auth.validate-signatures=true} verifies every SigV4 signature, in the header * or the query string, and refuses a forged or unknown credential. Every class relies on it.
  • *
  • {@code floci.services.iam.enforcement-enabled=true} evaluates every request against the - * caller's IAM policies. {@code StsFederationCallerEnforcementIntegrationTest} and - * {@code CloudWatchQueryGetSignatureIntegrationTest} rely on it, for the refusals their IAM - * users' policies decide; {@code StsPresignedSignatureIntegrationTest} passes with it off.
  • + * caller's IAM policies. {@code StsFederationCallerEnforcementIntegrationTest}, + * {@code CloudWatchQueryGetSignatureIntegrationTest} and + * {@code CloudWatchJsonTargetSignatureIntegrationTest} rely on it, for the refusals their IAM + * users' policies decide and, in the last, for refusing unsigned calls; + * {@code StsPresignedSignatureIntegrationTest} passes with it off. *
  • {@code floci.services.s3.enforce-auth=true} makes S3 run its own access checks, bucket * policies among them, on top of the signature check. No class fails with it off. It stays so * that the signed S3 request in {@code CloudWatchQueryGetSignatureIntegrationTest}, which must * reach S3 rather than CloudWatch, still runs under those checks, as that class was written to. - * It only acts on requests routed to S3, and neither STS class sends one.
  • + * It only acts on requests routed to S3, and no other class sends one. * */ public class SignedIamEnforcementProfile implements QuarkusTestProfile { diff --git a/src/test/java/io/github/hectorvent/floci/testing/SignedIamUsers.java b/src/test/java/io/github/hectorvent/floci/testing/SignedIamUsers.java new file mode 100644 index 0000000000..2feff673f1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/SignedIamUsers.java @@ -0,0 +1,88 @@ +package io.github.hectorvent.floci.testing; + +import io.github.hectorvent.floci.testutil.AwsRequestSigner; +import io.restassured.response.Response; + +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import static io.restassured.RestAssured.given; + +/** + * IAM calls with real SigV4 signatures, for classes that run with signature validation on (such as + * {@link SignedIamEnforcementProfile}), where {@link EnforcementFixtures}' placeholder signatures + * are refused. Every call is signed as the root {@code test} key. + * + *

    {@link #createUser} makes an IAM user with an access key and one inline policy; closing the + * returned {@link User} deletes the key, the policy and the user, so a test can hold it in a + * try-with-resources block. + */ +public final class SignedIamUsers { + + private SignedIamUsers() { + } + + /** Sends one IAM Query action, signed as the root {@code test} key, to {@code endpoint}. */ + public static Response iam(URI endpoint, String action, Map parameters) throws Exception { + String body = "Action=" + action + "&Version=2010-05-08&" + parameters.entrySet().stream() + .map(entry -> URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "=" + + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)) + .collect(Collectors.joining("&")); + return given().headers(AwsRequestSigner.signedAs("test", "test", "iam") + .headersFor("POST", endpoint, Map.of(), body.getBytes(StandardCharsets.UTF_8))) + .contentType("application/x-www-form-urlencoded").body(body).post(endpoint); + } + + /** + * Creates a user named {@code namePrefix} plus a random suffix, with one access key and the + * inline policy {@code policyName} holding {@code policyDocument}. If a later step fails, the + * parts already made are removed before the failure is rethrown. + */ + public static User createUser(URI endpoint, String namePrefix, String policyName, String policyDocument) + throws Exception { + String name = namePrefix + UUID.randomUUID(); + iam(endpoint, "CreateUser", Map.of("UserName", name)).then().statusCode(200); + User user = new User(endpoint, name, policyName, null, null); + try { + Response credentials = iam(endpoint, "CreateAccessKey", Map.of("UserName", name)); + credentials.then().statusCode(200); + user = new User(endpoint, name, policyName, + credentials.xmlPath().getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"), + credentials.xmlPath().getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey")); + iam(endpoint, "PutUserPolicy", Map.of("UserName", name, "PolicyName", policyName, + "PolicyDocument", policyDocument)).then().statusCode(200); + return user; + } catch (Exception | AssertionError e) { + try { + user.close(); + } catch (Exception | AssertionError cleanup) { + e.addSuppressed(cleanup); + } + throw e; + } + } + + /** An IAM user made by {@link #createUser}; {@link #close} removes it with its key and policy. */ + public record User(URI endpoint, String name, String policyName, String accessKeyId, String secretAccessKey) + implements AutoCloseable { + + /** A signer for {@code service} with this user's access key, in us-east-1. */ + public AwsRequestSigner signer(String service) { + return AwsRequestSigner.signedAs(accessKeyId, secretAccessKey, service); + } + + @Override + public void close() throws Exception { + if (accessKeyId != null) { + iam(endpoint, "DeleteAccessKey", Map.of("UserName", name, "AccessKeyId", accessKeyId)) + .then().statusCode(200); + } + iam(endpoint, "DeleteUserPolicy", Map.of("UserName", name, "PolicyName", policyName)); + iam(endpoint, "DeleteUser", Map.of("UserName", name)).then().statusCode(200); + } + } +}