From 82d5c18018d0b8f4b078d2efea07642bf861d247 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 28 Nov 2026 12:47:10 -0600 Subject: [PATCH] fix(cloudwatch): keep dashboards global per account instead of per region (#9643) Dashboards were stored under region::name keys, so a dashboard put through one Region was missing from GetDashboard, ListDashboards and DeleteDashboards in every other Region of the same account. The CloudWatch model says otherwise. PutDashboard: "All dashboards in your account are global, not region-specific." ListDashboards: "Returns a list of the dashboards for your account." Key dashboards by name in the account's store. Dashboards persisted under the old keys are folded onto their name when the store loads, in every account; when one name was stored in several Regions the most recently modified copy is kept, a tie going to the Region that sorts first. A legacy entry is one whose key ends in the dashboard's own name after the separator, whatever the Region, and a folded source is deleted where it was stored, including the bare key of a dashboard saved before stores kept accounts apart. A region-ful dashboard ARN now resolves whatever Region it names, and the regionless ARN is unchanged. PutDashboard now refuses a name outside A-Z, a-z, 0-9, - and _ with InvalidParameterValue "The value for field DashboardName contains invalid characters. It can only contain alphanumerics, dash (-) and underscore (_).", as AWS does. Signed-off-by: Hector Ventura --- .../CloudWatchDashboardsService.java | 158 ++++++++++++++---- ...atchTagUnknownResourceIntegrationTest.java | 4 +- .../CloudWatchDashboardsIntegrationTest.java | 68 +++++++- .../CloudWatchDashboardsServiceTest.java | 140 ++++++++++++++-- 4 files changed, 326 insertions(+), 44 deletions(-) diff --git a/src/main/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsService.java b/src/main/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsService.java index ab528d1c49..7aec03206b 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsService.java @@ -12,6 +12,8 @@ import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudwatch.dashboards.model.Dashboard; @@ -26,10 +28,20 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.TreeMap; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.regex.Pattern; /** * CloudWatch dashboards. Dashboards are pure metadata: the DashboardBody is an opaque JSON * document that AWS stores and hands back verbatim, so there is no backing behaviour here. + * + *

Dashboards are global per account, as PutDashboard documents ("All dashboards in your account + * are global, not region-specific"), so they are keyed by name alone in the account's store and + * every Region of the account sees the same set. The Region a call arrives through only picks + * the partition of a new dashboard's ARN. */ @ApplicationScoped public class CloudWatchDashboardsService { @@ -41,6 +53,19 @@ public class CloudWatchDashboardsService { /** AWS's documented ceiling for PutDashboard's Tags. */ private static final int MAX_TAGS = 50; + /** Separates the Region from the name in the keys dashboards were stored under before. */ + private static final String LEGACY_SEPARATOR = "::"; + // PutDashboard's DashboardName documentation: valid characters are A-Z, a-z, 0-9, "-", and "_". + private static final Pattern DASHBOARD_NAME = Pattern.compile("[A-Za-z0-9_-]+"); + + /** + * Orders the legacy copies of one name so the last is the one kept: the most recently + * modified, and on a tie the one whose key, so whose Region, sorts first. + */ + private static final Comparator> LEGACY_WINNER_ORDER = + Comparator.>comparingLong(entry -> entry.getValue().getLastModified()) + .thenComparing(Map.Entry::getKey, Comparator.reverseOrder()); + private static final ObjectReader JSON = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .readerFor(JsonNode.class); @@ -53,6 +78,7 @@ public class CloudWatchDashboardsService { this.dashboardStore = storageFactory.create("cloudwatchmetrics", "cwdashboards.json", new TypeReference>() {}); this.regionResolver = regionResolver; + foldLegacyRegionKeys(); } // Public rather than package-private so handler tests in the metrics package can build @@ -61,6 +87,83 @@ public class CloudWatchDashboardsService { RegionResolver regionResolver) { this.dashboardStore = dashboardStore; this.regionResolver = regionResolver; + foldLegacyRegionKeys(); + } + + /** + * Moves dashboards stored under the old {@code region::name} keys onto their name, in every + * account that holds one: a key that ends in the dashboard's own name after the separator, which + * no dashboard name can hold since names allow only letters, digits, dashes and underscores. A + * folded source is deleted where it was stored. When one account stored the same + * name in several Regions, only one dashboard can survive: the most recently modified copy is + * kept, a tie going to the Region that sorts first, and the other copies are dropped. + */ + private void foldLegacyRegionKeys() { + if (dashboardStore instanceof AccountAwareStorageBackend accounts) { + Map> legacyByAccount = new TreeMap<>(); + for (AccountEntry entry : accounts.scanAllAccountEntries(key -> key.contains(LEGACY_SEPARATOR))) { + if (isLegacyEntry(entry.key(), entry.value())) { + legacyByAccount.computeIfAbsent(entry.accountId(), ignored -> new LinkedHashMap<>()) + .put(entry.key(), entry.value()); + } + } + legacyByAccount.forEach((accountId, legacy) -> foldLegacyEntries(legacy, + key -> accounts.getForAccount(accountId, key), + (key, dashboard) -> accounts.putForAccount(accountId, key, dashboard), + key -> deleteLegacySource(accounts, accountId, key))); + return; + } + Map legacy = new LinkedHashMap<>(); + for (String key : dashboardStore.keys()) { + dashboardStore.get(key).filter(dashboard -> isLegacyEntry(key, dashboard)) + .ifPresent(dashboard -> legacy.put(key, dashboard)); + } + foldLegacyEntries(legacy, dashboardStore::get, dashboardStore::put, dashboardStore::delete); + } + + private static void foldLegacyEntries(Map legacy, + Function> get, + BiConsumer put, + Consumer delete) { + if (legacy.isEmpty()) { + return; + } + Map> winners = new TreeMap<>(); + for (Map.Entry entry : legacy.entrySet()) { + String name = entry.getKey().substring(entry.getKey().indexOf(LEGACY_SEPARATOR) + LEGACY_SEPARATOR.length()); + winners.merge(name, entry, (kept, other) -> LEGACY_WINNER_ORDER.compare(kept, other) >= 0 ? kept : other); + } + winners.forEach((name, winner) -> { + if (get.apply(name).isEmpty()) { + put.accept(name, withRegionlessArn(winner.getValue())); + } + }); + legacy.keySet().forEach(delete); + LOG.infov("Moved {0} dashboard(s) stored per Region onto account-wide keys ({1} name(s))", + legacy.size(), winners.size()); + } + + /** + * Deletes a folded legacy key where it was stored: under the account's prefix, or, for the default account, also + * under the bare key a dashboard saved before stores kept accounts apart sits under. + */ + private static void deleteLegacySource(AccountAwareStorageBackend accounts, String accountId, + String key) { + accounts.deleteForAccount(accountId, key); + if (accountId.equals(accounts.defaultAccountId())) { + accounts.deleteRaw(key); + } + } + + /** + * An entry stored under the old {@code region::name} form: a Region before the separator and the dashboard's own + * name after it. The Region is not checked against a catalog, since Floci serves Regions none publishes. A name + * an older Floci accepted with the separator in it, once folded, is its whole key, so it is not folded again. + */ + private static boolean isLegacyEntry(String key, Dashboard dashboard) { + int separator = key.indexOf(LEGACY_SEPARATOR); + return separator > 0 + && key.substring(separator + LEGACY_SEPARATOR.length()).equals(dashboard.getDashboardName()); } /** Creates the dashboard, or replaces it wholesale when the name is already taken. */ @@ -80,12 +183,16 @@ public class CloudWatchDashboardsService { if (dashboardName == null || dashboardName.isBlank()) { throw new AwsException("InvalidParameterValue", "DashboardName is required.", 400); } + if (!DASHBOARD_NAME.matcher(dashboardName).matches()) { + throw new AwsException("InvalidParameterValue", "The value for field DashboardName contains invalid " + + "characters. It can only contain alphanumerics, dash (-) and underscore (_).\n", 400); + } if (dashboardBody == null) { throw new AwsException("InvalidParameterValue", "DashboardBody is required.", 400); } validateDashboardBody(dashboardBody); - Dashboard existing = dashboardStore.get(key(region, dashboardName)).orElse(null); + Dashboard existing = dashboardStore.get(dashboardName).orElse(null); Dashboard dashboard = new Dashboard(dashboardName, dashboardArn(region, dashboardName), dashboardBody); dashboard.setLastModified(Instant.now().getEpochSecond()); if (existing != null) { @@ -100,7 +207,7 @@ public class CloudWatchDashboardsService { // put() overwrites, which is exactly PutDashboard's semantics: an existing name is // replaced in full rather than merged. - dashboardStore.put(key(region, dashboardName), dashboard); + dashboardStore.put(dashboardName, dashboard); LOG.debugv("PutDashboard: {0} in {1}", dashboardName, region); return dashboard; } @@ -125,14 +232,13 @@ public class CloudWatchDashboardsService { } public Dashboard getDashboard(String dashboardName, String region) { - return dashboardStore.get(key(region, dashboardName)) + return dashboardStore.get(dashboardName) .map(CloudWatchDashboardsService::withRegionlessArn) .orElseThrow(() -> notFound(dashboardName)); } public List listDashboards(String dashboardNamePrefix, String region) { - String keyPrefix = region + "::"; - List all = new ArrayList<>(dashboardStore.scan(k -> k.startsWith(keyPrefix)).stream() + List all = new ArrayList<>(dashboardStore.scan(k -> true).stream() .map(CloudWatchDashboardsService::withRegionlessArn) .toList()); if (dashboardNamePrefix != null && !dashboardNamePrefix.isBlank()) { @@ -151,7 +257,7 @@ public class CloudWatchDashboardsService { } String prefix = dashboardNamePrefix == null || dashboardNamePrefix.isBlank() ? "" : dashboardNamePrefix; - String scope = "cloudwatch-dashboards:" + regionResolver.getAccountId() + ":" + region + ":" + prefix; + String scope = "cloudwatch-dashboards:" + regionResolver.getAccountId() + ":" + prefix; return Pagination.paginate(listDashboards(prefix, region), Dashboard::getDashboardName, 1000, nextToken, scope, token -> new AwsException("InvalidParameterValue", "Invalid NextToken.", 400)); @@ -175,13 +281,13 @@ public class CloudWatchDashboardsService { } String firstMissing = null; for (String name : dashboardNames) { - if (dashboardStore.get(key(region, name)).isEmpty()) { + if (dashboardStore.get(name).isEmpty()) { if (firstMissing == null) { firstMissing = name; } continue; } - dashboardStore.delete(key(region, name)); + dashboardStore.delete(name); } LOG.debugv("DeleteDashboards: {0} in {1}", dashboardNames, region); if (firstMissing != null) { @@ -198,19 +304,19 @@ public class CloudWatchDashboardsService { } public Map listTagsForResource(String resourceArn, String region) { - return requireDashboard(resourceArn, region).getTags(); + return requireDashboard(resourceArn).getTags(); } public void tagResource(String resourceArn, Map tags, String region) { - Dashboard dashboard = requireDashboard(resourceArn, region); + Dashboard dashboard = requireDashboard(resourceArn); dashboard.getTags().putAll(tags); - dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard); + dashboardStore.put(dashboard.getDashboardName(), dashboard); } public void untagResource(String resourceArn, List tagKeys, String region) { - Dashboard dashboard = requireDashboard(resourceArn, region); + Dashboard dashboard = requireDashboard(resourceArn); tagKeys.forEach(dashboard.getTags()::remove); - dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard); + dashboardStore.put(dashboard.getDashboardName(), dashboard); } /** @@ -219,16 +325,16 @@ public class CloudWatchDashboardsService { * {@code ResourceNotFound} that {@code GetDashboard} declares, * so this is not the {@link #notFound(String)} used by the rest of this service. */ - private Dashboard requireDashboard(String resourceArn, String region) { - return findByArn(resourceArn, region).orElseThrow(() -> + private Dashboard requireDashboard(String resourceArn) { + return findByArn(resourceArn).orElseThrow(() -> new AwsException("ResourceNotFoundException", "Dashboard does not exist: " + resourceArn, 404)); } - private Optional findByArn(String resourceArn, String region) { - return dashboardStore.scan(k -> k.startsWith(region + "::")).stream() + private Optional findByArn(String resourceArn) { + return dashboardStore.scan(k -> true).stream() .map(CloudWatchDashboardsService::withRegionlessArn) - .filter(d -> namesDashboard(resourceArn, d.getDashboardArn(), region)) + .filter(d -> namesDashboard(resourceArn, d.getDashboardArn())) .findFirst(); } @@ -237,18 +343,14 @@ public class CloudWatchDashboardsService { * *

AWS's dashboard ARN has no Region ({@code arn::cloudwatch:::dashboard/}), * which is what Floci mints. Floci used to mint one with the Region of the request, and callers - * may still hold those, so that form resolves too, but only for the Region the dashboard is - * stored in: an ARN naming another Region is a miss rather than a same-named dashboard here. + * may still hold those, so that form resolves too. A dashboard is global per account, so the + * Region such an ARN names does not matter. */ - private static boolean namesDashboard(String candidate, String arn, String region) { + private static boolean namesDashboard(String candidate, String arn) { if (candidate == null || arn == null) { return false; } - if (candidate.equals(arn)) { - return true; - } - String[] fields = candidate.split(":", 6); - return fields.length == 6 && region.equals(fields[3]) && withoutRegion(candidate).equals(arn); + return candidate.equals(arn) || withoutRegion(candidate).equals(arn); } /** The dashboard's ARN: regionless, in the partition of the Region it was put through. */ @@ -280,10 +382,6 @@ public class CloudWatchDashboardsService { .toString(); } - private static String key(String region, String dashboardName) { - return region + "::" + dashboardName; - } - private static AwsException notFound(String dashboardName) { return new AwsException("ResourceNotFound", "Dashboard does not exist: " + dashboardName, 404); diff --git a/src/test/java/io/floci/aws/services/cloudwatch/CloudWatchTagUnknownResourceIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/CloudWatchTagUnknownResourceIntegrationTest.java index c3d93822cd..eae2ec63a0 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/CloudWatchTagUnknownResourceIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/CloudWatchTagUnknownResourceIntegrationTest.java @@ -209,8 +209,8 @@ class CloudWatchTagUnknownResourceIntegrationTest { assertQueryTagOpsSucceed("arn:aws:cloudwatch::000000000000:dashboard/tag-regionless-dashboard"); - // Still only an absent region: another region's ARN remains a miss. - assertQueryTagOpsNotFound( + // Dashboards are global per account, so an old region-ful ARN naming any Region is the same one. + assertQueryTagOpsSucceed( "arn:aws:cloudwatch:eu-west-1:000000000000:dashboard/tag-regionless-dashboard"); } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsIntegrationTest.java index 00a41c0c32..79045d81d9 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsIntegrationTest.java @@ -37,6 +37,9 @@ class CloudWatchDashboardsIntegrationTest { private static final String CW_SCOPE = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/monitoring/aws4_request"; + private static final String EU_SCOPE = + "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-1/monitoring/aws4_request"; + private static final String JSON_1_0 = "application/x-amz-json-1.0"; @BeforeAll @@ -185,12 +188,16 @@ class CloudWatchDashboardsIntegrationTest { "AWS4-HMAC-SHA256 Credential=210987654321/20260205/us-east-1/monitoring/aws4_request") .when().post("/") .then().statusCode(400); + // Dashboards are global per account, so the listing a token continues is the same + // from every Region. json("ListDashboards", "{\"DashboardNamePrefix\":\"pagination-issue-\",\"NextToken\":\"" + nextToken + "\"}") .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-west-2/monitoring/aws4_request") .when().post("/") - .then().statusCode(400); + .then().statusCode(200) + .body("DashboardEntries[0].DashboardName", + equalTo(secondPage.jsonPath().getString("DashboardEntries[0].DashboardName"))); queryListDashboards(null, "not-a-token") .when().post("/") .then().statusCode(400); @@ -239,6 +246,65 @@ class CloudWatchDashboardsIntegrationTest { .statusCode(404); } + // Catches: dashboards kept per Region. PutDashboard documents "All dashboards in your account + // are global, not region-specific", so every Region of the account sees, lists and deletes one. + @Test + void aDashboardPutInOneRegionIsVisibleAndDeletableFromAnother() { + putDashboard("cross-region", BODY); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", EU_SCOPE) + .formParam("Action", "GetDashboard") + .formParam("DashboardName", "cross-region") + .when() + .post("/") + .then() + .statusCode(200) + .body("GetDashboardResponse.GetDashboardResult.DashboardBody", equalTo(BODY)); + + json("GetDashboard", "{\"DashboardName\": \"cross-region\"}") + .header("Authorization", EU_SCOPE) + .when() + .post("/") + .then() + .statusCode(200) + .body("DashboardBody", equalTo(BODY)); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", EU_SCOPE) + .formParam("Action", "ListDashboards") + .formParam("DashboardNamePrefix", "cross-region") + .when() + .post("/") + .then() + .statusCode(200) + .body("ListDashboardsResponse.ListDashboardsResult.DashboardEntries.member.DashboardName", + equalTo("cross-region")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", EU_SCOPE) + .formParam("Action", "DeleteDashboards") + .formParam("DashboardNames.member.1", "cross-region") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CW_SCOPE) + .formParam("Action", "GetDashboard") + .formParam("DashboardName", "cross-region") + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("ResourceNotFound")); + } + // 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 diff --git a/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsServiceTest.java b/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsServiceTest.java index 80ee39548b..670c2c653b 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/dashboards/CloudWatchDashboardsServiceTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.cloudwatch.dashboards; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.cloudwatch.dashboards.model.Dashboard; import org.junit.jupiter.api.BeforeEach; @@ -9,6 +10,7 @@ import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; +import java.util.Set; import static org.junit.jupiter.api.Assertions.*; @@ -118,13 +120,17 @@ class CloudWatchDashboardsServiceTest { assertEquals(3, service.listDashboards(null, REGION).size()); } + // Catches: dashboards kept per Region; AWS keeps them global per account. @Test - void listDashboardsIsScopedToRegion() { + void aDashboardPutInOneRegionIsTheSameDashboardInEveryRegion() { service.putDashboard("ops", BODY, REGION); - service.putDashboard("ops", BODY, "eu-west-1"); + service.putDashboard("ops", "{\"widgets\":[]}", "eu-west-1"); assertEquals(1, service.listDashboards(null, REGION).size()); - assertEquals(1, service.listDashboards(null, "eu-west-1").size()); + assertEquals("{\"widgets\":[]}", service.getDashboard("ops", REGION).getDashboardBody()); + + service.deleteDashboards(List.of("ops"), "ap-southeast-2"); + assertTrue(service.listDashboards(null, "eu-west-1").isEmpty()); } @Test @@ -196,18 +202,130 @@ class CloudWatchDashboardsServiceTest { assertEquals(Map.of(), service.listTagsForResource(regionless, REGION)); } - /** - * The old region-ful form resolves only for the Region the dashboard was put through. An - * ARN naming a different Region must not resolve to the same-named dashboard in this one. - */ + /** A dashboard is global per account, so an old region-ful ARN naming any Region resolves. */ @Test - void anArnNamingAnotherRegionDoesNotResolve() { + void anOldRegionfulArnNamingAnotherRegionResolves() { service.putDashboard("ops", BODY, REGION); String elsewhere = "arn:aws:cloudwatch:eu-west-1:000000000000:dashboard/ops"; - AwsException e = assertThrows(AwsException.class, - () -> service.listTagsForResource(elsewhere, REGION)); - assertEquals("ResourceNotFoundException", e.getErrorCode()); + service.tagResource(elsewhere, Map.of("env", "dev"), REGION); + assertEquals(Map.of("env", "dev"), service.listTagsForResource(elsewhere, "eu-west-1")); + } + + // Catches: dashboards persisted under the old region::name keys vanishing, or folding into + // an arbitrary copy when one name was stored in two Regions. + @Test + void legacyRegionKeysFoldOntoTheNameKeepingTheMostRecentlyModifiedCopy() { + InMemoryStorage store = new InMemoryStorage<>(); + store.put("us-east-1::ops", legacyDashboard("ops", "us-east-1", "{\"v\":\"old\"}", 100)); + store.put("eu-west-1::ops", legacyDashboard("ops", "eu-west-1", "{\"v\":\"new\"}", 200)); + store.put("eu-west-1::solo", legacyDashboard("solo", "eu-west-1", BODY, 50)); + + CloudWatchDashboardsService folded = new CloudWatchDashboardsService(store, + new RegionResolver(REGION, "000000000000")); + + assertEquals(Set.of("ops", "solo"), store.keys()); + assertEquals("{\"v\":\"new\"}", folded.getDashboard("ops", "eu-west-1").getDashboardBody()); + assertEquals("arn:aws:cloudwatch::000000000000:dashboard/ops", + folded.getDashboard("ops", "ap-southeast-2").getDashboardArn()); + assertEquals(List.of("ops", "solo"), + folded.listDashboards(null, REGION).stream().map(Dashboard::getDashboardName).toList()); + } + + @Test + void aLegacyTieGoesToTheRegionThatSortsFirst() { + InMemoryStorage store = new InMemoryStorage<>(); + store.put("us-west-2::ops", legacyDashboard("ops", "us-west-2", "{\"r\":\"us-west-2\"}", 100)); + store.put("ap-south-1::ops", legacyDashboard("ops", "ap-south-1", "{\"r\":\"ap-south-1\"}", 100)); + + CloudWatchDashboardsService folded = new CloudWatchDashboardsService(store, + new RegionResolver(REGION, "000000000000")); + + assertEquals("{\"r\":\"ap-south-1\"}", folded.getDashboard("ops", "eu-west-1").getDashboardBody()); + } + + @Test + void legacyRegionKeysFoldInEveryAccount() { + AccountAwareStorageBackend store = AccountAwareStorageBackend.inMemory("000000000000"); + store.putForAccount("000000000000", "us-east-1::ops", legacyDashboard("ops", "us-east-1", BODY, 100)); + store.putForAccount("111111111111", "eu-west-1::ops", legacyDashboard("ops", "eu-west-1", BODY, 100)); + + new CloudWatchDashboardsService(store, new RegionResolver(REGION, "000000000000")); + + assertTrue(store.getForAccount("000000000000", "ops").isPresent()); + assertTrue(store.getForAccount("111111111111", "ops").isPresent()); + assertTrue(store.getForAccount("000000000000", "us-east-1::ops").isEmpty()); + assertTrue(store.getForAccount("111111111111", "eu-west-1::ops").isEmpty()); + } + + /** + * A dashboard saved before stores kept accounts apart sits under a bare {@code region::name} key of the default + * account. Folding it must remove that exact key, or a later delete of the dashboard is undone by the next load. + */ + @Test + void aDeletedDashboardFoldedFromABareLegacyKeyStaysDeletedAfterReload() { + InMemoryStorage raw = new InMemoryStorage<>(); + raw.put("us-east-1::ops", legacyDashboard("ops", "us-east-1", BODY, 100)); + AccountAwareStorageBackend store = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + CloudWatchDashboardsService first = new CloudWatchDashboardsService(store, + new RegionResolver(REGION, "000000000000")); + + assertEquals(Set.of("000000000000/ops"), raw.keys()); + first.deleteDashboards(List.of("ops"), REGION); + new CloudWatchDashboardsService(store, new RegionResolver(REGION, "000000000000")); + + assertEquals(Set.of(), raw.keys()); + } + + /** As recorded against AWS: a name outside alphanumerics, dash and underscore is refused. */ + @Test + void aNameWithACharacterOutsideTheAllowedSetIsRefused() { + for (String name : List.of("prod::copy", "with space", "dot.ted")) { + AwsException refused = assertThrows(AwsException.class, () -> service.putDashboard(name, BODY, REGION)); + assertEquals("InvalidParameterValue", refused.getErrorCode()); + assertEquals("The value for field DashboardName contains invalid characters. It can only contain " + + "alphanumerics, dash (-) and underscore (_).\n", refused.getMessage()); + } + assertTrue(service.listDashboards(null, REGION).isEmpty()); + } + + /** + * Floci serves a Region a partition's pattern admits, or any Region with {@code allow-unknown-regions}, so a + * dashboard stored per Region may sit under a Region no catalog publishes. It folds like any other. + */ + @Test + void legacyKeysOfRegionsNoCatalogPublishesFoldToo() { + InMemoryStorage store = new InMemoryStorage<>(); + store.put("us-east-5::ops", legacyDashboard("ops", "us-east-5", BODY, 100)); + store.put("local::solo", legacyDashboard("solo", "local", BODY, 100)); + + CloudWatchDashboardsService folded = new CloudWatchDashboardsService(store, + new RegionResolver(REGION, "000000000000")); + + assertEquals(Set.of("ops", "solo"), store.keys()); + assertEquals("ops", folded.getDashboard("ops", REGION).getDashboardName()); + } + + /** + * A key stored per Region ends in the dashboard's own name after the separator. A name an older Floci accepted + * with the separator in it, once folded, is its whole key, so it stays where it is on the next load. + */ + @Test + void aFoldedNameHoldingTheSeparatorIsNotFoldedAgain() { + InMemoryStorage store = new InMemoryStorage<>(); + store.put("prod::copy", new Dashboard("prod::copy", + "arn:aws:cloudwatch::000000000000:dashboard/prod::copy", BODY)); + + new CloudWatchDashboardsService(store, new RegionResolver(REGION, "000000000000")); + + assertEquals(Set.of("prod::copy"), store.keys()); + } + + private static Dashboard legacyDashboard(String name, String region, String body, long lastModified) { + Dashboard dashboard = new Dashboard(name, + "arn:aws:cloudwatch:" + region + ":000000000000:dashboard/" + name, body); + dashboard.setLastModified(lastModified); + return dashboard; } /**