fix(ec2): preserve reserved tags during API and stack updates (#5611)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-14 13:39:45 -04:00
1 parent 12c8f969af
commit 90b9d37fd2
16 files changed
+470 -110

No files matched your search

@@ -1,8 +1,14 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -21,6 +27,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudFormationEc2InstanceIntegrationTest {
@Inject
Ec2Service ec2;
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/ap-southeast-2/cloudformation/aws4_request";
private static final String EC2_AUTH =
@@ -28,6 +37,72 @@ class CloudFormationEc2InstanceIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request";
@Test
void tagUpdatesPreserveServiceOwnedInstanceAndSubnetTags() {
String region = "ap-southeast-2";
String stackName = "cfn-ec2-owned-tags-" + Long.toString(System.nanoTime(), 36);
String template = """
{"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.193.0.0/16"}},
"Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.193.1.0/24", "Tags": %s}},
"Server": {"Type": "AWS::EC2::Instance", "Properties": {
"ImageId": "ami-12345678", "InstanceType": "t3.micro",
"SubnetId": {"Ref": "Subnet"}, "Tags": %s}}
}, "Outputs": {
"InstanceId": {"Value": {"Ref": "Server"}},
"SubnetId": {"Value": {"Ref": "Subnet"}}
}}
""";
String original = """
[{"Key": "Name", "Value": "before"}, {"Key": "Removed", "Value": "before"}]
""";
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted(original, original))
.when().post("/").then().statusCode(200);
try {
String stack = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>")).extract().asString();
List<String> ids = List.of(output(stack, "InstanceId"), output(stack, "SubnetId"));
Map<String, String> managed = Map.of("aws:autoscaling:groupName", "attached-group",
"aws:cloudformation:stack-id", stackName, "AWS:service", "owner");
ec2.createSystemTags(region, ids, managed.entrySet().stream()
.map(entry -> new Tag(entry.getKey(), entry.getValue())).toList());
for (String desired : List.of("""
[{"Key": "Name", "Value": "after"}, {"Key": "Added", "Value": "after"}]
""", "[]")) {
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted(desired, desired))
.when().post("/").then().statusCode(200);
String updated = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>")).extract().asString();
assertEquals(ids, List.of(output(updated, "InstanceId"), output(updated, "SubnetId")));
Map<String, String> expected = new HashMap<>(managed);
if (!"[]".equals(desired)) {
expected.put("Name", "after");
expected.put("Added", "after");
}
for (String id : ids) {
Map<String, String> observed = new HashMap<>();
ec2.describeTags(region, Map.of("resource-id", List.of(id)))
.forEach(tag -> observed.put(tag.get("key"), tag.get("value")));
assertEquals(expected, observed);
}
}
} finally {
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack").formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
}
}
@Test
void createStackProvisionsRealEc2Instance() {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -39,6 +39,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
@@ -472,7 +473,9 @@ class Ec2InstanceCfnProvisionerTest {
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
.thenReturn(List.of(reservationOf(i1)));
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(
tagEntry("i-1", "env", "prod"), tagEntry("i-1", "old", "stale")));
tagEntry("i-1", "env", "prod"), tagEntry("i-1", "old", "stale"),
tagEntry("i-1", "aws:autoscaling:groupName", "group"),
tagEntry("i-1", "AWS:cloudformation:stack-id", "stack")));
provisioner.provision(r, props("""
{"ImageId": "ami-1", "Tags": [{"Key": "env", "Value": "prod"}]}
"""), ctx("i-1"));
@@ -484,6 +487,41 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("old", removed.getValue().get(0).getKey());
}
@Test
void reservedUpdateTagsFailBeforeChangingTheInstanceOrItsTags() throws Exception {
StackResource r = resource("Server");
r.setPhysicalId("i-1");
r.getAttributes().put("InstanceId", "i-1");
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"ImageId": "ami-1", "InstanceType": "t3.small",
"SecurityGroupIds": ["sg-new"], "UserData": "changed",
"Tags": [{"Key": "AWS:reserved", "Value": "invalid"}]}
"""), ctx("i-1")));
assertEquals("InvalidParameterValue", failure.getErrorCode());
assertEquals("i-1", r.getPhysicalId());
assertEquals(Map.of("InstanceId", "i-1"), r.getAttributes());
verifyNoInteractions(ec2);
}
@Test
void reservedCreateTagsFailBeforeLaunchingAnInstance() throws Exception {
assertThrows(AwsException.class, () -> provisioner.provision(resource("Server"), props("""
{"ImageId": "ami-1", "Tags": [{"Key": "aws:reserved", "Value": "invalid"}]}
"""), ctx(null)));
verifyNoInteractions(ec2);
}
@Test
void tagReconciliationValidatesBeforeDeletingStaleTags() {
assertThrows(AwsException.class, () -> Ec2Tags.reconcile(ec2, "us-east-1", "i-1",
Map.of("env", "new", "aWs:reserved", "invalid")));
verifyNoInteractions(ec2);
}
@Test
void reusedInstanceResizesInstanceTypeInPlace() throws Exception {
Instance i1 = new Instance();
@@ -602,7 +602,8 @@ class Ec2NetworkCfnProvisionerTest {
@Test
void aReusedSubnetDropsTheTagKeysTheTemplateRemovedAndWritesTheRest() {
Subnet current = subnet();
current.setTags(List.of(new Tag("Name", "old"), new Tag("team", "net")));
current.setTags(List.of(new Tag("Name", "old"), new Tag("team", "net"),
new Tag("aws:cloudformation:stack-id", "stack"), new Tag("AWS:service", "owner")));
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ObjectNode props = withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "Name", "new");
@@ -621,7 +622,8 @@ class Ec2NetworkCfnProvisionerTest {
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
rt.setTags(List.of(new Tag("Name", "old"), new Tag("team", "net")));
rt.setTags(List.of(new Tag("Name", "old"), new Tag("team", "net"),
new Tag("aws:cloudformation:stack-id", "stack")));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
StackResource r = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID));
@@ -31,6 +31,7 @@ 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;
/**
@@ -91,6 +92,34 @@ class Ec2SecurityGroupCfnProvisionerTest {
verify(ec2, never()).createSecurityGroup(anyString(), anyString(), anyString(), any());
}
@Test
void reservedUpdateTagsFailBeforeChangingRulesOrDeletingExistingTags() throws Exception {
StackResource r = resource("WebSg");
r.setPhysicalId("sg-1");
r.getAttributes().put("GroupId", "sg-1");
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1",
"SecurityGroupIngress": [{"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,
"CidrIp": "10.0.0.0/24"}],
"Tags": [{"Key": "aWs:reserved", "Value": "invalid"}]}
"""), ctx("sg-1")));
assertEquals("InvalidParameterValue", failure.getErrorCode());
assertEquals("sg-1", r.getPhysicalId());
assertEquals(Map.of("GroupId", "sg-1"), r.getAttributes());
verifyNoInteractions(ec2);
}
@Test
void reservedCreateTagsFailBeforeAllocatingASecurityGroup() throws Exception {
assertThrows(AwsException.class, () -> provisioner.provision(resource("WebSg"), props("""
{"GroupDescription": "web tier", "Tags": [{"Key": "aws:reserved", "Value": "invalid"}]}
"""), ctx(null)));
verifyNoInteractions(ec2);
}
@Test
void inlineRuleTheGroupAlreadyCarriesIsNotAuthorizedAgain() throws Exception {
SecurityGroup existing = group("sg-1", "web", "web tier", "vpc-1");
@@ -11,6 +11,7 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
@@ -34,6 +35,59 @@ import static org.mockito.Mockito.when;
class Ec2QueryHandlerTest {
@ParameterizedTest
@CsvSource({
"CreateVpc,vpc", "CreateSubnet,subnet", "CreateSecurityGroup,security-group",
"CreateInternetGateway,internet-gateway", "CreateRouteTable,route-table",
"CreateCapacityReservation,capacity-reservation", "AllocateHosts,dedicated-host",
"AllocateAddress,elastic-ip", "AuthorizeSecurityGroupIngress,security-group-rule",
"AuthorizeSecurityGroupEgress,security-group-rule", "RunInstances,instance",
"RunInstances,network-interface", "CreateVolume,volume",
"RequestSpotInstances,spot-instances-request", "RequestSpotInstances,instance"
})
void rejectsReservedCreationTagsBeforeAllocatingResources(String action, String resourceType) {
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(prefix + ".1.ResourceType", resourceType);
params.putSingle(prefix + ".1.Tag.1.Key", "Name");
params.putSingle(prefix + ".1.Tag.1.Value", "valid");
params.putSingle(prefix + ".1.Tag.2.Key", "aWs:reserved");
params.putSingle(prefix + ".1.Tag.2.Value", "invalid");
Response response = handler(service).handle(action, params, "us-east-1");
assertEquals(400, response.getStatus());
String code = List.of("vpc", "subnet", "security-group-rule", "spot-instances-request")
.contains(resourceType)
? "InvalidParameter" : "InvalidParameterValue";
assertTrue(response.getEntity().toString().contains("<Code>" + code + "</Code>"));
assertTrue(response.getEntity().toString().contains("reserved for internal use"));
verifyNoInteractions(service);
}
}
@ParameterizedTest
@ValueSource(strings = {"CreateLaunchTemplate", "CreateLaunchTemplateVersion"})
void rejectsReservedNestedTemplateTagsBeforeCreatingATemplateOrVersion(String action) {
Ec2Service service = mock(Ec2Service.class);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("LaunchTemplateName", "test");
params.putSingle("LaunchTemplateId", "lt-test");
params.putSingle("LaunchTemplateData.TagSpecification.1.ResourceType", "instance");
params.putSingle("LaunchTemplateData.TagSpecification.1.Tag.1.Key", "aws:reserved");
Response response = handler(service).handle(action, params, "us-east-1");
assertEquals(400, response.getStatus());
assertTrue(response.getEntity().toString().contains("<Code>InvalidTagKey.Malformed</Code>"));
verifyNoInteractions(service);
}
@ParameterizedTest
@ValueSource(strings = {"TagSpecification", "TagSpecifications"})
void normalizesValuelessCreateSubnetTagsBeforeMutation(String prefix) {
@@ -105,6 +105,61 @@ import static org.mockito.Mockito.when;
class Ec2ServiceTest {
@ParameterizedTest
@CsvSource({
"false, aws:autoscaling:groupName", "true, aws:autoscaling:groupName",
"false, AWS:custom", "true, AWS:custom",
"false, aWs:custom", "true, aWs:custom"
})
void userTagMutationsRejectAwsKeysBeforeChangingAnyResource(boolean delete, String key) {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
List<Tag> original = List.of(new Tag("aws:autoscaling:groupName", "group"), new Tag("env", "original"));
List<String> ids = service.runInstances("us-east-1", "ami-test", "t3.micro",
2, 2, null, List.of(), null, null, original, null, null)
.getInstances().stream().map(Instance::getInstanceId).toList();
List<Tag> changes = List.of(new Tag("env", delete ? null : "changed"), new Tag(key, "spoofed"));
AwsException error = assertThrows(AwsException.class, () -> {
if (delete) {
service.deleteTags("us-east-1", ids, changes);
} else {
service.createTags("us-east-1", ids, changes);
}
});
assertEquals("InvalidParameterValue", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("Value ( " + key + " ) for parameter key is invalid. "
+ "Tag keys starting with 'aws:' are reserved for internal use", error.getMessage());
for (Reservation reservation : service.describeInstances("us-east-1", ids, Map.of())) {
for (Instance instance : reservation.getInstances()) {
assertEquals(original, instance.getTags());
}
}
}
@Test
void deletingAllUserTagsPreservesTheAutoscalingMembershipTag() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
Tag membership = new Tag("aws:autoscaling:groupName", "group");
String id = service.runInstances("us-east-1", "ami-test", "t3.micro",
1, 1, null, List.of(), null, null,
List.of(membership, new Tag("env", "original")), null, null)
.getInstances().getFirst().getInstanceId();
service.createTags("us-east-1", List.of(id), List.of(new Tag("env", "updated")));
service.deleteTags("us-east-1", List.of(id), List.of());
Instance instance = service.describeInstances("us-east-1", List.of(id), Map.of())
.getFirst().getInstances().getFirst();
assertEquals(List.of(membership), instance.getTags());
}
@Test
void createAndDescribeVpcsDoNotContactDockerEvenOnFirstUse() {
EmulatorConfig config = mockConfig(false);
@@ -1759,7 +1759,7 @@ class EksServiceTest {
String defaultVpc = Ec2Service.defaultVpcId("us-east-1");
doThrow(new RuntimeException("Simulated tagging failure"))
.when(spyEc2).createTags(any(), any(), any());
.when(spyEc2).createSystemTags(any(), any(), any());
StorageFactory storageFactory = fixedStorageFactory(new InMemoryStorage<>());
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");