feat(cloudwatch): implement the dashboard operations on both protocols (#2888)

* feat(cloudwatch): implement the dashboard operations on both protocols

CloudWatch served no dashboard operations at all, so terraform-aws-monitoring's
cloudwatch-dashboard example failed on apply with "api error UnsupportedOperation:
Operation PutDashboard is not supported by CloudWatch Query" - the Query
handler's default branch, reached because PutDashboard had no case.

Adds PutDashboard, GetDashboard, ListDashboards and DeleteDashboards, backed by
a new CloudWatchDashboardsService. Dashboards are pure metadata: the
DashboardBody is stored opaquely and returned verbatim, matching AWS. Put
overwrites an existing name, Get on a missing name is ResourceNotFound,
ListDashboards honours DashboardNamePrefix, DeleteDashboards checks every name
before deleting any so it is all-or-nothing, and responses carry DashboardArn.

Both CloudWatch protocols are wired, since which one a caller uses depends on
its SDK: the Terraform provider sends the Query protocol (form-encoded Action,
routed by credential scope through AwsQueryController), while the AWS CLI and
SDK v3 send JSON 1.0 with X-Amz-Target: GraniteServiceVersion20100801.*, routed
by AwsJsonController. The monitoring service descriptor already declared both,
so no new dispatch was needed - only the four cases in each handler, plus the
new action names in AwsQueryController's CLOUDWATCH_ACTIONS so the no-auth
action-inference path resolves them to CloudWatch too.

* fix(cloudwatch): reject a dashboard body that is not a JSON object

PutDashboard checked only that a body was present, so a malformed document was
stored and answered with success. AWS parses the body and returns
InvalidParameterInput, and the difference matters: a client that sends broken
JSON otherwise learns nothing until the dashboard renders as nothing.

The body is still stored and returned verbatim; this validates that it parses
and is an object, and does not inspect what is inside it.

* fix(cloudwatch): reject a dashboard body with trailing content

readTree stops at the end of the first value, so a body of "{} and then some"
validated as the leading object and the rest was dropped, storing a document AWS
rejects. FAIL_ON_TRAILING_TOKENS makes the reader require exactly one document.

* fix(cloudwatch): make DeleteDashboards best effort, as AWS documents it

The all-or-nothing behaviour was backwards. AWS says the opposite, verbatim: "If
there is an error during this call, the operation attempts to delete as many
dashboards as possible." Deleting ["a", "missing"] where a exists removes a and
errors on missing; this removed neither, so a caller retrying with the same
batch made no progress.

Every name is now attempted, including ones after the first miss, and the first
missing name is reported afterwards. Whether a missing name errors at all is the
part that stays uncertain: DeleteDashboards' own Errors list does not name
ResourceNotFound the way GetDashboard's does, which hints at a silent skip
without establishing one, so the error is kept as the conservative reading.

* feat(cloudwatch): support PutDashboard's Tags, and tag ops on a dashboard ARN

Tags were accepted and dropped, which is the failure mode this emulator is meant
not to have. They are now stored on the dashboard, and CloudWatch's own tag
operations reach it: ListTagsForResource, TagResource and UntagResource take one
ARN for every taggable resource CloudWatch owns, so both protocol handlers route
a dashboard ARN to the dashboards service instead of the alarm store that
answered before.

Tags apply on create only, as AWS documents. A Put that replaces an existing
dashboard keeps the tags that dashboard already had, so an update cannot retag a
resource sideways through an operation that is not a tag operation. More than 50
tags is refused.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-01 17:15:37 -04:00
1 parent 3a212d8360
commit e8eb4f2ff0
10 files changed
+842 -13

No files matched your search

@@ -0,0 +1,226 @@
package io.github.hectorvent.floci.services.cloudwatch.dashboards;
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 static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
/**
* The dashboard operations reach the emulator over the Query protocol - that is what the
* Terraform AWS provider speaks to CloudWatch, and the route that used to answer
* "Operation PutDashboard is not supported by CloudWatch Query".
*/
@QuarkusTest
class CloudWatchDashboardsIntegrationTest {
private static final String CW_SCOPE =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/monitoring/aws4_request";
private static final String JSON_1_0 = "application/x-amz-json-1.0";
@BeforeAll
static void registerJsonParser() {
RestAssured.registerParser(JSON_1_0, Parser.JSON);
}
// RestAssured has no built-in serializer for the x-amz-json content types; send raw text.
private static RequestSpecification json(String target, String body) {
return given()
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs(JSON_1_0, ContentType.TEXT)))
.contentType(JSON_1_0)
.header("X-Amz-Target", "GraniteServiceVersion20100801." + target)
.body(body);
}
private static final String BODY =
"{\"widgets\":[{\"type\":\"metric\",\"properties\":{\"title\":\"a > b\"}}]}";
private void putDashboard(String name, String body) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "PutDashboard")
.formParam("DashboardName", name)
.formParam("DashboardBody", body)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml");
}
@Test
void putThenGetReturnsTheBodyVerbatim() {
putDashboard("query-round-trip", BODY);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "GetDashboard")
.formParam("DashboardName", "query-round-trip")
.when()
.post("/")
.then()
.statusCode(200)
.body("GetDashboardResponse.GetDashboardResult.DashboardBody", equalTo(BODY))
.body("GetDashboardResponse.GetDashboardResult.DashboardArn",
containsString(":dashboard/query-round-trip"));
}
@Test
void getUnknownDashboardReturnsResourceNotFound() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "GetDashboard")
.formParam("DashboardName", "no-such-dashboard")
.when()
.post("/")
.then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
}
@Test
void listDashboardsHonoursTheNamePrefix() {
putDashboard("prefixed-one", BODY);
putDashboard("prefixed-two", BODY);
putDashboard("unprefixed", BODY);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "ListDashboards")
.formParam("DashboardNamePrefix", "prefixed-")
.when()
.post("/")
.then()
.statusCode(200)
.body("ListDashboardsResponse.ListDashboardsResult.DashboardEntries.member.DashboardName",
hasItem("prefixed-one"))
.body("ListDashboardsResponse.ListDashboardsResult.DashboardEntries.member.DashboardName",
not(hasItem("unprefixed")));
}
@Test
void deleteDashboardsRemovesEveryNamedDashboard() {
putDashboard("delete-a", BODY);
putDashboard("delete-b", BODY);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "DeleteDashboards")
.formParam("DashboardNames.member.1", "delete-a")
.formParam("DashboardNames.member.2", "delete-b")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "GetDashboard")
.formParam("DashboardName", "delete-a")
.when()
.post("/")
.then()
.statusCode(404);
}
// The AWS CLI and SDK v3 send the same operations as JSON with an X-Amz-Target header,
// which the emulator dispatches to CloudWatchMetricsJsonHandler instead.
@Test
void theSameOperationsAreServedOverTheJsonProtocol() {
json("PutDashboard", "{\"DashboardName\": \"json-round-trip\", \"DashboardBody\": \"{}\"}")
.when()
.post("/")
.then()
.statusCode(200);
json("GetDashboard", "{\"DashboardName\": \"json-round-trip\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("DashboardBody", equalTo("{}"));
}
/**
* Tags supplied on PutDashboard have to be readable afterwards, and CloudWatch's tag
* operations take one ARN for every resource it owns, so the handler has to route a dashboard
* ARN to the dashboards service rather than the alarm store that answered before.
*/
@Test
void tagsSuppliedOnPutAreReadableThroughListTagsForResource() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "PutDashboard")
.formParam("DashboardName", "tagged")
.formParam("DashboardBody", BODY)
.formParam("Tags.member.1.Key", "team")
.formParam("Tags.member.1.Value", "platform")
.when()
.post("/")
.then()
.statusCode(200);
String arn = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "GetDashboard")
.formParam("DashboardName", "tagged")
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("GetDashboardResponse.GetDashboardResult.DashboardArn");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "ListTagsForResource")
.formParam("ResourceARN", arn)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Key>team</Key>"))
.body(containsString("<Value>platform</Value>"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "UntagResource")
.formParam("ResourceARN", arn)
.formParam("TagKeys.member.1", "team")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CW_SCOPE)
.formParam("Action", "ListTagsForResource")
.formParam("ResourceARN", arn)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("<Key>team</Key>")));
}
}
@@ -0,0 +1,164 @@
package io.github.hectorvent.floci.services.cloudwatch.dashboards;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CloudWatchDashboardsServiceTest {
private static final String REGION = "us-east-1";
private static final String BODY = "{\"widgets\":[{\"type\":\"metric\",\"width\":6}]}";
private CloudWatchDashboardsService service;
@BeforeEach
void setUp() {
service = new CloudWatchDashboardsService(
new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000")
);
}
@Test
void putAndGetReturnsBodyVerbatim() {
service.putDashboard("ops", BODY, REGION);
Dashboard dashboard = service.getDashboard("ops", REGION);
assertEquals(BODY, dashboard.getDashboardBody());
assertEquals("ops", dashboard.getDashboardName());
assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:dashboard/ops",
dashboard.getDashboardArn());
}
@Test
void putOnExistingNameOverwrites() {
service.putDashboard("ops", BODY, REGION);
service.putDashboard("ops", "{\"widgets\":[]}", REGION);
assertEquals("{\"widgets\":[]}", service.getDashboard("ops", REGION).getDashboardBody());
assertEquals(1, service.listDashboards(null, REGION).size());
}
@Test
void getMissingDashboardThrowsResourceNotFound() {
AwsException e = assertThrows(AwsException.class, () -> service.getDashboard("nope", REGION));
assertEquals("ResourceNotFound", e.getErrorCode());
}
@Test
void putRejectsNullBody() {
assertThrows(AwsException.class, () -> service.putDashboard("ops", null, REGION));
}
@Test
void putRejectsAMalformedBody() {
AwsException e = assertThrows(AwsException.class,
() -> service.putDashboard("ops", "{\"widgets\": [", REGION));
assertEquals("InvalidParameterInput", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
}
/** A leading object followed by anything else is still a malformed document, not a dashboard. */
@Test
void putRejectsABodyWithTrailingContentAfterTheObject() {
AwsException e = assertThrows(AwsException.class,
() -> service.putDashboard("ops", "{\"widgets\": []} and then some", REGION));
assertEquals("InvalidParameterInput", e.getErrorCode());
}
/** A body that parses but is not an object is equally unusable as a dashboard. */
@Test
void putRejectsABodyThatIsNotAJsonObject() {
AwsException e = assertThrows(AwsException.class,
() -> service.putDashboard("ops", "[]", REGION));
assertEquals("InvalidParameterInput", e.getErrorCode());
}
@Test
void listDashboardsFiltersByNamePrefix() {
service.putDashboard("prod-api", BODY, REGION);
service.putDashboard("prod-web", BODY, REGION);
service.putDashboard("staging-api", BODY, REGION);
List<Dashboard> filtered = service.listDashboards("prod-", REGION);
assertEquals(List.of("prod-api", "prod-web"),
filtered.stream().map(Dashboard::getDashboardName).toList());
assertEquals(3, service.listDashboards(null, REGION).size());
}
@Test
void listDashboardsIsScopedToRegion() {
service.putDashboard("ops", BODY, REGION);
service.putDashboard("ops", BODY, "eu-west-1");
assertEquals(1, service.listDashboards(null, REGION).size());
assertEquals(1, service.listDashboards(null, "eu-west-1").size());
}
@Test
void deleteDashboardsRemovesEveryNamedDashboard() {
service.putDashboard("a", BODY, REGION);
service.putDashboard("b", BODY, REGION);
service.putDashboard("c", BODY, REGION);
service.deleteDashboards(List.of("a", "b"), REGION);
assertEquals(List.of("c"),
service.listDashboards(null, REGION).stream().map(Dashboard::getDashboardName).toList());
}
@Test
void tagsGivenOnCreateAreReadableByArn() {
service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);
String arn = service.getDashboard("ops", REGION).getDashboardArn();
assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
assertTrue(CloudWatchDashboardsService.isDashboardArn(arn));
}
/**
* AWS documents Tags on PutDashboard as create-only, so replacing a dashboard keeps the tags
* it already had: an update must not be able to retag a resource sideways.
*/
@Test
void tagsOnAReplacingPutDoNotOverwriteTheExistingOnes() {
service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);
String arn = service.getDashboard("ops", REGION).getDashboardArn();
service.putDashboard("ops", BODY, java.util.Map.of("team", "someone-else"), REGION);
assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
}
@Test
void tagAndUntagResourceReachDashboards() {
service.putDashboard("ops", BODY, REGION);
String arn = service.getDashboard("ops", REGION).getDashboardArn();
service.tagResource(arn, java.util.Map.of("env", "dev"), REGION);
assertEquals(java.util.Map.of("env", "dev"), service.listTagsForResource(arn, REGION));
service.untagResource(arn, List.of("env"), REGION);
assertEquals(java.util.Map.of(), service.listTagsForResource(arn, REGION));
}
@Test
void deleteDashboardsIsBestEffortWhenOneNameIsMissing() {
service.putDashboard("a", BODY, REGION);
service.putDashboard("b", BODY, REGION);
AwsException e = assertThrows(AwsException.class,
() -> service.deleteDashboards(List.of("a", "missing", "b"), REGION));
assertEquals("ResourceNotFound", e.getErrorCode());
// AWS attempts to delete as many dashboards as possible, so the two that existed are
// gone even though the batch errored, and a name after the missing one is still tried.
assertEquals(0, service.listDashboards(null, REGION).size());
}
}
@@ -9,6 +9,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import jakarta.ws.rs.core.Response;
import java.math.BigDecimal;
import java.time.Instant;
@@ -41,7 +42,11 @@ class CloudWatchMetricsJsonHandlerTest {
new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000")
);
handler = new CloudWatchMetricsJsonHandler(service, MAPPER);
CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(
new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000")
);
handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, MAPPER);
}
/**
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -24,7 +25,9 @@ class CloudWatchMetricsQueryHandlerTest {
private static final String REGION = "us-east-1";
private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metricsService);
// The alarm cases below never reach a dashboard operation; the handler simply routes both.
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(
metricsService, mock(CloudWatchDashboardsService.class));
@Test
void putMetricAlarmDefaultsActionsEnabledToTrueWhenOmitted() {
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -31,8 +32,10 @@ class CloudWatchMetricsTagsTest {
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000")
);
queryHandler = new CloudWatchMetricsQueryHandler(service);
jsonHandler = new CloudWatchMetricsJsonHandler(service, objectMapper);
CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService);
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, objectMapper);
}
@Test