diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java index 0218ae5a82..de295199b7 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java @@ -165,6 +165,7 @@ class CodeDeployTest { .deploymentGroupName("sdk-lambda-dg") .deploymentConfigName("CodeDeployDefault.LambdaAllAtOnce") .serviceRoleArn(TestFixtures.globalArn("iam", "000000000000", "role/codedeploy-role")) + .tags(Tag.builder().key("team").value("release").build()) .deploymentStyle(DeploymentStyle.builder() .deploymentType(DeploymentType.BLUE_GREEN) .deploymentOption(DeploymentOption.WITH_TRAFFIC_CONTROL) @@ -172,6 +173,9 @@ class CodeDeployTest { assertThat(resp.deploymentGroupId()).isNotBlank(); dgId = resp.deploymentGroupId(); + String arn = TestFixtures.arn("codedeploy", "000000000000", "deploymentgroup:sdk-lambda-app/sdk-lambda-dg"); + ListTagsForResourceResponse tags = codedeploy.listTagsForResource(r -> r.resourceArn(arn)); + assertThat(tags.tags()).contains(Tag.builder().key("team").value("release").build()); } @Test diff --git a/docs/services/iam.md b/docs/services/iam.md index 5361ba3e82..85510dfd04 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2352,9 +2352,9 @@ As with passed roles, an operation Floci does not serve is in the table too. - The tags are read from a top-level request member named `Tags`, `TagList`, `TagSpecifications` or the like that holds a tag list or map, as the Floci handler that applies them reads it, so the check sees the tags the resource gets. A JSON or CBOR body's member is read under its own name, and an - alarm's in CloudWatch's `PutMetricAlarm` and `PutCompositeAlarm` under `tags` too; a CodeDeploy - tag's key and value as `Key` and `Value`, or `key` and `value`, as its handler takes either, each as - text whatever it holds (a key `123` is the tag `123`). Query form + alarm's in CloudWatch's `PutMetricAlarm` and `PutCompositeAlarm` under `tags` too. CodeDeploy + accepts tag lists of objects with a textual `Key` and an optional textual `Value`; lowercase + member names and numeric keys are rejected by its handler. Query form parameters are read under the spelling the SDK sends, from 1 to the first number with no key, and under the further spellings the RDS, DocumentDB, Neptune, ElastiCache and Redshift handlers read. EC2's are read from every tag specification, under `TagSpecification` or `TagSpecifications`, as EC2 @@ -2364,8 +2364,9 @@ As with passed roles, an operation Floci does not serve is in the table too. tag list and an object's structures, a form's list under any spelling and every number, so none a handler applies goes unchecked. An object's members, read as a map's tags, are a set of their own beside its structures, so a member named as a structure's key does not hide the structure's tag - from a handler that iterates the object, as KMS's `CreateKey` does. CodeDeploy's handler iterates - its tags member whatever it holds, so an object's structures are its tags too. + from a handler that iterates the object, as KMS's `CreateKey` does. CodeDeploy rejects an + object-shaped tag collection at its handler boundary; the wider authorization scan is defensive + and does not make that shape valid CodeDeploy input. - CloudWatch Logs `CreateLogGroup`, which takes either of two tagging actions, is checked as described under CloudWatch Logs groups below. - Not read: an operation whose request carries no tags, which the Service Reference lists with a diff --git a/src/main/java/io/floci/aws/core/common/TagOnCreate.java b/src/main/java/io/floci/aws/core/common/TagOnCreate.java index 62ebccf1f1..ca971f867c 100644 --- a/src/main/java/io/floci/aws/core/common/TagOnCreate.java +++ b/src/main/java/io/floci/aws/core/common/TagOnCreate.java @@ -41,12 +41,6 @@ final class TagOnCreate { /** CloudWatch's handler reads an alarm's tags from {@code tags} when the body has no {@code Tags}. */ private static final Set LOWER_CASE_TAGS = Set.of("cloudwatch:PutMetricAlarm", "cloudwatch:PutCompositeAlarm"); - /** - * CodeDeploy's handler reads a tag as {@code Key} and {@code Value}, or as {@code key} and {@code value} when it - * has no {@code Key}. - */ - private static final Set EITHER_CASE_TAGS = Set.of("codedeploy"); - /** * The tags one resource gets, and the type of that resource where a tag specification names it, else null. */ @@ -105,8 +99,7 @@ final class TagOnCreate { otherSpellings.addAll(anySpellingInForm(form, member)); } else if (body != null && body.isObject()) { Map> byType = new LinkedHashMap<>(); - collect(topLevel(body, operation, member.steps().getFirst().name()), member, - EITHER_CASE_TAGS.contains(operation.substring(0, operation.indexOf(':'))), 0, null, byType); + collect(topLevel(body, operation, member.steps().getFirst().name()), member, 0, null, byType); byType.forEach((type, tags) -> add(sets, type, tags)); otherSpellings.addAll(anySpellingInBody(body, member)); } @@ -430,23 +423,14 @@ final class TagOnCreate { * The tags a body carries at the member, by the resource type of the tag specification they are in, null * outside one. */ - private static void collect(JsonNode value, TagOnCreateMembers.Member member, boolean eitherCase, int index, + private static void collect(JsonNode value, TagOnCreateMembers.Member member, int index, String type, Map> byType) { List steps = member.steps(); PassedRoleMembers.Step step = steps.get(index); if (index == steps.size() - 1) { Map tags = byType.computeIfAbsent(type, ignored -> new LinkedHashMap<>()); - // CodeDeployJsonHandler iterates the member whatever it holds, which for an object is its values. - if (step.into() == PassedRoleMembers.Into.LIST && value != null - && (value.isArray() || eitherCase && value.isObject())) { + if (step.into() == PassedRoleMembers.Into.LIST && value != null && value.isArray()) { for (JsonNode tag : value) { - if (eitherCase) { - // As CodeDeployJsonHandler reads it: as text whatever it holds, a missing key an empty one. - boolean lower = !tag.has(member.key()); - tags.put(tag.path(lower ? member.key().toLowerCase(Locale.ROOT) : member.key()).asText(), - tag.path(lower ? member.value().toLowerCase(Locale.ROOT) : member.value()).asText()); - continue; - } JsonNode key = tag.get(member.key()); if (key != null && key.isValueNode() && !key.isNull()) { tags.put(key.asText(), text(tag.get(member.value()))); @@ -463,13 +447,13 @@ final class TagOnCreate { } String next = steps.get(index + 1).name(); switch (step.into()) { - case NONE -> collect(value.get(next), member, eitherCase, index + 1, type, byType); - case KEY -> collect(value.path(step.key()).get(next), member, eitherCase, index + 1, type, byType); + case NONE -> collect(value.get(next), member, index + 1, type, byType); + case KEY -> collect(value.path(step.key()).get(next), member, index + 1, type, byType); case LIST, MAP -> { if (step.into() == PassedRoleMembers.Into.LIST ? value.isArray() : value.isObject()) { for (JsonNode element : value) { JsonNode kind = member.resourceType() == null ? null : element.get(member.resourceType()); - collect(element.get(next), member, eitherCase, index + 1, + collect(element.get(next), member, index + 1, kind != null && kind.isTextual() ? kind.asText() : type, byType); } } diff --git a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployJsonHandler.java b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployJsonHandler.java index 433292332b..35bafc8f84 100644 --- a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployJsonHandler.java +++ b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployJsonHandler.java @@ -18,10 +18,13 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; @ApplicationScoped public class CodeDeployJsonHandler { + private static final Set TAG_FILTER_TYPES = Set.of("KEY_ONLY", "VALUE_ONLY", "KEY_AND_VALUE"); + private final CodeDeployService service; private final ObjectMapper mapper; @@ -75,7 +78,7 @@ public class CodeDeployJsonHandler { private Response createApplication(JsonNode req, String region) { String name = req.path("applicationName").asText(null); String computePlatform = req.has("computePlatform") ? req.path("computePlatform").asText() : null; - List> tags = parseTags(req, "tags"); + List> tags = parseOptionalTags(req, "tags"); Application app = service.createApplication(region, name, computePlatform, tags); return Response.ok(Map.of("applicationId", app.getApplicationId())).build(); } @@ -123,8 +126,9 @@ public class CodeDeployJsonHandler { String deploymentConfigName = req.has("deploymentConfigName") ? req.path("deploymentConfigName").asText() : null; String serviceRoleArn = req.has("serviceRoleArn") ? req.path("serviceRoleArn").asText() : null; Map fields = extractGroupFields(req); + List> tags = parseOptionalTags(req, "tags"); DeploymentGroup group = service.createDeploymentGroup(region, appName, groupName, - deploymentConfigName, serviceRoleArn, fields); + deploymentConfigName, serviceRoleArn, fields, tags); return Response.ok(Map.of("deploymentGroupId", group.getDeploymentGroupId())).build(); } @@ -313,13 +317,13 @@ public class CodeDeployJsonHandler { private Response listOnPremisesInstances(JsonNode req, String region) { String registrationStatus = req.has("registrationStatus") ? req.path("registrationStatus").asText() : null; - List> tagFilters = parseTags(req, "tagFilters"); + List> tagFilters = parseTagFilters(req); List names = service.listOnPremisesInstances(region, registrationStatus, tagFilters); return Response.ok(Map.of("instanceNames", names)).build(); } private Response addTagsToOnPremisesInstances(JsonNode req, String region) { - List> tags = parseTags(req, "tags"); + List> tags = parseTags(req, "tags", "InvalidTagException"); List names = new ArrayList<>(); req.path("instanceNames").forEach(n -> names.add(n.asText())); service.addTagsToOnPremisesInstances(region, names, tags); @@ -327,7 +331,7 @@ public class CodeDeployJsonHandler { } private Response removeTagsFromOnPremisesInstances(JsonNode req, String region) { - List> tags = parseTags(req, "tags"); + List> tags = parseTags(req, "tags", "InvalidTagException"); List names = new ArrayList<>(); req.path("instanceNames").forEach(n -> names.add(n.asText())); service.removeTagsFromOnPremisesInstances(region, names, tags); @@ -348,22 +352,58 @@ public class CodeDeployJsonHandler { return fields; } - private List> parseTags(JsonNode req, String fieldName) { - if (!req.has(fieldName) || req.get(fieldName).isNull()) { + private List> parseTagFilters(JsonNode req) { + if (!req.has("tagFilters") || req.get("tagFilters").isNull()) { return List.of(); } + JsonNode filterList = req.get("tagFilters"); + if (!filterList.isArray()) { + throw new AwsException("InvalidTagFilterException", "The specified tag filters are not valid.", 400); + } List> result = new ArrayList<>(); - for (JsonNode tag : req.get(fieldName)) { - Map t = new HashMap<>(); - // Support both capitalizations (Tags uses Key/Value, tags uses key/value) - if (tag.has("Key")) { - t.put("Key", tag.path("Key").asText()); - t.put("Value", tag.path("Value").asText()); - } else { - t.put("Key", tag.path("key").asText()); - t.put("Value", tag.path("value").asText()); + for (JsonNode filter : filterList) { + if (!filter.isObject()) { + throw new AwsException("InvalidTagFilterException", "The specified tag filters are not valid.", 400); } - result.add(t); + Map values = new HashMap<>(); + for (String member : List.of("Key", "Value", "Type")) { + if (filter.hasNonNull(member)) { + JsonNode value = filter.get(member); + if (!value.isTextual() + || (member.equals("Type") && !TAG_FILTER_TYPES.contains(value.asText()))) { + throw new AwsException("InvalidTagFilterException", "The specified tag filters are not valid.", 400); + } + values.put(member, value.asText()); + } + } + result.add(values); + } + return result; + } + + private List> parseTags(JsonNode req, String fieldName) { + return parseTags(req, fieldName, "InvalidTagsToAddException"); + } + + private List> parseOptionalTags(JsonNode req, String fieldName) { + return req.path(fieldName).isNull() ? List.of() : parseTags(req, fieldName); + } + + private List> parseTags(JsonNode req, String fieldName, String invalidType) { + if (!req.has(fieldName)) { + return List.of(); + } + JsonNode tagList = req.get(fieldName); + if (!tagList.isArray()) { + throw new AwsException(invalidType, "The specified tags are not valid.", 400); + } + List> result = new ArrayList<>(); + for (JsonNode tag : tagList) { + if (!tag.isObject() || !tag.path("Key").isTextual() + || tag.has("Value") && !tag.get("Value").isTextual()) { + throw new AwsException(invalidType, "The specified tags are not valid.", 400); + } + result.add(Map.of("Key", tag.get("Key").asText(), "Value", tag.path("Value").asText(""))); } return result; } diff --git a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java index bc892ff7ba..e0f56dfd00 100644 --- a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java +++ b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java @@ -424,7 +424,7 @@ public class CodeDeployService { public DeploymentGroup createDeploymentGroup(String region, String appName, String groupName, String deploymentConfigName, String serviceRoleArn, - Map fields) { + Map fields, List> tags) { getApplication(region, appName); Map> appGroups = deploymentGroupsFor(region); Map groupStore = appGroups.computeIfAbsent(appName, a -> new ConcurrentHashMap<>()); @@ -442,6 +442,9 @@ public class CodeDeployService { applyGroupFields(group, fields); groupStore.put(groupName, group); persistRegion(deploymentGroups, region); + if (tags != null && !tags.isEmpty()) { + applyTags(deploymentGroupArn(region, appName, groupName), tags); + } return group; } @@ -465,14 +468,25 @@ public class CodeDeployService { Map groupStore = deploymentGroupsFor(region) .computeIfAbsent(appName, a -> new ConcurrentHashMap<>()); + if (newGroupName != null && !newGroupName.equals(currentGroupName) + && groupStore.containsKey(newGroupName)) { + throw new AwsException("DeploymentGroupAlreadyExistsException", + "Deployment group already exists: " + newGroupName, 400); + } + if (deploymentConfigName != null) { group.setDeploymentConfigName(deploymentConfigName); } if (serviceRoleArn != null) { group.setServiceRoleArn(serviceRoleArn); } applyGroupFields(group, fields); if (newGroupName != null && !newGroupName.equals(currentGroupName)) { + String oldArn = deploymentGroupArn(region, appName, currentGroupName); groupStore.remove(currentGroupName); group.setDeploymentGroupName(newGroupName); groupStore.put(newGroupName, group); + Map groupTags = tags.remove(oldArn); + if (groupTags != null) { + tags.put(deploymentGroupArn(region, appName, newGroupName), groupTags); + } } persistRegion(deploymentGroups, region); return group; @@ -486,6 +500,7 @@ public class CodeDeployService { throw new AwsException("DeploymentGroupDoesNotExistException", "Deployment group does not exist: " + groupName, 400); } + tags.remove(deploymentGroupArn(region, appName, groupName)); persistRegion(deploymentGroups, region); } @@ -1122,10 +1137,21 @@ public class CodeDeployService { for (Map filter : filters) { String key = filter.get("Key"); String value = filter.get("Value"); - if (key == null) { continue; } - boolean found = instanceTags.stream() - .anyMatch(t -> key.equals(t.get("Key")) - && (value == null || value.equals(t.get("Value")))); + String type = filter.get("Type"); + if (key == null && type == null) { continue; } + boolean found = instanceTags.stream().anyMatch(tag -> { + if ("VALUE_ONLY".equals(type)) { + return value != null && value.equals(tag.get("Value")); + } + if ("KEY_ONLY".equals(type)) { + return key != null && key.equals(tag.get("Key")); + } + if ("KEY_AND_VALUE".equals(type) && value == null) { + return false; + } + return key != null && key.equals(tag.get("Key")) + && (value == null || value.equals(tag.get("Value"))); + }); if (!found) { return false; } } return true; diff --git a/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java b/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java index 3a3864c890..6a1b523d19 100644 --- a/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java +++ b/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java @@ -73,38 +73,34 @@ class TagOnCreateTest { + "&TagSpecification.item.1.Tag.1.Key=team")).orElseThrow().otherSpellings()); } - /** - * CodeDeploy's handler reads a tag as {@code Key} and {@code Value}, or as {@code key} and {@code value}, so both - * are the tags it applies; under any other case a tag is checked on the tagging action only. - */ + /** CodeDeploy reads its modeled {@code Key}/{@code Value} tags; other spellings stay on the tagging check. */ @Test - void aBodysTagsAreReadInTheCasesTheirHandlerReadsAndCheckedOnTheTaggingActionInAnyOther() { - for (String tag : List.of("{\"key\":\"team\",\"value\":\"red\"}", "{\"Key\":\"team\",\"Value\":\"red\"}")) { - Tagging tagging = TagOnCreate.of("codedeploy:CreateApplication", json( - "{\"applicationName\":\"demo\",\"tags\":[" + tag + "]}")).orElseThrow(); - assertEquals(List.of(set(Map.of("team", "red"))), tagging.sets(), tag); - assertEquals(List.of(), tagging.otherSpellings(), tag); + void aBodysTagsAreReadInTheModeledCaseAndCheckedOnTheTaggingActionInAnyOther() { + for (String operation : List.of("CreateApplication", "CreateDeploymentGroup")) { + Tagging tagging = TagOnCreate.of("codedeploy:" + operation, json( + "{\"applicationName\":\"demo\",\"tags\":[{\"Key\":\"team\",\"Value\":\"red\"}]}")).orElseThrow(); + assertEquals(List.of(set(Map.of("team", "red"))), tagging.sets(), operation); + assertEquals(List.of(), tagging.otherSpellings(), operation); } - // Under any other case the handler reads neither, and keeps an empty tag; the tagging action is checked for both. + Tagging lower = TagOnCreate.of("codedeploy:CreateApplication", json( + "{\"applicationName\":\"demo\",\"tags\":[{\"key\":\"team\",\"value\":\"red\"}]}")).orElseThrow(); + assertEquals(List.of(), lower.sets()); + assertEquals(List.of(set(Map.of("team", "red"))), lower.otherSpellings()); Tagging upper = TagOnCreate.of("codedeploy:CreateApplication", json( "{\"applicationName\":\"demo\",\"tags\":[{\"KEY\":\"team\",\"VALUE\":\"red\"}]}")).orElseThrow(); - assertEquals(List.of(set(Map.of("", ""))), upper.sets()); - assertEquals(List.of(set(Map.of("", "")), set(Map.of("team", "red"))), upper.checked()); - // Only CodeDeploy's handler reads a lowercase key where the SDK sends Key. + assertEquals(List.of(), upper.sets()); + assertEquals(List.of(set(Map.of("team", "red"))), upper.otherSpellings()); assertEquals(List.of(), sets("dynamodb:CreateTable", json( "{\"TableName\":\"t\",\"Tags\":[{\"key\":\"team\",\"value\":\"red\"}]}"))); } - /** - * CodeDeploy's handler iterates its tags member whatever it holds, so an object's values are tags too; a deny on - * one holds on the own action and the tagging action alike. - */ + /** A non-list CodeDeploy tags member is not applied, though its contents remain visible to the safety check. */ @Test - void anObjectsValuesAreTagsWhereTheHandlerIteratesIt() { + void anObjectsValuesAreOnlyOtherSpellingsForCodeDeploy() { Tagging object = TagOnCreate.of("codedeploy:CreateApplication", json("{\"applicationName\":\"demo\"," + "\"tags\":{\"0\":{\"key\":\"team\",\"value\":\"red\"}}}")).orElseThrow(); - assertEquals(List.of(set(Map.of("team", "red"))), object.sets()); - assertEquals(List.of("red"), TagOnCreate.requestTagContexts(object).getFirst().get("aws:RequestTag/team")); + assertEquals(List.of(), object.sets()); + assertTrue(object.otherSpellings().contains(set(Map.of("team", "red")))); // Elsewhere it is checked on the tagging action and with the own action, beside no tags. Tagging elsewhere = TagOnCreate.of("dynamodb:CreateTable", json("{\"TableName\":\"t\"," + "\"Tags\":{\"0\":{\"Key\":\"team\",\"Value\":\"red\"}}}")).orElseThrow(); @@ -133,16 +129,9 @@ class TagOnCreateTest { "{\"Tags\":{\"team\":\"red\"}}")).orElseThrow().otherSpellings()); } - /** - * CodeDeploy's handler reads a tag's key and value as text whatever they hold, a missing key as an empty one, - * and so does the check; other handlers' keys are read as text when they are a number or a flag too. - */ + /** Some handlers read non-string tag fields as text, and the check follows their current behavior. */ @Test void aTagKeyThatIsNoStringIsReadAsText() { - assertEquals(List.of(set(Map.of("123", "red"))), sets("codedeploy:CreateApplication", json( - "{\"applicationName\":\"demo\",\"tags\":[{\"key\":123,\"value\":\"red\"}]}"))); - assertEquals(List.of(set(Map.of("", "red"))), sets("codedeploy:CreateApplication", json( - "{\"applicationName\":\"demo\",\"tags\":[{\"value\":\"red\"}]}"))); assertEquals(List.of(set(Map.of("true", "1"))), sets("dynamodb:CreateTable", json( "{\"TableName\":\"t\",\"Tags\":[{\"Key\":true,\"Value\":1}]}"))); // Under any other spelling, every element of a tag list is checked on the tagging action. diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployHookTimeoutTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployHookTimeoutTest.java index a602e13ff5..6d397dcc79 100644 --- a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployHookTimeoutTest.java +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployHookTimeoutTest.java @@ -86,7 +86,7 @@ class CodeDeployHookTimeoutTest { ssm, mock(Ec2Service.class), new ObjectMapper(), new RegionResolver(region, "000000000000"), null); service.createApplication(region, "app", "Server", null); - service.createDeploymentGroup(region, "app", "group", null, "role", null); + service.createDeploymentGroup(region, "app", "group", null, "role", null, null); return service; } } diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServicePersistenceTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServicePersistenceTest.java index e8a1cc46a9..76ae9991bf 100644 --- a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServicePersistenceTest.java +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServicePersistenceTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.codedeploy; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +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; @@ -43,7 +44,8 @@ class CodeDeployServicePersistenceTest { first.createApplication(REGION, "web-app", "Server", List.of(Map.of("Key", "team", "Value", "platform"))); first.createDeploymentGroup(REGION, "web-app", "prod-group", - "CodeDeployDefault.OneAtATime", "arn:aws:iam::000000000000:role/cd", null); + "CodeDeployDefault.OneAtATime", "arn:aws:iam::000000000000:role/cd", null, + List.of(Map.of("Key", "owner", "Value", "release"))); first.createDeploymentConfig(REGION, "custom-cfg", Map.of("type", "HOST_COUNT", "value", 1), "Server", null, null); first.registerOnPremisesInstance(REGION, "onprem-1", @@ -67,6 +69,10 @@ class CodeDeployServicePersistenceTest { .stream().collect(Collectors.toMap(t -> t.get("Key"), t -> t.get("Value"))); assertEquals("prod", appTags.get("env")); // tagResource assertEquals("platform", appTags.get("team")); // createApplication tags + Map groupTags = reloaded.listTagsForResource( + first.deploymentGroupArn(REGION, "web-app", "prod-group")).stream() + .collect(Collectors.toMap(t -> t.get("Key"), t -> t.get("Value"))); + assertEquals("release", groupTags.get("owner")); } @Test @@ -76,8 +82,8 @@ class CodeDeployServicePersistenceTest { CodeDeployService first = serviceWithStorage(storage); first.createApplication(REGION, "keep-app", "Server", null); first.createApplication(REGION, "drop-app", "Server", null); - first.createDeploymentGroup(REGION, "keep-app", "g1", null, "arn:r", null); - first.createDeploymentGroup(REGION, "keep-app", "g2", null, "arn:r", null); + first.createDeploymentGroup(REGION, "keep-app", "g1", null, "arn:r", null, null); + first.createDeploymentGroup(REGION, "keep-app", "g2", null, "arn:r", null, null); first.deleteApplication(REGION, "drop-app"); first.deleteDeploymentGroup(REGION, "keep-app", "g2"); String arn = first.applicationArn(REGION, "keep-app"); @@ -96,6 +102,66 @@ class CodeDeployServicePersistenceTest { assertTrue(!tags.containsKey("team"), "untagged key must not reappear after restart"); } + @Test + void taggedDeploymentGroupKeepsTagsWhenRenamed() { + SharedStorageFactory storage = new SharedStorageFactory(); + CodeDeployService service = serviceWithStorage(storage); + service.createApplication(REGION, "rename-app", "Server", null); + service.createDeploymentGroup(REGION, "rename-app", "old-group", null, "arn:r", null, null); + String originalArn = service.deploymentGroupArn(REGION, "rename-app", "old-group"); + service.tagResource(originalArn, List.of(Map.of("Key", "team", "Value", "red"))); + + service.updateDeploymentGroup(REGION, "rename-app", "old-group", "new-group", null, null, null); + + CodeDeployService reloaded = serviceWithStorage(storage); + String renamedArn = reloaded.deploymentGroupArn(REGION, "rename-app", "new-group"); + assertEquals(List.of(Map.of("Key", "team", "Value", "red")), reloaded.listTagsForResource(renamedArn)); + assertEquals(List.of(), reloaded.listTagsForResource(originalArn)); + } + + @Test + void renamingDeploymentGroupToExistingNamePreservesBothGroupsAndTags() { + SharedStorageFactory storage = new SharedStorageFactory(); + CodeDeployService service = serviceWithStorage(storage); + service.createApplication(REGION, "rename-conflict-app", "Server", null); + DeploymentGroup source = service.createDeploymentGroup(REGION, "rename-conflict-app", "source", + null, "arn:source-role", null, List.of(Map.of("Key", "team", "Value", "red"))); + DeploymentGroup destination = service.createDeploymentGroup(REGION, "rename-conflict-app", "destination", + null, "arn:destination-role", null, List.of(Map.of("Key", "team", "Value", "blue"))); + String sourceArn = service.deploymentGroupArn(REGION, "rename-conflict-app", "source"); + String destinationArn = service.deploymentGroupArn(REGION, "rename-conflict-app", "destination"); + + AwsException error = assertThrows(AwsException.class, () -> service.updateDeploymentGroup( + REGION, "rename-conflict-app", "source", "destination", null, "arn:changed-role", null)); + + assertEquals("DeploymentGroupAlreadyExistsException", error.getErrorCode()); + CodeDeployService reloaded = serviceWithStorage(storage); + assertEquals(source.getDeploymentGroupId(), + reloaded.getDeploymentGroup(REGION, "rename-conflict-app", "source").getDeploymentGroupId()); + assertEquals(destination.getDeploymentGroupId(), + reloaded.getDeploymentGroup(REGION, "rename-conflict-app", "destination").getDeploymentGroupId()); + assertEquals("arn:source-role", + reloaded.getDeploymentGroup(REGION, "rename-conflict-app", "source").getServiceRoleArn()); + assertEquals(List.of(Map.of("Key", "team", "Value", "red")), reloaded.listTagsForResource(sourceArn)); + assertEquals(List.of(Map.of("Key", "team", "Value", "blue")), reloaded.listTagsForResource(destinationArn)); + } + + @Test + void deletedDeploymentGroupDoesNotLeaveTagsForRecreatedName() { + SharedStorageFactory storage = new SharedStorageFactory(); + CodeDeployService service = serviceWithStorage(storage); + service.createApplication(REGION, "recreate-app", "Server", null); + service.createDeploymentGroup(REGION, "recreate-app", "group", null, "arn:r", null, null); + String arn = service.deploymentGroupArn(REGION, "recreate-app", "group"); + service.tagResource(arn, List.of(Map.of("Key", "team", "Value", "red"))); + + service.deleteDeploymentGroup(REGION, "recreate-app", "group"); + service.createDeploymentGroup(REGION, "recreate-app", "group", null, "arn:r", null, null); + + CodeDeployService reloaded = serviceWithStorage(storage); + assertEquals(List.of(), reloaded.listTagsForResource(arn)); + } + private static CodeDeployService serviceWithStorage(StorageFactory storage) { CodeDeployService service = new CodeDeployService( mock(LambdaService.class), mock(EcsService.class), mock(ElbV2Service.class), diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java index 8cfd5833ad..64f05ac51f 100644 --- a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java @@ -20,6 +20,7 @@ import java.time.Clock; import java.time.Duration; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -66,6 +67,51 @@ class CodeDeployServiceTest { return svc; } + @Test + void onPremisesTagFilterTypesMatchOnlyRequestedTags() { + for (String name : List.of("red-team", "blue-team", "red-env", "untagged")) { + service.registerOnPremisesInstance(REGION, name, null, null); + } + service.addTagsToOnPremisesInstances(REGION, List.of("red-team"), + List.of(Map.of("Key", "team", "Value", "red"))); + service.addTagsToOnPremisesInstances(REGION, List.of("blue-team"), + List.of(Map.of("Key", "team", "Value", "blue"))); + service.addTagsToOnPremisesInstances(REGION, List.of("red-env"), + List.of(Map.of("Key", "env", "Value", "red"))); + + assertEquals(Set.of("red-team", "red-env"), Set.copyOf(service.listOnPremisesInstances(REGION, null, + List.of(Map.of("Value", "red", "Type", "VALUE_ONLY"))))); + assertEquals(Set.of("red-team", "red-env"), Set.copyOf(service.listOnPremisesInstances(REGION, null, + List.of(Map.of("Key", "ignored", "Value", "red", "Type", "VALUE_ONLY"))))); + assertEquals(Set.of("red-team", "blue-team"), Set.copyOf(service.listOnPremisesInstances(REGION, null, + List.of(Map.of("Key", "team", "Value", "ignored", "Type", "KEY_ONLY"))))); + assertEquals(List.of("red-team"), service.listOnPremisesInstances(REGION, null, + List.of(Map.of("Key", "team", "Value", "red", "Type", "KEY_AND_VALUE")))); + assertEquals(List.of(), service.listOnPremisesInstances(REGION, null, + List.of(Map.of("Key", "team", "Type", "KEY_AND_VALUE")))); + assertEquals(List.of(), service.listOnPremisesInstances(REGION, null, + List.of(Map.of("Value", "red", "Type", "KEY_AND_VALUE")))); + assertEquals(List.of("red-team"), service.listOnPremisesInstances(REGION, null, + List.of(Map.of("Key", "team", "Value", "red")))); + } + + @Test + void keylessUntypedOnPremisesFilterStillSelectsRegisteredDeploymentTargets() { + service.registerOnPremisesInstance(REGION, "matching-onprem", null, null); + service.registerOnPremisesInstance(REGION, "untagged-onprem", null, null); + service.addTagsToOnPremisesInstances(REGION, List.of("matching-onprem"), + List.of(Map.of("Key", "team", "Value", "red"))); + service.createApplication(REGION, "keyless-filter-app", "Server", null); + service.createDeploymentGroup(REGION, "keyless-filter-app", "group", null, ROLE_ARN, + Map.of("onPremisesInstanceTagFilters", List.of(Map.of("Value", "red"))), null); + + String deploymentId = service.createDeployment(REGION, "keyless-filter-app", "group", null, + Map.of("appSpecContent", Map.of("content", "os: linux")), null); + + assertEquals(Set.of("matching-onprem", "untagged-onprem"), + Set.copyOf(service.listDeploymentTargets(REGION, deploymentId))); + } + // ---- Server platform (SSM) hooks --------------------------------------------------- @Test @@ -223,7 +269,7 @@ class CodeDeployServiceTest { CodeDeployService shortTimeoutService = newService(Duration.ofSeconds(1)); shortTimeoutService.createApplication(REGION, "app-hook-timeout", "Lambda", null); shortTimeoutService.createDeploymentGroup(REGION, "app-hook-timeout", "group-hook-timeout", - "CodeDeployDefault.LambdaAllAtOnce", ROLE_ARN, null); + "CodeDeployDefault.LambdaAllAtOnce", ROLE_ARN, null, null); InvokeResult cleanInvoke = new InvokeResult(200, null, new byte[0], null, "req-3"); when(lambdaService.invoke(eq(REGION), eq("beforeHook"), any(byte[].class), eq(InvocationType.RequestResponse))) .thenReturn(cleanInvoke); @@ -328,7 +374,7 @@ class CodeDeployServiceTest { private String createServerDeployment(CodeDeployService target, String appName, String groupName, int timeoutSeconds) { target.createApplication(REGION, appName, "Server", null); - target.createDeploymentGroup(REGION, appName, groupName, "CodeDeployDefault.AllAtOnce", ROLE_ARN, null); + target.createDeploymentGroup(REGION, appName, groupName, "CodeDeployDefault.AllAtOnce", ROLE_ARN, null, null); String appSpec = """ os: linux hooks: @@ -344,7 +390,7 @@ class CodeDeployServiceTest { private void createLambdaAppAndGroup(String appName, String groupName) { service.createApplication(REGION, appName, "Lambda", null); service.createDeploymentGroup(REGION, appName, groupName, - "CodeDeployDefault.LambdaAllAtOnce", ROLE_ARN, null); + "CodeDeployDefault.LambdaAllAtOnce", ROLE_ARN, null, null); } private String createLambdaDeployment(String appName, String groupName, String beforeHook, String afterHook) { diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployTagFilterHandlerTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployTagFilterHandlerTest.java new file mode 100644 index 0000000000..c64b474cdf --- /dev/null +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployTagFilterHandlerTest.java @@ -0,0 +1,58 @@ +package io.floci.aws.services.codedeploy; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class CodeDeployTagFilterHandlerTest { + + @Test + void optionalTagFilterMembersRemainAbsent() throws Exception { + CodeDeployService service = mock(CodeDeployService.class); + when(service.listOnPremisesInstances(eq("us-east-1"), isNull(), anyList())).thenReturn(List.of()); + ObjectMapper mapper = new ObjectMapper(); + CodeDeployJsonHandler handler = new CodeDeployJsonHandler(service, mapper); + + handler.handle("ListOnPremisesInstances", mapper.readTree(""" + {"tagFilters":[{"Key":"team"},{"Value":"red"},{"Type":"KEY_ONLY"}]} + """), "us-east-1"); + + verify(service).listOnPremisesInstances(eq("us-east-1"), isNull(), + eq(List.of(Map.of("Key", "team"), Map.of("Value", "red"), Map.of("Type", "KEY_ONLY")))); + } + + @Test + void explicitNullTagFiltersAreTreatedAsAbsent() throws Exception { + CodeDeployService service = mock(CodeDeployService.class); + when(service.listOnPremisesInstances(eq("us-east-1"), isNull(), anyList())).thenReturn(List.of()); + ObjectMapper mapper = new ObjectMapper(); + CodeDeployJsonHandler handler = new CodeDeployJsonHandler(service, mapper); + + handler.handle("ListOnPremisesInstances", mapper.readTree("{\"tagFilters\":null}"), "us-east-1"); + + verify(service).listOnPremisesInstances(eq("us-east-1"), isNull(), eq(List.of())); + } + + @Test + void nullTagFilterMembersAreTreatedAsAbsent() throws Exception { + CodeDeployService service = mock(CodeDeployService.class); + when(service.listOnPremisesInstances(eq("us-east-1"), isNull(), anyList())).thenReturn(List.of()); + ObjectMapper mapper = new ObjectMapper(); + CodeDeployJsonHandler handler = new CodeDeployJsonHandler(service, mapper); + + handler.handle("ListOnPremisesInstances", mapper.readTree(""" + {"tagFilters":[{"Key":null,"Value":null,"Type":null}]} + """), "us-east-1"); + + verify(service).listOnPremisesInstances(eq("us-east-1"), isNull(), eq(List.of(Map.of()))); + } +} diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployTagsIntegrationTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployTagsIntegrationTest.java new file mode 100644 index 0000000000..29b6d8b6e9 --- /dev/null +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployTagsIntegrationTest.java @@ -0,0 +1,300 @@ +package io.floci.aws.services.codedeploy; + +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; + +@QuarkusTest +class CodeDeployTagsIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createDeploymentGroupStoresItsTags() { + String application = "tag-app-7949-" + UUID.randomUUID(); + String group = "tag-dg-7949-" + UUID.randomUUID(); + String groupArn = "arn:aws:codedeploy:us-east-1:000000000000:deploymentgroup:" + + application + "/" + group; + deleteApplicationLater(application); + given() + .header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + "\"}") + .when() + .post("/") + .then() + .statusCode(200); + + deleteDeploymentGroupLater(application, group); + untagLater(groupArn); + given() + .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeploymentGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "applicationName": "%s", + "deploymentGroupName": "%s", + "serviceRoleArn": "arn:aws:iam::000000000000:role/codedeploy", + "tags": [{"Key": "team", "Value": "red"}] + } + """.formatted(application, group)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.ListTagsForResource") + .contentType(CONTENT_TYPE) + .body("{\"ResourceArn\":\"" + groupArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("team")) + .body("Tags[0].Value", equalTo("red")); + } + + @Test + void explicitNullTagsRemainOptional() { + String application = "null-tag-app-7949-" + UUID.randomUUID(); + String group = "null-tag-group-7949-" + UUID.randomUUID(); + deleteApplicationLater(application); + deleteDeploymentGroupLater(application, group); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + "\",\"tags\":null}") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeploymentGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "applicationName": "%s", + "deploymentGroupName": "%s", + "serviceRoleArn": "arn:aws:iam::000000000000:role/codedeploy", + "tags": null + } + """.formatted(application, group)) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + void createApplicationRejectsUnmodeledTagShapes() { + String[] invalidTags = { + "[{\"key\":\"team\",\"value\":\"red\"}]", + "[{\"Key\":123,\"Value\":\"red\"}]", + "[{\"Key\":\"team\",\"Value\":true}]", + "{\"0\":{\"Key\":\"team\",\"Value\":\"red\"}}" + }; + for (int i = 0; i < invalidTags.length; i++) { + String application = "invalid-tag-app-7949-" + UUID.randomUUID(); + String applicationArn = "arn:aws:codedeploy:us-east-1:000000000000:application:" + application; + deleteApplicationLater(application); + untagLater(applicationArn); + given() + .header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + "\",\"tags\":" + invalidTags[i] + "}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidTagsToAddException")); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.GetApplication") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + "\"}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ApplicationDoesNotExistException")); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.ListTagsForResource") + .contentType(CONTENT_TYPE) + .body("{\"ResourceArn\":\"" + applicationArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Tags", hasSize(0)); + } + } + + @Test + void createDeploymentGroupAndTagResourceRejectUnmodeledTagShapes() { + String application = "invalid-tag-group-app-7949-" + UUID.randomUUID(); + String group = "invalid-tag-group-7949-" + UUID.randomUUID(); + String applicationArn = "arn:aws:codedeploy:us-east-1:000000000000:application:" + application; + String groupArn = "arn:aws:codedeploy:us-east-1:000000000000:deploymentgroup:" + + application + "/" + group; + deleteApplicationLater(application); + given() + .header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + "\"}") + .when() + .post("/") + .then() + .statusCode(200); + + deleteDeploymentGroupLater(application, group); + given() + .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeploymentGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "applicationName": "%s", + "deploymentGroupName": "%s", + "serviceRoleArn": "arn:aws:iam::000000000000:role/codedeploy", + "tags": {"0": {"Key": "team", "Value": "red"}} + } + """.formatted(application, group)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidTagsToAddException")); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.GetDeploymentGroup") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + + "\",\"deploymentGroupName\":\"" + group + "\"}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("DeploymentGroupDoesNotExistException")); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.ListTagsForResource") + .contentType(CONTENT_TYPE) + .body("{\"ResourceArn\":\"" + groupArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Tags", hasSize(0)); + + untagLater(applicationArn); + given() + .header("X-Amz-Target", "CodeDeploy_20141006.TagResource") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResourceArn": "%s", + "Tags": [{"key": "team", "value": "red"}] + } + """.formatted(applicationArn)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidTagsToAddException")); + + given() + .header("X-Amz-Target", "CodeDeploy_20141006.ListTagsForResource") + .contentType(CONTENT_TYPE) + .body("{\"ResourceArn\":\"" + applicationArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Tags", hasSize(0)); + } + + @Test + void listOnPremisesInstancesRejectsObjectTagFilters() { + assertMalformed("ListOnPremisesInstances", + "{\"tagFilters\":{\"0\":{\"Key\":\"team\",\"Value\":\"red\"}}}", + "InvalidTagFilterException"); + } + + @Test + void listOnPremisesInstancesRejectsUnknownFilterType() { + assertMalformed("ListOnPremisesInstances", + "{\"tagFilters\":[{\"Key\":\"team\",\"Type\":\"UNKNOWN\"}]}", + "InvalidTagFilterException"); + } + + @Test + void addTagsToOnPremisesInstancesRejectsObjectTags() { + assertMalformed("AddTagsToOnPremisesInstances", + "{\"instanceNames\":[],\"tags\":{\"0\":{\"Key\":\"team\",\"Value\":\"red\"}}}", + "InvalidTagException"); + } + + @Test + void removeTagsFromOnPremisesInstancesRejectsObjectTags() { + assertMalformed("RemoveTagsFromOnPremisesInstances", + "{\"instanceNames\":[],\"tags\":{\"0\":{\"Key\":\"team\",\"Value\":\"red\"}}}", + "InvalidTagException"); + } + + private void assertMalformed(String action, String body, String expectedType) { + given() + .header("X-Amz-Target", "CodeDeploy_20141006." + action) + .contentType(CONTENT_TYPE) + .body(body) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo(expectedType)); + } + + private void deleteApplicationLater(String application) { + cleanup.register(() -> given() + .header("X-Amz-Target", "CodeDeploy_20141006.DeleteApplication") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + "\"}") + .post("/")); + } + + private void deleteDeploymentGroupLater(String application, String group) { + cleanup.register(() -> given() + .header("X-Amz-Target", "CodeDeploy_20141006.DeleteDeploymentGroup") + .contentType(CONTENT_TYPE) + .body("{\"applicationName\":\"" + application + "\",\"deploymentGroupName\":\"" + group + "\"}") + .post("/")); + } + + private void untagLater(String arn) { + cleanup.register(() -> given() + .header("X-Amz-Target", "CodeDeploy_20141006.UntagResource") + .contentType(CONTENT_TYPE) + .body("{\"ResourceArn\":\"" + arn + "\",\"TagKeys\":[\"team\",\"123\",\"\"]}") + .post("/")); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamTagOnCreateEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamTagOnCreateEnforcementIntegrationTest.java index c764648b08..b76f008489 100644 --- a/src/test/java/io/floci/aws/services/iam/IamTagOnCreateEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamTagOnCreateEnforcementIntegrationTest.java @@ -504,22 +504,15 @@ class IamTagOnCreateEnforcementIntegrationTest { .body("TagList.size()", equalTo(2)); } - /** - * CodeDeploy's handler reads a tag's key and value in either case, so the tagging action is checked for both, - * and the create's own action sees them. - */ + /** CodeDeploy's modeled tags need TagResource and are visible to the create's own condition keys. */ @Test - void anApplicationsTagsInEitherCaseNeedTagResource() { + void anApplicationsTagsNeedTagResource() { User user = user("tag-application"); String application = "tag-app-" + suffix(); - String create = "{\"applicationName\":\"" + application + "\",\"tags\":[{\"key\":\"team\",\"value\":\"red\"}]}"; + String create = "{\"applicationName\":\"" + application + "\",\"tags\":[{\"Key\":\"team\",\"Value\":\"red\"}]}"; user.policy(allow("codedeploy:CreateApplication")); refusedJson(user.json("codedeploy", "CodeDeploy_20141006.CreateApplication", "1.1").body(create).post("/").then(), "codedeploy:TagResource"); - // The handler keeps a key that is a number as its text, so it needs the tagging action too. - refusedJson(user.json("codedeploy", "CodeDeploy_20141006.CreateApplication", "1.1") - .body("{\"applicationName\":\"" + application + "\",\"tags\":[{\"key\":123,\"value\":\"red\"}]}") - .post("/").then(), "codedeploy:TagResource"); user.policy("{\"Effect\":\"Allow\",\"Action\":\"codedeploy:CreateApplication\",\"Resource\":\"*\"," + "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"red\"}}}," + allow("codedeploy:TagResource")); @@ -527,14 +520,50 @@ class IamTagOnCreateEnforcementIntegrationTest { .statusCode(200); cleanup.register(() -> admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.DeleteApplication") .contentType("application/x-amz-json-1.1").body("{\"applicationName\":\"" + application + "\"}").post("/")); + cleanup.register(() -> admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.UntagResource") + .contentType("application/x-amz-json-1.1") + .body("{\"ResourceArn\":\"arn:aws:codedeploy:us-east-1:000000000000:application:" + application + + "\",\"TagKeys\":[\"team\"]}").post("/")); + } - // The handler iterates an object's values as tags, so a deny on one holds however they are shaped. - user.policy(allow("codedeploy:CreateApplication") + "," + allow("codedeploy:TagResource") - + ",{\"Effect\":\"Deny\",\"Action\":\"codedeploy:CreateApplication\",\"Resource\":\"*\"," - + "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"red\"}}}"); - refusedJson(user.json("codedeploy", "CodeDeploy_20141006.CreateApplication", "1.1") - .body("{\"applicationName\":\"" + application + "-object\",\"tags\":{\"0\":{\"key\":\"team\",\"value\":\"red\"}}}") - .post("/").then(), "codedeploy:CreateApplication"); + @Test + void aDeploymentGroupsTagsNeedTagResource() { + User user = user("tag-deployment-group"); + String application = "tag-group-app-" + suffix(); + String group = "tag-group-" + suffix(); + String groupArn = "arn:aws:codedeploy:us-east-1:000000000000:deploymentgroup:" + + application + "/" + group; + cleanup.register(() -> admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.DeleteApplication") + .contentType("application/x-amz-json-1.1").body("{\"applicationName\":\"" + application + "\"}").post("/")); + admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication") + .contentType("application/x-amz-json-1.1") + .body("{\"applicationName\":\"" + application + "\"}").post("/").then().statusCode(200); + + cleanup.register(() -> admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.DeleteDeploymentGroup") + .contentType("application/x-amz-json-1.1") + .body("{\"applicationName\":\"" + application + "\",\"deploymentGroupName\":\"" + group + "\"}") + .post("/")); + cleanup.register(() -> admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.UntagResource") + .contentType("application/x-amz-json-1.1") + .body("{\"ResourceArn\":\"" + groupArn + "\",\"TagKeys\":[\"team\"]}").post("/")); + String create = """ + {"applicationName":"%s","deploymentGroupName":"%s", + "serviceRoleArn":"arn:aws:iam::000000000000:role/codedeploy", + "tags":[{"Key":"team","Value":"red"}]} + """.formatted(application, group); + user.policy(allow("codedeploy:CreateDeploymentGroup") + "," + allow("iam:PassRole")); + refusedJson(user.json("codedeploy", "CodeDeploy_20141006.CreateDeploymentGroup", "1.1") + .body(create).post("/").then(), "codedeploy:TagResource"); + + user.policy("{\"Effect\":\"Allow\",\"Action\":\"codedeploy:CreateDeploymentGroup\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"red\"}}}," + + allow("codedeploy:TagResource") + "," + allow("iam:PassRole")); + user.json("codedeploy", "CodeDeploy_20141006.CreateDeploymentGroup", "1.1") + .body(create).post("/").then().statusCode(200); + admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.ListTagsForResource") + .contentType("application/x-amz-json-1.1") + .body("{\"ResourceArn\":\"" + groupArn + "\"}").post("/").then().statusCode(200) + .body("Tags.find { it.Key == 'team' }.Value", equalTo("red")); } @Test