diff --git a/docs/services/appconfig.md b/docs/services/appconfig.md index 8badaa7a89..45503b6a42 100644 --- a/docs/services/appconfig.md +++ b/docs/services/appconfig.md @@ -57,6 +57,12 @@ such as one from an S3 or SSM source, returns `ResourceNotFoundException`. `AlarmRoleArn`, and environment reads return them; an environment created without monitors returns none. Floci does not evaluate the alarms or trigger automatic rollback. More than five monitors, or an `AlarmRoleArn` that is not an IAM role ARN, returns `BadRequestException`. + +Applications and environments keep their tags: the `Tags` given to `CreateApplication` or `CreateEnvironment`, and +those `TagResource` and `UntagResource` change, are returned by `ListTagsForResource` and read by IAM for +`aws:ResourceTag` conditions, not by the resource's own reads. `Tags` that are not a map of strings return +`BadRequestException`. `TagResource` on a configuration profile, deployment strategy, extension or extension +association ARN is accepted and not stored, and `ListTagsForResource` returns no tags for it. `StartDeployment` and `GetDeployment` return the deployed profile's name and location URI as `ConfigurationName` and `ConfigurationLocationUri`. Deployments stored by earlier Floci versions did not record them, so on those neither is set. @@ -126,8 +132,8 @@ A change to a configuration profile's `Type` is accepted on update and not appli type it was created with, as `UpdateConfigurationProfile` has no `Type` member. Deleting an environment deletes its deployments, and deleting a configuration profile deletes its hosted configuration -versions. Floci keeps tags on applications only, so `Tags` on the other three types are accepted and not stored, as -`TagResource` treats them; so are a configuration profile's `KmsKeyIdentifier`, `RetrievalRoleArn` and `Validators`, +versions. CloudFormation applies `Tags` to applications only, so `Tags` on the other three types are accepted and +not stored; so are a configuration profile's `KmsKeyIdentifier`, `RetrievalRoleArn` and `Validators`, and `DeletionProtectionCheck`. `ReplicateTo: SSM_DOCUMENT` writes no SSM document. `AWS::AppConfig::HostedConfigurationVersion`, `Deployment`, `Extension` and `ExtensionAssociation` are not provisioned. diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java index ca490a5277..cac6890434 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java @@ -38,6 +38,8 @@ import java.util.Map; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class AppConfigController { + private static final String STORED_TAGS_MEMBER = "tags"; + private final AppConfigService service; private final AppConfigDataService dataService; private final ObjectMapper objectMapper; @@ -58,13 +60,13 @@ public class AppConfigController { @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); Application app = service.createApplication(request); - return Response.status(201).entity(app).build(); + return Response.status(201).entity(withoutTags(app)).build(); } @GET @Path("/applications/{id}") public Response getApplication(@PathParam("id") String id) { - return Response.ok(service.getApplication(id)).build(); + return Response.ok(withoutTags(service.getApplication(id))).build(); } @PATCH @@ -72,7 +74,7 @@ public class AppConfigController { public Response updateApplication(@PathParam("id") String id, String body) throws IOException { @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); - return Response.ok(service.updateApplication(id, request)).build(); + return Response.ok(withoutTags(service.updateApplication(id, request))).build(); } @GET @@ -82,7 +84,7 @@ public class AppConfigController { @Context UriInfo uriInfo) { PaginatedResult page = service.listApplicationsPage( Pagination.parseMaxResults(maxResults, "BadRequestException"), rawNextToken(nextToken, uriInfo)); - return listResponse(page.items(), page.nextToken()); + return listResponse(page.items().stream().map(this::withoutTags).toList(), page.nextToken()); } @DELETE @@ -100,13 +102,13 @@ public class AppConfigController { @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); Environment env = service.createEnvironment(appId, request); - return Response.status(201).entity(env).build(); + return Response.status(201).entity(withoutTags(env)).build(); } @GET @Path("/applications/{appId}/environments/{envId}") public Response getEnvironment(@PathParam("appId") String appId, @PathParam("envId") String envId) { - return Response.ok(service.getEnvironment(appId, envId)).build(); + return Response.ok(withoutTags(service.getEnvironment(appId, envId))).build(); } @DELETE @@ -124,7 +126,7 @@ public class AppConfigController { @Context UriInfo uriInfo) { PaginatedResult page = service.listEnvironmentsPage(appId, parseListMaxResults(maxResults, uriInfo), rawNextToken(nextToken, uriInfo)); - return listResponse(page.items(), page.nextToken()); + return listResponse(page.items().stream().map(this::withoutTags).toList(), page.nextToken()); } // ──────────────────────────── Configuration Profile ──────────────────────────── @@ -278,6 +280,16 @@ public class AppConfigController { return listResponse(page.items(), page.nextToken()); } + /** + * An application or environment as AWS answers it. Their models carry the tags storage keeps, which AWS returns + * only through ListTagsForResource, so the stored {@code tags} member is left out of the answer. + */ + private ObjectNode withoutTags(Object model) { + ObjectNode node = objectMapper.valueToTree(model); + node.remove(STORED_TAGS_MEMBER); + return node; + } + private Response listResponse(List items, String nextToken) { ObjectNode root = objectMapper.createObjectNode(); ArrayNode itemArray = root.putArray("Items"); diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java index fb308524f8..26684d173f 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java @@ -44,7 +44,7 @@ public class AppConfigService { private static final Logger LOG = Logger.getLogger(AppConfigService.class); private final RegionScopedStorage applicationStore; - private final StorageBackend environmentStore; + private final RegionScopedStorage environmentStore; private final StorageBackend profileStore; private final StorageBackend strategyStore; private final StorageBackend versionStore; @@ -86,10 +86,12 @@ public class AppConfigService { // ──────────────────────────── Application ──────────────────────────── public Application createApplication(Map request) { + Map tags = requestTags(request); Application app = new Application(); app.setId(shortId(7)); app.setName((String) request.get("Name")); app.setDescription((String) request.get("Description")); + app.getTags().putAll(tags); applicationStore.put(app.getId(), app); return app; } @@ -173,6 +175,7 @@ public class AppConfigService { public Environment createEnvironment(String applicationIdentifier, Map request) { List monitors = monitors(request.get("Monitors")); + Map tags = requestTags(request); String appId = resolveApplication(applicationIdentifier).getId(); Environment env = new Environment(); env.setId(shortId(7)); @@ -181,6 +184,7 @@ public class AppConfigService { env.setDescription((String) request.get("Description")); env.setState("READY"); env.setMonitors(monitors); + env.getTags().putAll(tags); environmentStore.put(env.getId(), env); return env; } @@ -912,9 +916,8 @@ public class AppConfigService { } /** - * The tags of the application {@code arn} names by its id, read in the ARN's account and Region, which IAM gives a - * condition on a resource's tags; empty for any other resource, Floci keeping tags on applications alone, or for - * one it does not hold. + * The tags of the application or environment {@code arn} names by its ids, read in the ARN's account and Region, + * which IAM gives a condition on a resource's tags; empty for any other resource, or for one it does not hold. */ public Map storedTags(String arn) { if (!AwsArnUtils.isArnFor(arn, "appconfig")) { @@ -923,6 +926,10 @@ public class AppConfigService { AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); String id = parsed.resource().startsWith(APPLICATION_RESOURCE) ? parsed.resource().substring(APPLICATION_RESOURCE.length()) : ""; + String[] environmentPath = id.split("/", -1); + if (environmentPath.length == 3 && "environment".equals(environmentPath[1])) { + return storedEnvironmentTags(parsed, environmentPath[0], environmentPath[2]); + } if (id.isEmpty() || id.contains("/")) { return Map.of(); } @@ -932,6 +939,13 @@ public class AppConfigService { .orElse(Map.of()); } + private Map storedEnvironmentTags(AwsArnUtils.Arn arn, String appId, String envId) { + return environmentStore.readInAccount(arn.accountId(), arn.region(), envId) + .filter(env -> envId.equals(env.getId()) && appId.equals(env.getApplicationId())) + .map(Environment::getTags) + .orElse(Map.of()); + } + public synchronized void tagApplication(String appId, Map tags) { Application app = copy(getApplication(appId)); app.getTags().putAll(tags); @@ -944,6 +958,22 @@ public class AppConfigService { applicationStore.put(app.getId(), app); } + public Map getEnvironmentTags(String appId, String envId) { + return getEnvironment(appId, envId).getTags(); + } + + public synchronized void tagEnvironment(String appId, String envId, Map tags) { + Environment env = copy(getEnvironment(appId, envId)); + env.getTags().putAll(tags); + environmentStore.put(env.getId(), env); + } + + public synchronized void untagEnvironment(String appId, String envId, List tagKeys) { + Environment env = copy(getEnvironment(appId, envId)); + tagKeys.forEach(env.getTags()::remove); + environmentStore.put(env.getId(), env); + } + /** * Sets the tags of the application whose ID is exactly {@code applicationId} to {@code tags}, * removing any other key, as a CloudFormation create or update of {@code Tags} does; {@code tags} @@ -967,6 +997,24 @@ public class AppConfigService { return StorageJson.copy(entity); } + private static Map requestTags(Map request) { + Object tags = request.get("Tags"); + if (tags == null) { + return Map.of(); + } + if (!(tags instanceof Map tagMap)) { + throw new AwsException("BadRequestException", "Tags must be a map of strings", 400); + } + Map result = new HashMap<>(); + for (Map.Entry tag : tagMap.entrySet()) { + if (!(tag.getValue() instanceof String value)) { + throw new AwsException("BadRequestException", "Tags must be a map of strings", 400); + } + result.put(String.valueOf(tag.getKey()), value); + } + return result; + } + private static String shortId(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigStoredResourceArns.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigStoredResourceArns.java index 087380bed7..51a97825f4 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigStoredResourceArns.java @@ -10,7 +10,7 @@ import java.util.Optional; /** * What IAM asks AppConfig of the resources a request names: the application an id or a name finds, the configuration a - * session's token is on, and the tags of the application an ARN names. + * session's token is on, and the tags of the application or environment an ARN names. */ @ApplicationScoped public class AppConfigStoredResourceArns implements StoredResourceArns { diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigTagHandler.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigTagHandler.java index 92a88eec12..d88617c38b 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigTagHandler.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigTagHandler.java @@ -22,7 +22,7 @@ import java.util.Set; *
  • {@code arn:aws:appconfig:::extension/} *
  • {@code arn:aws:appconfig:::extensionassociation/} * - * Only application-level tags are actually stored; every other recognized ARN shape above is + * Application and environment tags are stored; every other recognized ARN shape above is * accepted (not rejected with a 400) but the tag call itself is a no-op - this satisfies callers * (e.g. Terraform's AWS provider) that read tags back after a write without erroring on a resource * type Floci doesn't yet persist tags for. @@ -52,6 +52,7 @@ public class AppConfigTagHandler implements TagHandler { ResourceRef ref = parseArn(arn); return switch (ref.type()) { case "application" -> service.getApplicationTags(ref.id()); + case "environment" -> service.getEnvironmentTags(ref.applicationId(), ref.id()); default -> Map.of(); }; } @@ -61,6 +62,8 @@ public class AppConfigTagHandler implements TagHandler { ResourceRef ref = parseArn(arn); if ("application".equals(ref.type())) { service.tagApplication(ref.id(), tags); + } else if ("environment".equals(ref.type())) { + service.tagEnvironment(ref.applicationId(), ref.id(), tags); } } @@ -69,10 +72,12 @@ public class AppConfigTagHandler implements TagHandler { ResourceRef ref = parseArn(arn); if ("application".equals(ref.type())) { service.untagApplication(ref.id(), tagKeys); + } else if ("environment".equals(ref.type())) { + service.untagEnvironment(ref.applicationId(), ref.id(), tagKeys); } } - private record ResourceRef(String type, String id) {} + private record ResourceRef(String type, String applicationId, String id) {} // The AppConfig resource types AWS documents as taggable that are NOT nested under // application/... (see e.g. the Tags property on AWS::AppConfig::DeploymentStrategy, @@ -91,16 +96,16 @@ public class AppConfigTagHandler implements TagHandler { } String[] parts = resource.split("/"); if (parts.length == 2 && TOP_LEVEL_TYPES.contains(parts[0])) { - return new ResourceRef(parts[0], parts[1]); + return new ResourceRef(parts[0], null, parts[1]); } if (parts.length >= 2 && "application".equals(parts[0])) { // application/ - if (parts.length == 2) return new ResourceRef("application", parts[1]); + if (parts.length == 2) return new ResourceRef("application", parts[1], parts[1]); // application//environment/ // application//configurationprofile/ - if (parts.length == 4) return new ResourceRef(parts[2], parts[3]); + if (parts.length == 4) return new ResourceRef(parts[2], parts[1], parts[3]); // application//environment//deployment/ - if (parts.length == 6) return new ResourceRef(parts[4], parts[5]); + if (parts.length == 6) return new ResourceRef(parts[4], parts[1], parts[5]); } throw new AwsException("BadRequestException", "Invalid resource ARN: " + arn, 400); } diff --git a/src/main/java/io/floci/aws/services/appconfig/model/Environment.java b/src/main/java/io/floci/aws/services/appconfig/model/Environment.java index 488acf8d04..ed7b2eb4da 100644 --- a/src/main/java/io/floci/aws/services/appconfig/model/Environment.java +++ b/src/main/java/io/floci/aws/services/appconfig/model/Environment.java @@ -5,7 +5,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.HashMap; import java.util.List; +import java.util.Map; @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @@ -24,6 +26,7 @@ public class Environment { @JsonProperty("Monitors") @JsonInclude(JsonInclude.Include.NON_NULL) private List monitors; + private Map tags = new HashMap<>(); public Environment() {} @@ -44,4 +47,7 @@ public class Environment { public List getMonitors() { return monitors; } public void setMonitors(List monitors) { this.monitors = monitors != null ? List.copyOf(monitors) : null; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags != null ? tags : new HashMap<>(); } } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java index 07816dda8e..14b897c0ca 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java @@ -35,8 +35,8 @@ import java.util.Set; * leaves the displaced one to the {@link ReplacementCleanup} record. Whether one changed is judged on * the resolved template values the entity was made from, as CloudFormation compares them. * - *

    Floci keeps AppConfig tags on applications only, so {@code Tags} on the other three types are - * accepted and not stored, as Floci's AppConfig TagResource treats them. So are a profile's + *

    This provisioner applies {@code Tags} to applications only: on the other three types they are + * accepted and not stored. So are a profile's * {@code KmsKeyIdentifier}, {@code RetrievalRoleArn} and {@code Validators}, and the * {@code DeletionProtectionCheck} of an environment or profile, which Floci's create operations do * not keep either. diff --git a/src/test/java/io/floci/aws/services/appconfig/AppConfigIntegrationTest.java b/src/test/java/io/floci/aws/services/appconfig/AppConfigIntegrationTest.java index b8cbe56202..b32c1219ce 100644 --- a/src/test/java/io/floci/aws/services/appconfig/AppConfigIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/appconfig/AppConfigIntegrationTest.java @@ -523,7 +523,7 @@ class AppConfigIntegrationTest { .body("Tags.team", equalTo("platform")); } - // ──────────────────────────── Tags on non-application resources (no-op) ──────────────────────────── + // ──────────────────────────── Tags on untagged environment and deployment ARNs ──────────────────────────── @Test @Order(22) void listTagsForEnvironmentArnReturnsEmpty() { @@ -547,10 +547,10 @@ class AppConfigIntegrationTest { // ──────────── Tags on top-level (non-application-nested) resource ARNs ──────────── // deploymentstrategy/extension/extensionassociation are real, taggable AppConfig resource - // types per the API - unlike environment/deployment above, their ARNs don't nest under + // types per the API. Unlike environment/deployment above, their ARNs don't nest under // application/..., so they need their own top-level branch in AppConfigTagHandler#parseArn. - // Regression coverage for that ARN-shape acceptance; no tag storage exists for these types - // yet (same no-op precedent as environment/deployment above), so only 200-not-400 is asserted. + // Regression coverage for that ARN-shape acceptance. Floci stores tags for applications and + // environments only, so tagging these is accepted and not stored, and only 200-not-400 is asserted. @Test @Order(24) void listTagsForDeploymentStrategyArnIsAcceptedNotRejected() { @@ -1282,6 +1282,138 @@ class AppConfigIntegrationTest { + "\"ConfigurationProfileIdentifier\":\"" + profile + "\"}"; } + // ──────────────────────────── Tags given at creation ──────────────────────────── + + @Test @Order(60) + void createApplicationAppliesTagsFromRequest() { + String taggedAppId = given() + .contentType(ContentType.JSON) + .body("{\"Name\": \"tagged-app\", \"Tags\": {\"Team\": \"a\"}}") + .when().post("/applications") + .then().statusCode(201) + .extract().path("Id"); + + given().urlEncodingEnabled(false) + .when().get(tagsPath("arn:aws:appconfig:us-east-1:000000000000:application/" + taggedAppId)) + .then() + .statusCode(200) + .body("Tags.Team", equalTo("a")); + } + + @Test @Order(61) + void createEnvironmentAppliesTagsFromRequest() { + String taggedEnvId = given() + .contentType(ContentType.JSON) + .body("{\"Name\": \"tagged-env\", \"Tags\": {\"Team\": \"a\"}}") + .when().post("/applications/" + appId + "/environments") + .then().statusCode(201) + .extract().path("Id"); + + given().urlEncodingEnabled(false) + .when().get(tagsPath("arn:aws:appconfig:us-east-1:000000000000:application/" + appId + + "/environment/" + taggedEnvId)) + .then() + .statusCode(200) + .body("Tags.Team", equalTo("a")); + } + + @Test @Order(62) + void tagResourceOnEnvironmentIsListedBack() { + String untaggedEnvId = given() + .contentType(ContentType.JSON) + .body("{\"Name\": \"env-tagged-later\"}") + .when().post("/applications/" + appId + "/environments") + .then().statusCode(201) + .extract().path("Id"); + String arn = "arn:aws:appconfig:us-east-1:000000000000:application/" + appId + "/environment/" + untaggedEnvId; + given().urlEncodingEnabled(false) + .contentType(ContentType.JSON) + .body("{\"Tags\": {\"Owner\": \"ops\"}}") + .when().post(tagsPath(arn)) + .then().statusCode(204); + + given().urlEncodingEnabled(false) + .when().get(tagsPath(arn)) + .then() + .statusCode(200) + .body("Tags.Owner", equalTo("ops")); + } + + @Test @Order(63) + void createApplicationRejectsTagsThatAreNotAMapOfStrings() { + for (String tags : new String[] {"{\"Team\": 123}", "[\"Team\"]"}) { + given() + .contentType(ContentType.JSON) + .body("{\"Name\": \"bad-tags-app\", \"Tags\": " + tags + "}") + .when().post("/applications") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + } + + @Test @Order(64) + void createEnvironmentRejectsTagsThatAreNotAMapOfStrings() { + given() + .contentType(ContentType.JSON) + .body("{\"Name\": \"bad-tags-env\", \"Tags\": {\"Team\": 123}}") + .when().post("/applications/" + appId + "/environments") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test @Order(65) + void applicationAnswersLeaveTagsOutWhileTheApplicationKeepsThem() { + String taggedAppId = given() + .contentType(ContentType.JSON) + .body("{\"Name\": \"wire-app\", \"Tags\": {\"Team\": \"a\"}}") + .when().post("/applications") + .then().statusCode(201) + .body("$", not(hasKey("tags"))) + .body("$", not(hasKey("Tags"))) + .extract().path("Id"); + + given().when().get("/applications/" + taggedAppId) + .then().statusCode(200) + .body("$", not(hasKey("tags"))); + given().contentType(ContentType.JSON).body("{\"Description\": \"changed\"}") + .when().patch("/applications/" + taggedAppId) + .then().statusCode(200) + .body("$", not(hasKey("tags"))); + given().when().get("/applications") + .then().statusCode(200) + .body("Items.find { it.Id == '" + taggedAppId + "' }", not(hasKey("tags"))); + given().urlEncodingEnabled(false) + .when().get(tagsPath("arn:aws:appconfig:us-east-1:000000000000:application/" + taggedAppId)) + .then().statusCode(200) + .body("Tags.Team", equalTo("a")); + } + + @Test @Order(66) + void environmentAnswersLeaveTagsOutWhileTheEnvironmentKeepsThem() { + String taggedEnvId = given() + .contentType(ContentType.JSON) + .body("{\"Name\": \"wire-env\", \"Tags\": {\"Team\": \"a\"}}") + .when().post("/applications/" + appId + "/environments") + .then().statusCode(201) + .body("$", not(hasKey("tags"))) + .body("$", not(hasKey("Tags"))) + .extract().path("Id"); + + given().when().get("/applications/" + appId + "/environments/" + taggedEnvId) + .then().statusCode(200) + .body("$", not(hasKey("tags"))); + given().when().get("/applications/" + appId + "/environments") + .then().statusCode(200) + .body("Items.find { it.Id == '" + taggedEnvId + "' }", not(hasKey("tags"))); + given().urlEncodingEnabled(false) + .when().get(tagsPath("arn:aws:appconfig:us-east-1:000000000000:application/" + appId + + "/environment/" + taggedEnvId)) + .then().statusCode(200) + .body("Tags.Team", equalTo("a")); + } + /** The modeled {@code /tags/{ResourceArn}} for an ARN, encoded as one path segment as an SDK sends it. */ private static String tagsPath(String arn) { return "/tags/" + URLEncoder.encode(arn, StandardCharsets.UTF_8); diff --git a/src/test/java/io/floci/aws/services/appconfig/AppConfigStoredTagsServiceTest.java b/src/test/java/io/floci/aws/services/appconfig/AppConfigStoredTagsServiceTest.java new file mode 100644 index 0000000000..71b65fced8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appconfig/AppConfigStoredTagsServiceTest.java @@ -0,0 +1,50 @@ +package io.floci.aws.services.appconfig; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AppConfigStoredTagsServiceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private AppConfigService service; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory(ACCOUNT)); + RegionResolver regions = mock(RegionResolver.class); + when(regions.getDefaultRegion()).thenReturn(REGION); + when(regions.getRegion()).thenReturn(REGION); + when(regions.getAccountId()).thenReturn(ACCOUNT); + service = new AppConfigService(storageFactory, regions); + } + + @Test + void storedTagsReadTheEnvironmentTheArnNamesInItsApplicationAccountAndRegion() { + String appId = service.createApplication(Map.of("Name", "app")).getId(); + String otherAppId = service.createApplication(Map.of("Name", "other")).getId(); + String envId = service.createEnvironment(appId, Map.of("Name", "env", "Tags", Map.of("Protected", "true"))) + .getId(); + String environment = "arn:aws:appconfig:" + REGION + ":" + ACCOUNT + ":application/" + appId + + "/environment/" + envId; + + assertEquals(Map.of("Protected", "true"), service.storedTags(environment)); + assertEquals(Map.of(), service.storedTags(environment.replace(appId, otherAppId))); + assertEquals(Map.of(), service.storedTags(environment.replace(ACCOUNT, "111111111111"))); + assertEquals(Map.of(), service.storedTags(environment.replace(REGION, "us-west-2"))); + } +}