fix(ec2): apply TagSpecification on key pair, network ACL and image creates (#6551)

This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-26 06:53:52 -04:00
1 parent 935922933f
commit 0634184f5e
7 files changed
+1000 -20

No files matched your search

@@ -0,0 +1,478 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ED25519_KEY;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* TagSpecification on the create actions that used to drop it: CreateKeyPair, ImportKeyPair,
* CreateNetworkAcl, RegisterImage, CreateImage and CopyImage. AWS applies each specification to
* the resource the call creates, the next Describe* reports the tags, CreateKeyPair and
* ImportKeyPair also return them in the create response's tagSet, and CreateImage and CopyImage
* tag the AMI's new snapshots as well as the AMI. A specification CreateTags would reject is
* answered before anything is created, so a rejected create leaves no key pair, network ACL,
* AMI or snapshot behind. The image actions also accept only the resource types their reference
* allows: image for RegisterImage, image and snapshot for CreateImage and CopyImage.
*/
@QuarkusTest
class Ec2CreateTagSpecificationIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261025/us-east-1/ec2/aws4_request";
@Test
void createKeyPairAppliesItsTagSpecificationAndDescribesIt() {
XmlPath created = ec2("CreateKeyPair",
"KeyName", "tagged-created-" + UUID.randomUUID(),
"TagSpecification.1.ResourceType", "key-pair",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "keys");
String id = created.getString("CreateKeyPairResponse.keyPairId");
try {
assertEquals("Team", created.getString("CreateKeyPairResponse.tagSet.item.key"));
assertEquals("keys", created.getString("CreateKeyPairResponse.tagSet.item.value"));
XmlPath described = ec2("DescribeKeyPairs", "KeyPairId.1", id);
assertEquals("Team", described.getString("DescribeKeyPairsResponse.keySet.item.tagSet.item.key"));
assertEquals("keys", described.getString("DescribeKeyPairsResponse.keySet.item.tagSet.item.value"));
} finally {
ec2("DeleteKeyPair", "KeyPairId", id);
}
}
@Test
void importKeyPairAppliesItsTagSpecificationAndDescribesIt() {
XmlPath imported = ec2("ImportKeyPair",
"KeyName", "tagged-imported-" + UUID.randomUUID(),
"PublicKeyMaterial", Base64.getEncoder()
.encodeToString(ED25519_KEY.getBytes(StandardCharsets.UTF_8)),
"TagSpecification.1.ResourceType", "key-pair",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "keys");
String id = imported.getString("ImportKeyPairResponse.keyPairId");
try {
assertEquals("Team", imported.getString("ImportKeyPairResponse.tagSet.item.key"));
assertEquals("keys", imported.getString("ImportKeyPairResponse.tagSet.item.value"));
XmlPath described = ec2("DescribeKeyPairs", "KeyPairId.1", id);
assertEquals("Team", described.getString("DescribeKeyPairsResponse.keySet.item.tagSet.item.key"));
assertEquals("keys", described.getString("DescribeKeyPairsResponse.keySet.item.tagSet.item.value"));
} finally {
ec2("DeleteKeyPair", "KeyPairId", id);
}
}
@Test
void createNetworkAclAppliesItsTagSpecificationAndDescribesIt() {
String vpc = ec2("CreateVpc", "CidrBlock", "10.60.0.0/16")
.getString("CreateVpcResponse.vpc.vpcId");
String acl = null;
try {
XmlPath created = ec2("CreateNetworkAcl",
"VpcId", vpc,
"TagSpecification.1.ResourceType", "network-acl",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "net");
acl = created.getString("CreateNetworkAclResponse.networkAcl.networkAclId");
assertEquals("Team", created.getString("CreateNetworkAclResponse.networkAcl.tagSet.item.key"));
assertEquals("net", created.getString("CreateNetworkAclResponse.networkAcl.tagSet.item.value"));
XmlPath described = ec2("DescribeNetworkAcls", "NetworkAclId.1", acl);
assertEquals("Team", described.getString("DescribeNetworkAclsResponse.networkAclSet.item.tagSet.item.key"));
assertEquals("net", described.getString("DescribeNetworkAclsResponse.networkAclSet.item.tagSet.item.value"));
} finally {
if (acl != null) {
ec2("DeleteNetworkAcl", "NetworkAclId", acl);
}
ec2("DeleteVpc", "VpcId", vpc);
}
}
@Test
void registerImageAppliesItsTagSpecificationAndDescribesIt() {
String imageId = ec2("RegisterImage",
"Name", "tagged-registered-" + UUID.randomUUID(),
"Architecture", "x86_64",
"RootDeviceName", "/dev/xvda",
"TagSpecification.1.ResourceType", "image",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "images")
.getString("RegisterImageResponse.imageId");
try {
XmlPath described = describeImage(imageId);
assertEquals("Team", described.getString("DescribeImagesResponse.imagesSet.item.tagSet.item.key"));
assertEquals("images", described.getString("DescribeImagesResponse.imagesSet.item.tagSet.item.value"));
} finally {
ec2("DeregisterImage", "ImageId", imageId);
}
}
@Test
void copyImageAppliesItsSpecificationsToTheCopyAndItsNewSnapshots() {
String sourceSnapshot = "snap-0123456789abcdef0";
String source = ec2("RegisterImage",
"Name", "tag-copy-source-" + UUID.randomUUID(),
"Architecture", "x86_64",
"RootDeviceName", "/dev/xvda",
"BlockDeviceMapping.1.DeviceName", "/dev/xvda",
"BlockDeviceMapping.1.Ebs.SnapshotId", sourceSnapshot,
"BlockDeviceMapping.1.Ebs.VolumeSize", "8")
.getString("RegisterImageResponse.imageId");
String copy = null;
try {
copy = ec2("CopyImage",
"SourceRegion", "us-east-1",
"SourceImageId", source,
"Name", "tag-copy-destination-" + UUID.randomUUID(),
"TagSpecification.1.ResourceType", "image",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "images",
"TagSpecification.2.ResourceType", "snapshot",
"TagSpecification.2.Tag.1.Key", "Team",
"TagSpecification.2.Tag.1.Value", "snapshots")
.getString("CopyImageResponse.imageId");
XmlPath described = describeImage(copy);
assertEquals("Team", described.getString("DescribeImagesResponse.imagesSet.item.tagSet.item.key"));
assertEquals("images", described.getString("DescribeImagesResponse.imagesSet.item.tagSet.item.value"));
List<String> copySnapshots = snapshotIdsOf(described);
assertEquals(1, copySnapshots.size());
assertFalse(copySnapshots.contains(sourceSnapshot), "the copy takes its own fresh snapshots");
XmlPath snapshot = ec2("DescribeSnapshots", "SnapshotId.1", copySnapshots.get(0));
assertEquals("Team", snapshot.getString("DescribeSnapshotsResponse.snapshotSet.item.tagSet.item.key"));
assertEquals("snapshots",
snapshot.getString("DescribeSnapshotsResponse.snapshotSet.item.tagSet.item.value"));
XmlPath sourceDescribed = ec2("DescribeSnapshots", "SnapshotId.1", sourceSnapshot);
assertTrue(sourceDescribed.getList("DescribeSnapshotsResponse.snapshotSet.item.tagSet.item",
String.class).isEmpty(), "the source AMI's own snapshot is left untagged");
} finally {
if (copy != null) {
ec2("DeregisterImage", "ImageId", copy, "DeleteAssociatedSnapshots", "true");
}
ec2("DeregisterImage", "ImageId", source);
}
}
@Test
void createImageAppliesItsSpecificationsToTheAmiAndItsSnapshots() {
String instance = ec2("RunInstances",
"ImageId", "ami-0abcdef1234567890",
"InstanceType", "t3.micro",
"MinCount", "1",
"MaxCount", "1")
.getString("RunInstancesResponse.instancesSet.item.instanceId");
String imageId = null;
try {
imageId = ec2("CreateImage",
"InstanceId", instance,
"Name", "tag-captured-" + UUID.randomUUID(),
"NoReboot", "true",
"TagSpecification.1.ResourceType", "image",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "images",
"TagSpecification.2.ResourceType", "snapshot",
"TagSpecification.2.Tag.1.Key", "Team",
"TagSpecification.2.Tag.1.Value", "snapshots")
.getString("CreateImageResponse.imageId");
XmlPath described = describeImage(imageId);
assertEquals("Team", described.getString("DescribeImagesResponse.imagesSet.item.tagSet.item.key"));
assertEquals("images", described.getString("DescribeImagesResponse.imagesSet.item.tagSet.item.value"));
assertFalse(snapshotIdsOf(described).isEmpty(), "the captured AMI records its new snapshots");
for (String snapshotId : snapshotIdsOf(described)) {
XmlPath snapshot = ec2("DescribeSnapshots", "SnapshotId.1", snapshotId);
assertEquals("Team", snapshot.getString("DescribeSnapshotsResponse.snapshotSet.item.tagSet.item.key"));
assertEquals("snapshots",
snapshot.getString("DescribeSnapshotsResponse.snapshotSet.item.tagSet.item.value"));
}
} finally {
if (imageId != null) {
ec2("DeregisterImage", "ImageId", imageId, "DeleteAssociatedSnapshots", "true");
}
ec2("TerminateInstances", "InstanceId.1", instance);
}
}
@Test
void createKeyPairRejectsAnInvalidTagSpecificationWithoutCreatingTheKeyPair() {
String name = "oversized-created-" + UUID.randomUUID();
XmlPath rejected = ec2Rejects("CreateKeyPair",
"KeyName", name,
"TagSpecification.1.ResourceType", "key-pair",
"TagSpecification.1.Tag.1.Key", "k".repeat(129),
"TagSpecification.1.Tag.1.Value", "valid");
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
assertEquals("Tag key exceeds the maximum length of 128 characters",
rejected.getString("Response.Errors.Error.Message"));
XmlPath described = ec2Rejects("DescribeKeyPairs", "KeyName.1", name);
assertEquals("InvalidKeyPair.NotFound", described.getString("Response.Errors.Error.Code"));
}
@Test
void importKeyPairRejectsAnInvalidTagSpecificationWithoutCreatingTheKeyPair() {
String name = "oversized-imported-" + UUID.randomUUID();
XmlPath rejected = ec2Rejects("ImportKeyPair",
"KeyName", name,
"PublicKeyMaterial", Base64.getEncoder()
.encodeToString(ED25519_KEY.getBytes(StandardCharsets.UTF_8)),
"TagSpecification.1.ResourceType", "key-pair",
"TagSpecification.1.Tag.1.Key", "k".repeat(129),
"TagSpecification.1.Tag.1.Value", "valid");
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
XmlPath described = ec2Rejects("DescribeKeyPairs", "KeyName.1", name);
assertEquals("InvalidKeyPair.NotFound", described.getString("Response.Errors.Error.Code"));
}
@Test
void createNetworkAclRejectsAnInvalidTagSpecificationWithoutCreatingTheAcl() {
String vpc = ec2("CreateVpc", "CidrBlock", "10.61.0.0/16")
.getString("CreateVpcResponse.vpc.vpcId");
try {
XmlPath rejected = ec2Rejects("CreateNetworkAcl",
"VpcId", vpc,
"TagSpecification.1.ResourceType", "network-acl",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "v".repeat(257));
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
assertEquals("Tag value exceeds the maximum length of 256 characters",
rejected.getString("Response.Errors.Error.Message"));
XmlPath acls = ec2("DescribeNetworkAcls",
"Filter.1.Name", "vpc-id",
"Filter.1.Value.1", vpc);
List<String> aclIds = acls.getList(
"DescribeNetworkAclsResponse.networkAclSet.item.networkAclId", String.class);
assertEquals(1, aclIds.size(), "only the VPC's default network ACL remains");
} finally {
ec2("DeleteVpc", "VpcId", vpc);
}
}
@Test
void registerImageRejectsAnInvalidTagSpecificationWithoutCreatingTheAmi() {
String name = "oversized-registered-" + UUID.randomUUID();
XmlPath rejected = ec2Rejects("RegisterImage",
"Name", name,
"Architecture", "x86_64",
"RootDeviceName", "/dev/xvda",
"TagSpecification.1.ResourceType", "image",
"TagSpecification.1.Tag.1.Key", "k".repeat(129),
"TagSpecification.1.Tag.1.Value", "valid");
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
assertTrue(describeImageByName(name).getList(
"DescribeImagesResponse.imagesSet.item.imageId", String.class).isEmpty(),
"the rejected registration created no AMI");
}
@Test
void registerImageRejectsATagSpecificationForAResourceItDoesNotCreate() {
String name = "wrong-type-registered-" + UUID.randomUUID();
XmlPath rejected = ec2Rejects("RegisterImage",
"Name", name,
"Architecture", "x86_64",
"RootDeviceName", "/dev/xvda",
"TagSpecification.1.ResourceType", "instance",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "instances");
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
assertEquals("Tag specification resource type 'instance' is not valid for this operation. "
+ "The valid resource type is 'image'.",
rejected.getString("Response.Errors.Error.Message"));
assertTrue(describeImageByName(name).getList(
"DescribeImagesResponse.imagesSet.item.imageId", String.class).isEmpty(),
"the rejected registration created no AMI");
}
@Test
void createImageRejectsInvalidSnapshotTagsWithoutCreatingTheAmiOrItsSnapshots() {
String instance = ec2("RunInstances",
"ImageId", "ami-0abcdef1234567890",
"InstanceType", "t3.micro",
"MinCount", "1",
"MaxCount", "1")
.getString("RunInstancesResponse.instancesSet.item.instanceId");
try {
int snapshotsBefore = selfOwnedSnapshotCount();
String name = "oversized-captured-" + UUID.randomUUID();
XmlPath rejected = ec2Rejects("CreateImage",
"InstanceId", instance,
"Name", name,
"NoReboot", "true",
"TagSpecification.1.ResourceType", "image",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "images",
"TagSpecification.2.ResourceType", "snapshot",
"TagSpecification.2.Tag.1.Key", "Team",
"TagSpecification.2.Tag.1.Value", "v".repeat(257));
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
assertEquals("Tag value exceeds the maximum length of 256 characters",
rejected.getString("Response.Errors.Error.Message"));
assertTrue(describeImageByName(name).getList(
"DescribeImagesResponse.imagesSet.item.imageId", String.class).isEmpty(),
"the rejected create left no AMI");
assertEquals(snapshotsBefore, selfOwnedSnapshotCount(), "the rejected create left no snapshots");
} finally {
ec2("TerminateInstances", "InstanceId.1", instance);
}
}
@Test
void createImageRejectsATagSpecificationForAResourceItDoesNotCreate() {
String instance = ec2("RunInstances",
"ImageId", "ami-0abcdef1234567890",
"InstanceType", "t3.micro",
"MinCount", "1",
"MaxCount", "1")
.getString("RunInstancesResponse.instancesSet.item.instanceId");
try {
int snapshotsBefore = selfOwnedSnapshotCount();
String name = "wrong-type-captured-" + UUID.randomUUID();
XmlPath rejected = ec2Rejects("CreateImage",
"InstanceId", instance,
"Name", name,
"NoReboot", "true",
"TagSpecification.1.ResourceType", "instance",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "instances");
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
assertEquals("Tag specification resource type 'instance' is not valid for this operation. "
+ "The valid resource types are 'image' and 'snapshot'.",
rejected.getString("Response.Errors.Error.Message"));
assertTrue(describeImageByName(name).getList(
"DescribeImagesResponse.imagesSet.item.imageId", String.class).isEmpty(),
"the rejected create left no AMI");
assertEquals(snapshotsBefore, selfOwnedSnapshotCount(), "the rejected create left no snapshots");
} finally {
ec2("TerminateInstances", "InstanceId.1", instance);
}
}
@Test
void copyImageRejectsATagSpecificationForAResourceItDoesNotCreate() {
String source = ec2("RegisterImage",
"Name", "wrong-type-copy-source-" + UUID.randomUUID(),
"Architecture", "x86_64",
"RootDeviceName", "/dev/xvda",
"BlockDeviceMapping.1.DeviceName", "/dev/xvda",
"BlockDeviceMapping.1.Ebs.SnapshotId", "snap-0123456789abcdef0",
"BlockDeviceMapping.1.Ebs.VolumeSize", "8")
.getString("RegisterImageResponse.imageId");
try {
int snapshotsBefore = selfOwnedSnapshotCount();
String name = "wrong-type-copy-destination-" + UUID.randomUUID();
XmlPath rejected = ec2Rejects("CopyImage",
"SourceRegion", "us-east-1",
"SourceImageId", source,
"Name", name,
"TagSpecification.1.ResourceType", "instance",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "instances");
assertEquals("InvalidParameterValue", rejected.getString("Response.Errors.Error.Code"));
assertEquals("Tag specification resource type 'instance' is not valid for this operation. "
+ "The valid resource types are 'image' and 'snapshot'.",
rejected.getString("Response.Errors.Error.Message"));
assertTrue(describeImageByName(name).getList(
"DescribeImagesResponse.imagesSet.item.imageId", String.class).isEmpty(),
"the rejected copy left no AMI");
assertEquals(snapshotsBefore, selfOwnedSnapshotCount(), "the rejected copy left no snapshots");
} finally {
ec2("DeregisterImage", "ImageId", source);
}
}
@Test
void copyImageRejectsInvalidSnapshotTagsWithoutCreatingTheAmiOrItsSnapshots() {
String source = ec2("RegisterImage",
"Name", "oversized-copy-source-" + UUID.randomUUID(),
"Architecture", "x86_64",
"RootDeviceName", "/dev/xvda",
"BlockDeviceMapping.1.DeviceName", "/dev/xvda",
"BlockDeviceMapping.1.Ebs.SnapshotId", "snap-0123456789abcdef0",
"BlockDeviceMapping.1.Ebs.VolumeSize", "8")
.getString("RegisterImageResponse.imageId");
try {
int snapshotsBefore = selfOwnedSnapshotCount();
String name = "oversized-copy-destination-" + UUID.randomUUID();
List<String> form = new ArrayList<>(List.of(
"SourceRegion", "us-east-1",
"SourceImageId", source,
"Name", name,
"TagSpecification.1.ResourceType", "image",
"TagSpecification.1.Tag.1.Key", "Team",
"TagSpecification.1.Tag.1.Value", "images",
"TagSpecification.2.ResourceType", "snapshot"));
for (int i = 1; i <= 51; i++) {
form.add("TagSpecification.2.Tag." + i + ".Key");
form.add("k" + i);
}
XmlPath rejected = ec2Rejects("CopyImage", form.toArray(new String[0]));
assertEquals("TagLimitExceeded", rejected.getString("Response.Errors.Error.Code"));
assertEquals("The maximum number of Tags for a resource has been reached.",
rejected.getString("Response.Errors.Error.Message"));
assertTrue(describeImageByName(name).getList(
"DescribeImagesResponse.imagesSet.item.imageId", String.class).isEmpty(),
"the rejected copy left no AMI");
assertEquals(snapshotsBefore, selfOwnedSnapshotCount(), "the rejected copy left no snapshots");
} finally {
ec2("DeregisterImage", "ImageId", source);
}
}
private XmlPath describeImage(String imageId) {
return ec2("DescribeImages", "ImageId.1", imageId);
}
private List<String> snapshotIdsOf(XmlPath describedImage) {
return describedImage.getList(
"DescribeImagesResponse.imagesSet.item.blockDeviceMapping.item.ebs.snapshotId", String.class);
}
private XmlPath describeImageByName(String name) {
return ec2("DescribeImages",
"Filter.1.Name", "name",
"Filter.1.Value.1", name);
}
private int selfOwnedSnapshotCount() {
return ec2("DescribeSnapshots")
.getList("DescribeSnapshotsResponse.snapshotSet.item.snapshotId", String.class).size();
}
private XmlPath ec2Rejects(String action, String... formParams) {
RequestSpecification request = given().header("Authorization", AUTH).formParam("Action", action);
for (int i = 0; i < formParams.length; i += 2) {
request.formParam(formParams[i], formParams[i + 1]);
}
return request.post("/").then().statusCode(400).extract().xmlPath();
}
private XmlPath ec2(String action, String... formParams) {
RequestSpecification request = given().header("Authorization", AUTH).formParam("Action", action);
for (int i = 0; i < formParams.length; i += 2) {
request.formParam(formParams[i], formParams[i + 1]);
}
return request.post("/").then().statusCode(200).extract().xmlPath();
}
}
@@ -3,7 +3,11 @@ package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.KeyPair;
import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
@@ -19,6 +23,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Stream;
@@ -35,9 +40,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -52,7 +59,10 @@ class Ec2QueryHandlerTest {
"AllocateAddress,elastic-ip", "AuthorizeSecurityGroupIngress,security-group-rule",
"AuthorizeSecurityGroupEgress,security-group-rule", "RunInstances,instance",
"RunInstances,network-interface", "CreateVolume,volume",
"RequestSpotInstances,spot-instances-request", "RequestSpotInstances,instance"
"RequestSpotInstances,spot-instances-request", "RequestSpotInstances,instance",
"CreateKeyPair,key-pair", "ImportKeyPair,key-pair", "CreateNetworkAcl,network-acl",
"CreateImage,image", "CreateImage,snapshot", "RegisterImage,image",
"CopyImage,image", "CopyImage,snapshot"
})
void rejectsReservedCreationTagsBeforeAllocatingResources(String action, String resourceType) {
for (String prefix : List.of("TagSpecification", "TagSpecifications")) {
@@ -62,6 +72,9 @@ class Ec2QueryHandlerTest {
params.putSingle("GroupDescription", "test");
params.putSingle("MinCount", "1");
params.putSingle("MaxCount", "1");
params.putSingle("KeyName", "test");
params.putSingle("PublicKeyMaterial",
Base64.getEncoder().encodeToString(ED25519_KEY.getBytes(StandardCharsets.UTF_8)));
params.putSingle(prefix + ".1.ResourceType", resourceType);
params.putSingle(prefix + ".1.Tag.1.Key", "Name");
params.putSingle(prefix + ".1.Tag.1.Value", "valid");
@@ -80,6 +93,86 @@ class Ec2QueryHandlerTest {
}
}
@ParameterizedTest
@CsvSource({
"CreateKeyPair,key-pair,key", "ImportKeyPair,key-pair,key",
"CreateNetworkAcl,network-acl,key", "RegisterImage,image,key",
"CreateImage,image,key", "CreateImage,snapshot,value",
"CopyImage,image,key", "CopyImage,snapshot,limit"
})
void rejectsInvalidCreationTagsBeforeAllocatingResources(String action, String resourceType,
String violation) {
for (String prefix : List.of("TagSpecification", "TagSpecifications")) {
Ec2Service service = mock(Ec2Service.class);
MultivaluedMap<String, String> params = createSubnetParams("10.38.1.0/24");
params.putSingle("GroupName", "test");
params.putSingle("GroupDescription", "test");
params.putSingle("MinCount", "1");
params.putSingle("MaxCount", "1");
params.putSingle("KeyName", "test");
params.putSingle("PublicKeyMaterial",
Base64.getEncoder().encodeToString(ED25519_KEY.getBytes(StandardCharsets.UTF_8)));
params.putSingle(prefix + ".1.ResourceType", resourceType);
switch (violation) {
case "key" -> {
params.putSingle(prefix + ".1.Tag.1.Key", "k".repeat(129));
params.putSingle(prefix + ".1.Tag.1.Value", "v");
}
case "value" -> {
params.putSingle(prefix + ".1.Tag.1.Key", "k");
params.putSingle(prefix + ".1.Tag.1.Value", "v".repeat(257));
}
case "limit" -> {
for (int i = 1; i <= 51; i++) {
params.putSingle(prefix + ".1.Tag." + i + ".Key", "k" + i);
}
}
default -> throw new IllegalArgumentException(violation);
}
Response response = handler(service).handle(action, params, "us-east-1");
assertEquals(400, response.getStatus());
String body = response.getEntity().toString();
String code = "limit".equals(violation) ? "TagLimitExceeded" : "InvalidParameterValue";
String message = switch (violation) {
case "key" -> "Tag key exceeds the maximum length of 128 characters";
case "value" -> "Tag value exceeds the maximum length of 256 characters";
default -> "The maximum number of Tags for a resource has been reached.";
};
assertTrue(body.contains("<Code>" + code + "</Code>"), body);
assertTrue(body.contains(message), body);
verifyNoInteractions(service);
}
}
@ParameterizedTest
@CsvSource({
"RegisterImage,instance,The valid resource type is 'image'.",
"CreateImage,instance,The valid resource types are 'image' and 'snapshot'.",
"CopyImage,instance,The valid resource types are 'image' and 'snapshot'."
})
void rejectsTagSpecificationsForResourcesTheImageActionsDoNotCreate(String action, String resourceType,
String validResourceTypes) {
Ec2Service service = mock(Ec2Service.class);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("Name", "wrong-resource-type");
params.putSingle("TagSpecification.1.ResourceType", resourceType);
params.putSingle("TagSpecification.1.Tag.1.Key", "Team");
params.putSingle("TagSpecification.1.Tag.1.Value", "images");
Response response = handler(service).handle(action, params, "us-east-1");
assertEquals(400, response.getStatus());
String body = response.getEntity().toString();
String message = ("Tag specification resource type '" + resourceType
+ "' is not valid for this operation. " + validResourceTypes)
.replace("'", "&apos;");
assertTrue(body.contains("<Code>InvalidParameterValue</Code>"), body);
assertTrue(body.contains(message), body);
verifyNoInteractions(service);
}
@ParameterizedTest
@ValueSource(strings = {"CreateLaunchTemplate", "CreateLaunchTemplateVersion"})
void rejectsReservedNestedTemplateTagsBeforeCreatingATemplateOrVersion(String action) {
@@ -180,6 +273,182 @@ class Ec2QueryHandlerTest {
assertEquals(List.of(""), tags.getValue().stream().map(Tag::getValue).toList());
}
@ParameterizedTest
@ValueSource(strings = {"TagSpecification", "TagSpecifications"})
void createKeyPairAppliesItsTagSpecificationAndReturnsIt(String prefix) {
Ec2Service service = mock(Ec2Service.class);
KeyPair keyPair = new KeyPair();
keyPair.setKeyPairId("key-0123456789abcdef0");
keyPair.setKeyName("tagged");
when(service.createKeyPair("us-east-1", "tagged", null, null)).thenReturn(keyPair);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("KeyName", "tagged");
params.putSingle(prefix + ".1.ResourceType", "key-pair");
params.putSingle(prefix + ".1.Tag.1.Key", "Team");
params.putSingle(prefix + ".1.Tag.1.Value", "keys");
Response response = handler(service).handle("CreateKeyPair", params, "us-east-1");
assertEquals(200, response.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
verify(service).createTags(eq("us-east-1"), eq(List.of("key-0123456789abcdef0")), tags.capture());
assertEquals(List.of("Team=keys"), tags.getValue().stream()
.map(tag -> tag.getKey() + "=" + tag.getValue()).toList());
String body = (String) response.getEntity();
assertTrue(body.contains("<tagSet><item><key>Team</key><value>keys</value></item></tagSet>"), body);
}
@ParameterizedTest
@ValueSource(strings = {"TagSpecification", "TagSpecifications"})
void importKeyPairAppliesItsTagSpecificationAndReturnsIt(String prefix) {
Ec2Service service = mock(Ec2Service.class);
KeyPair keyPair = new KeyPair();
keyPair.setKeyPairId("key-0123456789abcdef1");
keyPair.setKeyName("tagged");
when(service.importKeyPair(eq("us-east-1"), eq("tagged"), any())).thenReturn(keyPair);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("KeyName", "tagged");
params.putSingle("PublicKeyMaterial", Base64.getEncoder()
.encodeToString(ED25519_KEY.getBytes(StandardCharsets.UTF_8)));
params.putSingle(prefix + ".1.ResourceType", "key-pair");
params.putSingle(prefix + ".1.Tag.1.Key", "Team");
params.putSingle(prefix + ".1.Tag.1.Value", "keys");
Response response = handler(service).handle("ImportKeyPair", params, "us-east-1");
assertEquals(200, response.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
verify(service).createTags(eq("us-east-1"), eq(List.of("key-0123456789abcdef1")), tags.capture());
assertEquals(List.of("Team=keys"), tags.getValue().stream()
.map(tag -> tag.getKey() + "=" + tag.getValue()).toList());
String body = (String) response.getEntity();
assertTrue(body.contains("<tagSet><item><key>Team</key><value>keys</value></item></tagSet>"), body);
}
@Test
void createNetworkAclAppliesItsTagSpecification() {
Ec2Service service = mock(Ec2Service.class);
NetworkAcl acl = new NetworkAcl();
acl.setNetworkAclId("acl-0123456789abcdef0");
when(service.createNetworkAcl("us-east-1", "vpc-test")).thenReturn(acl);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("VpcId", "vpc-test");
params.putSingle("TagSpecification.1.ResourceType", "network-acl");
params.putSingle("TagSpecification.1.Tag.1.Key", "Team");
params.putSingle("TagSpecification.1.Tag.1.Value", "net");
Response response = handler(service).handle("CreateNetworkAcl", params, "us-east-1");
assertEquals(200, response.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
verify(service).createTags(eq("us-east-1"), eq(List.of("acl-0123456789abcdef0")), tags.capture());
assertEquals(List.of("Team=net"), tags.getValue().stream()
.map(tag -> tag.getKey() + "=" + tag.getValue()).toList());
}
@Test
void createImageTagsTheAmiAndEachNewSnapshot() {
Ec2Service service = mock(Ec2Service.class);
Image image = new Image();
image.setImageId("ami-0123456789abcdef0");
image.setBlockDeviceMappings(new ArrayList<>(List.of(
deviceMapping("/dev/sda1", "snap-0123456789abcdef0"),
new BlockDeviceMapping(),
deviceMapping("/dev/sdb", "snap-0123456789abcdef1"))));
when(service.createImage("us-east-1", "i-test", "name", null, false)).thenReturn(image);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("InstanceId", "i-test");
params.putSingle("Name", "name");
params.putSingle("NoReboot", "false");
params.putSingle("TagSpecification.1.ResourceType", "image");
params.putSingle("TagSpecification.1.Tag.1.Key", "Team");
params.putSingle("TagSpecification.1.Tag.1.Value", "images");
params.putSingle("TagSpecification.2.ResourceType", "snapshot");
params.putSingle("TagSpecification.2.Tag.1.Key", "Team");
params.putSingle("TagSpecification.2.Tag.1.Value", "snapshots");
Response response = handler(service).handle("CreateImage", params, "us-east-1");
assertEquals(200, response.getStatus());
assertEquals(List.of("ami-0123456789abcdef0=Team=images"),
appliedTags(service, "ami-0123456789abcdef0"));
assertEquals(List.of("snap-0123456789abcdef0=Team=snapshots"),
appliedTags(service, "snap-0123456789abcdef0"));
assertEquals(List.of("snap-0123456789abcdef1=Team=snapshots"),
appliedTags(service, "snap-0123456789abcdef1"));
}
@Test
void registerImageTagsTheAmiAlone() {
Ec2Service service = mock(Ec2Service.class);
Image image = new Image();
image.setImageId("ami-0123456789abcdef1");
image.setBlockDeviceMappings(List.of(deviceMapping("/dev/sda1", "snap-0123456789abcdef2")));
when(service.registerImage(eq("us-east-1"), eq("name"), any(), any(), any(), anyList()))
.thenReturn(image);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("Name", "name");
params.putSingle("TagSpecification.1.ResourceType", "image");
params.putSingle("TagSpecification.1.Tag.1.Key", "Team");
params.putSingle("TagSpecification.1.Tag.1.Value", "images");
Response response = handler(service).handle("RegisterImage", params, "us-east-1");
assertEquals(200, response.getStatus());
assertEquals(List.of("ami-0123456789abcdef1=Team=images"),
appliedTags(service, "ami-0123456789abcdef1"));
verify(service, never()).createTags(anyString(), eq(List.of("snap-0123456789abcdef2")), anyList());
}
@Test
void copyImageTagsTheCopyAndItsNewSnapshots() {
Ec2Service service = mock(Ec2Service.class);
Image image = new Image();
image.setImageId("ami-0123456789abcdef2");
image.setBlockDeviceMappings(List.of(deviceMapping("/dev/sda1", "snap-0123456789abcdef3")));
when(service.copyImage("us-east-1", "us-west-2", "ami-source", "name", null)).thenReturn(image);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("SourceRegion", "us-west-2");
params.putSingle("SourceImageId", "ami-source");
params.putSingle("Name", "name");
params.putSingle("TagSpecification.1.ResourceType", "image");
params.putSingle("TagSpecification.1.Tag.1.Key", "Team");
params.putSingle("TagSpecification.1.Tag.1.Value", "images");
params.putSingle("TagSpecification.2.ResourceType", "snapshot");
params.putSingle("TagSpecification.2.Tag.1.Key", "Team");
params.putSingle("TagSpecification.2.Tag.1.Value", "snapshots");
Response response = handler(service).handle("CopyImage", params, "us-east-1");
assertEquals(200, response.getStatus());
assertEquals(List.of("ami-0123456789abcdef2=Team=images"),
appliedTags(service, "ami-0123456789abcdef2"));
assertEquals(List.of("snap-0123456789abcdef3=Team=snapshots"),
appliedTags(service, "snap-0123456789abcdef3"));
}
/** The tags each createTags call applied to one resource, as {@code id=key=value} strings. */
private static List<String> appliedTags(Ec2Service service, String resourceId) {
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
verify(service).createTags(eq("us-east-1"), eq(List.of(resourceId)), tags.capture());
return tags.getValue().stream()
.map(tag -> resourceId + "=" + tag.getKey() + "=" + tag.getValue())
.toList();
}
private static BlockDeviceMapping deviceMapping(String deviceName, String snapshotId) {
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setSnapshotId(snapshotId);
BlockDeviceMapping mapping = new BlockDeviceMapping();
mapping.setDeviceName(deviceName);
mapping.setEbs(ebs);
return mapping;
}
@ParameterizedTest
@ValueSource(strings = {"TagSpecification", "TagSpecifications"})
void validatesEveryCreateSubnetTagSpecificationBeforeMutation(String prefix) {
@@ -1162,6 +1162,37 @@ class Ec2ServiceTest {
service.createTags("us-east-1", List.of(vpcId), List.of(new Tag("\uD83D\uDE00".repeat(128), "v")));
}
@Test
void validateNewResourceTagsRejectsWhatCreateTagsRejects() {
List<Tag> fiftyKeys = new ArrayList<>();
for (int i = 0; i < 50; i++) {
fiftyKeys.add(new Tag("k" + i, "v"));
}
fiftyKeys.add(new Tag("k0", "a repeated key counts once"));
Ec2Service.validateNewResourceTags(fiftyKeys);
AwsException reserved = assertThrows(AwsException.class,
() -> Ec2Service.validateNewResourceTags(List.of(new Tag("aws:Name", "v"))));
assertEquals("InvalidParameterValue", reserved.getErrorCode());
assertEquals("Value ( aws:Name ) for parameter key is invalid. "
+ "Tag keys starting with 'aws:' are reserved for internal use", reserved.getMessage());
AwsException longKey = assertThrows(AwsException.class,
() -> Ec2Service.validateNewResourceTags(List.of(new Tag("k".repeat(129), "v"))));
assertEquals("InvalidParameterValue", longKey.getErrorCode());
assertEquals("Tag key exceeds the maximum length of 128 characters", longKey.getMessage());
AwsException longValue = assertThrows(AwsException.class,
() -> Ec2Service.validateNewResourceTags(List.of(new Tag("k", "v".repeat(257)))));
assertEquals("InvalidParameterValue", longValue.getErrorCode());
assertEquals("Tag value exceeds the maximum length of 256 characters", longValue.getMessage());
List<Tag> fiftyOneKeys = new ArrayList<>(fiftyKeys);
fiftyOneKeys.add(new Tag("k50", "v"));
AwsException overLimit = assertThrows(AwsException.class,
() -> Ec2Service.validateNewResourceTags(fiftyOneKeys));
assertEquals("TagLimitExceeded", overLimit.getErrorCode());
assertEquals("The maximum number of Tags for a resource has been reached.", overLimit.getMessage());
}
private static Ec2Service tagTestService(StorageFactory storageFactory) {
return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), storageFactory);