mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(cloudwatch): accept the CloudWatchVersion20130116 JSON target (#6586)
* fix(cloudwatch): accept the CloudWatchVersion20130116 JSON target The CloudWatch console's API sends JSON 1.0 requests to the monitoring endpoint with X-Amz-Target CloudWatchVersion20130116.<Operation>, signed for the monitoring service. Floci knew only the GraniteServiceVersion20100801 prefix the SDKs send, so every such request got HTTP 404 UnknownOperationException. Register the prefix on the monitoring descriptor as a JSON-only target, the mechanism the DynamoDB_20111205 prefix already uses. A request naming it now reaches the CloudWatch JSON handler and the same metrics and alarms, after the same signature validation, unsigned-call refusal and cloudwatch:<Operation> IAM check as the current prefix. CBOR and Smithy RPC v2 requests that name it stay unknown, as do other CloudWatchVersion dates. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudwatch): serve only shared operations on the console JSON target The CloudWatch console's API names its operations with the CloudWatchVersion20130116 target, and several of them take shapes the current API does not: its GetMetricData takes Defaults and Metrics instead of MetricDataQueries, and its PutMetricAlarm and DescribeAlarms describe metric queries with Alias, Namespace and MetricName items instead of Id and MetricStat. The CloudWatch JSON handler ignores members it does not know, so through that target a console GetMetricData answered HTTP 200 with no results, and a console PutMetricAlarm stored an alarm without its metric. Route the target through a handleLegacy entry, as DynamoDB_20111205 is routed, and serve there only the operations whose shapes the two APIs share: ListMetrics, DescribeAlarms, GetMetricStatistics and DeleteAlarms. Every other operation, and a request that sets a member only the console's API defines (CountOnlyRequest, SegmentId, TotalSegments, ExcludeAutoscalingAlarms, ExcludeManagedAlarms), gets HTTP 400 UnsupportedOperation, the error Floci gives an operation it does not implement. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudwatch): refuse unshared members and math alarms on the console target Two gaps were left on the CloudWatchVersion20130116 target. Its DescribeAlarms listed a metric math alarm's Metrics as the current API's Id and MetricStat items, which the console's API does not define, so a client parsing the answer with that API's model sees metrics with no namespace, name or statistic. And only the five console-only members known today were refused, so a member the console's API adds later would again be ignored. Refuse a DescribeAlarms answer that would list a metric math alarm, and check request members against the ones the current API defines for each served operation, as botocore's cloudwatch 2010-08-01 model lists them, instead of against a list of console-only names. A null or false value still counts as unset. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudwatch): serve only honoured members on the console target The console target accepted every request member botocore's model defines for its four operations, but the CloudWatch JSON handler ignores several of them: StateValue, AlarmTypes, ActionPrefix, ChildrenOfAlarmName and ParentsOfAlarmName on DescribeAlarms, ExtendedStatistics on GetMetricStatistics, and RecentlyActive, OwningAccount and IncludeLinkedAccounts on ListMetrics. A request using one got HTTP 200 as if the member were unset. A null member also reached the handler, which read it as the string "null". Accept on the console target only the members the handler honours, plus NextToken and MaxRecords, which change nothing because every result comes back at once. Refuse any other member that is set with HTTP 400 UnsupportedOperation, and drop null members before handling. The four operations are served under these member checks and the DescribeAlarms check, which now names an alarm defined with Metrics rather than a metric math alarm, since it also covers a single metric query. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudwatch): cover presigned console-target calls and align naming Call the CloudWatchVersion20130116 target the console target in the tests, as the docs and comments do, and say why handleLegacy keeps the name of DynamoDB's JSON-only entry point. Cover presigned requests on both prefixes, and keep the DescribeAlarms rows within what AWS accepts by sending AlarmNames and AlarmNamePrefix apart. State in the docs that only the bare prefix over application/x-amz-json-1.0 is accepted, and in the comments that only top-level null members count as unset. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudwatch): pin the console target's other wire forms as unknown The docs say only the bare CloudWatchVersion20130116 prefix over application/x-amz-json-1.0 reaches CloudWatch. Pin that: the bare prefix over application/json or JSON 1.1, and the fully qualified com.amazonaws.cloudwatch.v2013_01_16 form, answer HTTP 404 UnknownOperationException. Name the presigned test for what it checks, a wrong secret, and wrap the new comments at 100 columns. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudwatch): share the signed IAM user setup between signature tests CloudWatchJsonTargetSignatureIntegrationTest and CloudWatchQueryGetSignatureIntegrationTest each carried their own copy of a helper that signs IAM Query calls with the root test key, and of the setup that creates a user with an access key and an inline policy and then removes them. Move both into SignedIamUsers under the testing package and call it from the two classes. It uses real SigV4 signatures, which the classes need because signature validation is on; EnforcementFixtures' placeholder signatures would be refused. The returned user is AutoCloseable, so each test holds it in a try-with-resources block; if creating the key or the policy fails, the parts already made are removed. Test behaviour is unchanged: both classes run the same 13 tests and pass before and after. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
8b57546159
commit
bc75edb4c4
10 files changed
+610
-52
No files matched your search
@@ -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 |
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
+66
@@ -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<String, Set<String>> 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<String> servedMembers = CONSOLE_TARGET_OPERATIONS.get(action);
|
||||
if (servedMembers == null) {
|
||||
return unsupportedWithConsoleTarget("Operation " + action);
|
||||
}
|
||||
ObjectNode served = objectMapper.createObjectNode();
|
||||
for (Map.Entry<String, JsonNode> 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<MetricDatum> datums = parseMetricDataJson(request.path("MetricData"), "MetricData");
|
||||
|
||||
+11
@@ -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
|
||||
|
||||
+289
@@ -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("/");
|
||||
}
|
||||
}
|
||||
+97
@@ -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("{}");
|
||||
}
|
||||
}
|
||||
+29
-46
@@ -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<String, String> 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<String, String> 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<String, String> 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<String, String> parameters) {
|
||||
return parameters.entrySet().stream().map(entry -> URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)
|
||||
+ "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)).collect(Collectors.joining("&"));
|
||||
|
||||
@@ -15,14 +15,16 @@ import java.util.Map;
|
||||
* <li>{@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.</li>
|
||||
* <li>{@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.</li>
|
||||
* 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.</li>
|
||||
* <li>{@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.</li>
|
||||
* It only acts on requests routed to S3, and no other class sends one.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class SignedIamEnforcementProfile implements QuarkusTestProfile {
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>{@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<String, String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user