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

@@ -0,0 +1,116 @@
"""Reserved tag validation checked against live AWS on 2026-10-13 and 2026-10-14."""
import uuid
from contextlib import ExitStack
import pytest
from botocore.exceptions import ClientError
def test_reserved_tags_reject_atomically_before_allocation_and_mutation(ec2_client, aws_config):
name = "reserved-tags-" + uuid.uuid4().hex[:12]
with ExitStack() as cleanup:
vpc = ec2_client.create_vpc(CidrBlock="10.236.0.0/24")["Vpc"]["VpcId"]
cleanup.callback(ec2_client.delete_vpc, VpcId=vpc)
subnet = ec2_client.create_subnet(
VpcId=vpc, CidrBlock="10.236.0.0/26",
AvailabilityZone=aws_config["region_name"] + "a")["Subnet"]["SubnetId"]
cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet)
image = ec2_client.register_image(
Name=name, Architecture="x86_64", RootDeviceName="/dev/sda1")["ImageId"]
cleanup.callback(ec2_client.deregister_image, ImageId=image)
filters = [{"Name": "subnet-id", "Values": [subnet]}]
before_instances = ec2_client.describe_instances(Filters=filters)["Reservations"]
before_interfaces = ec2_client.describe_network_interfaces(Filters=filters)["NetworkInterfaces"]
with pytest.raises(ClientError) as error:
ec2_client.run_instances(
ImageId=image, InstanceType="t3.nano", SubnetId=subnet, MinCount=1, MaxCount=1,
TagSpecifications=[{"ResourceType": "network-interface", "Tags": [
{"Key": "Name", "Value": name}, {"Key": "aWs:reserved", "Value": "invalid"},
]}])
assert error.value.response["Error"] == {
"Code": "InvalidParameterValue",
"Message": "Tag keys starting with 'aws:' are reserved for internal use",
}
assert ec2_client.describe_instances(Filters=filters)["Reservations"] == before_instances
assert ec2_client.describe_network_interfaces(Filters=filters)["NetworkInterfaces"] == before_interfaces
instance = ec2_client.run_instances(
ImageId=image, InstanceType="t3.nano", SubnetId=subnet, MinCount=1, MaxCount=1,
TagSpecifications=[{"ResourceType": "instance", "Tags": [
{"Key": "Name", "Value": name},
]}])["Instances"][0]["InstanceId"]
cleanup.callback(ec2_client.terminate_instances, InstanceIds=[instance])
for operation in (ec2_client.create_tags, ec2_client.delete_tags):
for key in ("aws:autoscaling:groupName", "AWS:custom", "aWs:custom"):
with pytest.raises(ClientError) as error:
operation(Resources=[instance], Tags=[
{"Key": "Name", "Value": "changed" if operation == ec2_client.create_tags else name},
{"Key": key, "Value": "spoofed"},
])
assert error.value.response["Error"]["Code"] == "InvalidParameterValue"
assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
assert error.value.response["Error"]["Message"] == (
f"Value ( {key} ) for parameter key is invalid. "
"Tag keys starting with 'aws:' are reserved for internal use"
)
tags = ec2_client.describe_tags(
Filters=[{"Name": "resource-id", "Values": [instance]}])["Tags"]
assert {tag["Key"]: tag["Value"] for tag in tags} == {"Name": name}
for args in ({"Tags": []}, {}):
ec2_client.create_tags(Resources=[instance], Tags=[{"Key": "Name", "Value": name}])
ec2_client.delete_tags(Resources=[instance], **args)
assert not ec2_client.describe_tags(
Filters=[{"Name": "resource-id", "Values": [instance]}])["Tags"]
@pytest.mark.parametrize("key", ["aws:reserved", "AWS:reserved", "aWs:reserved"])
def test_volumes_and_spot_requests_reject_reserved_tags(ec2_client, aws_config, key):
name = "reserved-creation-" + uuid.uuid4().hex[:12]
filters = [{"Name": "tag:Name", "Values": [name]}]
tags = [{"Key": "Name", "Value": name}, {"Key": key, "Value": "invalid"}]
with pytest.raises(ClientError) as error:
ec2_client.create_volume(
AvailabilityZone=aws_config["region_name"] + "a", Size=1, VolumeType="gp3",
TagSpecifications=[{"ResourceType": "volume", "Tags": tags}])
assert error.value.response["Error"]["Code"] == "InvalidParameterValue"
assert ec2_client.describe_volumes(Filters=filters)["Volumes"] == []
with pytest.raises(ClientError) as error:
ec2_client.request_spot_instances(
InstanceCount=1, Type="one-time",
LaunchSpecification={"ImageId": "ami-00000000000000000", "InstanceType": "t3.nano"},
TagSpecifications=[{"ResourceType": "spot-instances-request", "Tags": tags}])
assert error.value.response["Error"]["Code"] == "InvalidParameter"
assert ec2_client.describe_spot_instance_requests(Filters=filters)["SpotInstanceRequests"] == []
def test_nested_launch_template_reserved_prefix_is_case_sensitive(ec2_client):
name = "reserved-template-" + uuid.uuid4().hex[:12]
def data(key):
return {"InstanceType": "t3.nano",
"TagSpecifications": [{"ResourceType": "instance",
"Tags": [{"Key": key, "Value": "test"}]}]}
with pytest.raises(ClientError) as error:
ec2_client.create_launch_template(LaunchTemplateName=name, LaunchTemplateData=data("aws:reserved"))
assert error.value.response["Error"]["Code"] == "InvalidTagKey.Malformed"
with pytest.raises(ClientError) as error:
ec2_client.describe_launch_templates(LaunchTemplateNames=[name])
assert error.value.response["Error"]["Code"] == "InvalidLaunchTemplateName.NotFoundException"
template = ec2_client.create_launch_template(
LaunchTemplateName=name, LaunchTemplateData=data("Name"))["LaunchTemplate"]["LaunchTemplateId"]
try:
with pytest.raises(ClientError) as error:
ec2_client.create_launch_template_version(
LaunchTemplateId=template, LaunchTemplateData=data("aws:reserved"))
assert error.value.response["Error"]["Code"] == "InvalidTagKey.Malformed"
versions = ec2_client.describe_launch_template_versions(LaunchTemplateId=template)["LaunchTemplateVersions"]
assert [version["VersionNumber"] for version in versions] == [1]
for key in ("AWS:reserved", "aWs:reserved"):
version = ec2_client.create_launch_template_version(
LaunchTemplateId=template, LaunchTemplateData=data(key))["LaunchTemplateVersion"]
assert version["LaunchTemplateData"]["TagSpecifications"] == data(key)["TagSpecifications"]
finally:
ec2_client.delete_launch_template(LaunchTemplateId=template)
+8
View File
@@ -300,6 +300,14 @@ that publish those images.
| DeleteTags | Removes tags from supported EC2 resources. |
| DescribeTags | Lists tags stored for EC2 resources. |
Public tag mutations reject keys beginning with `aws:` regardless of ASCII case.
An empty `DeleteTags` tag list removes user tags and preserves AWS-managed tags.
CloudFormation tag updates and rollbacks likewise leave AWS-managed tags intact.
Instance and security-group templates validate desired tags before changing resource properties
or deleting old tags. Volume and Spot request creation also reject reserved keys before allocation.
Nested launch-template tags follow AWS's case-sensitive check: `aws:` is rejected with
`InvalidTagKey.Malformed`, while `AWS:` and mixed-case prefixes can be stored in template versions.
### Internet Gateways
| Action | Description |
@@ -54,6 +54,8 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
List<Tag> tags = Ec2Tags.validatedTags(desiredTags);
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
CloudFormationTemplateEngine engine = ctx.engine();
String region = ctx.region();
@@ -115,22 +117,11 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
publishInstanceAttributes(r, current);
storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone);
putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn);
Ec2Tags.reconcile(ec2Service, region, current.getInstanceId(), ctx.resolveTags(props, "Tags"));
Ec2Tags.reconcile(ec2Service, region, current.getInstanceId(), desiredTags);
ReplacementCleanup.record(r, ctx, attributesBefore);
return;
}
List<Tag> tags = new ArrayList<>();
JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = engine.resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.add(new Tag(key, engine.resolve(tag.path("Value"))));
}
}
}
// The launch-time public-IP override rides on the primary network
// interface spec; absent means the subnet's MapPublicIpOnLaunch default.
Boolean associatePublicIp = null;
@@ -151,10 +151,14 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
String entityId = prior.path("entityId").asText();
if (prior.has("tags")) {
Map<String, String> priorTags = new LinkedHashMap<>();
prior.get("tags").fields().forEachRemaining(f -> priorTags.put(f.getKey(), f.getValue().asText()));
prior.get("tags").fields().forEachRemaining(f -> {
if (!Ec2Service.isAwsTagKey(f.getKey())) {
priorTags.put(f.getKey(), f.getValue().asText());
}
});
List<Tag> added = new ArrayList<>();
prior.path("appliedKeys").forEach(key -> {
if (!priorTags.containsKey(key.asText())) {
if (!Ec2Service.isAwsTagKey(key.asText()) && !priorTags.containsKey(key.asText())) {
added.add(new Tag(key.asText(), null));
}
});
@@ -279,7 +283,9 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
Map<String, String> desired = ctx.resolveTags(props, "Tags");
Map<String, String> currentTags = new LinkedHashMap<>();
for (Tag tag : current == null ? List.<Tag>of() : current) {
currentTags.put(tag.getKey(), tag.getValue());
if (!Ec2Service.isAwsTagKey(tag.getKey())) {
currentTags.put(tag.getKey(), tag.getValue());
}
}
List<String> stale = ProvisionContext.staleTagKeys(currentTags, desired);
if (reused && ctx.isUpdate() && (!stale.isEmpty() || !desired.equals(currentTags))) {
@@ -62,6 +62,8 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
Ec2Tags.validatedTags(desiredTags);
CloudFormationTemplateEngine engine = ctx.engine();
String region = ctx.region();
String groupName = ctx.resolveOptional(props, "GroupName");
@@ -104,7 +106,7 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
EGRESS_RULES_ATTR,
perms -> ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(), perms),
perms -> ec2Service.revokeSecurityGroupEgress(region, sg.getGroupId(), perms));
Ec2Tags.reconcile(ec2Service, region, sg.getGroupId(), ctx.resolveTags(props, "Tags"));
Ec2Tags.reconcile(ec2Service, region, sg.getGroupId(), desiredTags);
}
@Override
@@ -18,14 +18,24 @@ final class Ec2Tags {
private Ec2Tags() {
}
static List<Tag> validatedTags(Map<String, String> desired) {
List<Tag> tags = desired.entrySet().stream()
.map(entry -> new Tag(entry.getKey(), entry.getValue())).toList();
Ec2Service.validateUserTagKeys(tags);
return tags;
}
/**
* Brings a resource's tags to {@code desired}: removes the keys AWS currently has that the
* template no longer declares, then creates or overwrites the declared ones.
*/
static void reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
List<Tag> add = validatedTags(desired);
Map<String, String> current = new LinkedHashMap<>();
for (Map<String, String> entry : ec2Service.describeTags(region, Map.of("resource-id", List.of(resourceId)))) {
current.put(entry.get("key"), entry.get("value"));
if (!Ec2Service.isAwsTagKey(entry.get("key"))) {
current.put(entry.get("key"), entry.get("value"));
}
}
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
if (!stale.isEmpty()) {
@@ -35,11 +45,7 @@ final class Ec2Tags {
}
ec2Service.deleteTags(region, List.of(resourceId), remove);
}
if (!desired.isEmpty()) {
List<Tag> add = new ArrayList<>();
for (Map.Entry<String, String> entry : desired.entrySet()) {
add.add(new Tag(entry.getKey(), entry.getValue()));
}
if (!add.isEmpty()) {
ec2Service.createTags(region, List.of(resourceId), add);
}
}
@@ -592,6 +592,13 @@ public class Ec2QueryHandler {
}
}
}
if (tags.stream().anyMatch(tag -> Ec2Service.isAwsTagKey(tag.getKey()))) {
String code = switch (resourceType) {
case "vpc", "subnet", "security-group-rule", "spot-instances-request" -> "InvalidParameter";
default -> "InvalidParameterValue";
};
throw new AwsException(code, "Tag keys starting with 'aws:' are reserved for internal use", 400);
}
return tags;
}
@@ -618,8 +625,7 @@ public class Ec2QueryHandler {
// Apply tags supplied inline on a create call (TagSpecification) to the resource, so
// they round-trip on the next Describe* — otherwise the provider sees phantom tag drift.
private void applyResourceTags(MultivaluedMap<String, String> p, String region, String resourceType, String resourceId) {
List<Tag> tagList = parseTagsForResource(p, resourceType);
private void applyResourceTags(List<Tag> tagList, String region, String resourceId) {
if (!tagList.isEmpty()) {
service.createTags(region, List.of(resourceId), tagList);
}
@@ -627,9 +633,7 @@ public class Ec2QueryHandler {
// Each rule gets its own copy so mutating one rule's tag list can never leak into the
// others authorized in the same batch, and the copy also feeds the response XML.
private void applySecurityGroupRuleTags(MultivaluedMap<String, String> p, String region,
List<SecurityGroupRule> rules) {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
private void applySecurityGroupRuleTags(List<Tag> ruleTags, String region, List<SecurityGroupRule> rules) {
if (ruleTags.isEmpty()) {
return;
}
@@ -782,25 +786,8 @@ public class Ec2QueryHandler {
// Parse TagSpecifications. AWS applies each specification to exactly the resource
// type it names, so the interfaces RunInstances creates are tagged only by a
// ResourceType=network-interface specification - never by the instance's own tags.
List<Tag> instanceTags = new ArrayList<>();
List<Tag> networkInterfaceTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
List<Tag> target = switch (resType) {
case "instance" -> instanceTags;
case "network-interface" -> networkInterfaceTags;
default -> null;
};
if (target != null) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
target.add(creationTag(k, v));
}
}
}
List<Tag> instanceTags = parseTagsForResource(p, "instance");
List<Tag> networkInterfaceTags = parseTagsForResource(p, "network-interface");
// Absent fields stay null so the launch default, or the launch template's value, applies.
LaunchTemplateData.MetadataOptions metadataOptions = parseMetadataOptions(p, "MetadataOptions.");
@@ -1565,23 +1552,9 @@ public class Ec2QueryHandler {
private Response handleCreateVpc(MultivaluedMap<String, String> p, String region) {
String cidrBlock = p.getFirst("CidrBlock");
boolean amazonProvidedIpv6 = "true".equalsIgnoreCase(p.getFirst("AmazonProvidedIpv6CidrBlock"));
List<Tag> vpcTags = parseTagsForResource(p, "vpc");
Vpc vpc = service.createVpc(region, cidrBlock, false, amazonProvidedIpv6, p.getFirst("InstanceTenancy"));
List<Tag> vpcTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
if ("vpc".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
vpcTags.add(creationTag(k, v));
}
}
}
if (!vpcTags.isEmpty()) {
service.createTags(region, List.of(vpc.getVpcId()), vpcTags);
}
applyResourceTags(vpcTags, region, vpc.getVpcId());
XmlBuilder xml = new XmlBuilder()
.start("CreateVpcResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3148,11 +3121,12 @@ public class Ec2QueryHandler {
// ─── Security Group handlers ───────────────────────────────────────────────
private Response handleCreateSecurityGroup(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "security-group");
String groupName = requireParameter(p, "GroupName");
String description = requireParameter(p, "GroupDescription");
String vpcId = p.getFirst("VpcId");
SecurityGroup sg = service.createSecurityGroup(region, groupName, description, vpcId);
applyResourceTags(p, region, "security-group", sg.getGroupId());
applyResourceTags(resourceTags, region, sg.getGroupId());
XmlBuilder xml = new XmlBuilder()
.start("CreateSecurityGroupResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3219,10 +3193,11 @@ public class Ec2QueryHandler {
}
private Response handleAuthorizeSecurityGroupIngress(MultivaluedMap<String, String> p, String region) {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<SecurityGroupRule> rules = service.authorizeSecurityGroupIngress(region, groupId, perms);
applySecurityGroupRuleTags(p, region, rules);
applySecurityGroupRuleTags(ruleTags, region, rules);
XmlBuilder xml = new XmlBuilder()
.start("AuthorizeSecurityGroupIngressResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3236,10 +3211,11 @@ public class Ec2QueryHandler {
}
private Response handleAuthorizeSecurityGroupEgress(MultivaluedMap<String, String> p, String region) {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<SecurityGroupRule> rules = service.authorizeSecurityGroupEgress(region, groupId, perms);
applySecurityGroupRuleTags(p, region, rules);
applySecurityGroupRuleTags(ruleTags, region, rules);
XmlBuilder xml = new XmlBuilder()
.start("AuthorizeSecurityGroupEgressResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3711,8 +3687,9 @@ public class Ec2QueryHandler {
// ─── Internet Gateway handlers ────────────────────────────────────────────
private Response handleCreateInternetGateway(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "internet-gateway");
InternetGateway igw = service.createInternetGateway(region);
applyResourceTags(p, region, "internet-gateway", igw.getInternetGatewayId());
applyResourceTags(resourceTags, region, igw.getInternetGatewayId());
XmlBuilder xml = new XmlBuilder()
.start("CreateInternetGatewayResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3754,9 +3731,10 @@ public class Ec2QueryHandler {
// ─── Route Table handlers ─────────────────────────────────────────────────
private Response handleCreateRouteTable(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "route-table");
String vpcId = p.getFirst("VpcId");
RouteTable rt = service.createRouteTable(region, vpcId);
applyResourceTags(p, region, "route-table", rt.getRouteTableId());
applyResourceTags(resourceTags, region, rt.getRouteTableId());
XmlBuilder xml = new XmlBuilder()
.start("CreateRouteTableResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -4094,6 +4072,7 @@ public class Ec2QueryHandler {
// ─── Capacity Reservation handlers ────────────────────────────────────────
private Response handleCreateCapacityReservation(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "capacity-reservation");
CapacityReservation reservation = service.createCapacityReservation(
region,
p.getFirst("InstanceType"),
@@ -4109,7 +4088,7 @@ public class Ec2QueryHandler {
p.getFirst("InstanceMatchCriteria"),
p.getFirst("OutpostArn"),
p.getFirst("PlacementGroupArn"));
applyResourceTags(p, region, "capacity-reservation", reservation.getCapacityReservationId());
applyResourceTags(resourceTags, region, reservation.getCapacityReservationId());
XmlBuilder xml = new XmlBuilder()
.start("CreateCapacityReservationResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -4178,6 +4157,7 @@ public class Ec2QueryHandler {
// ─── Dedicated Host handlers ──────────────────────────────────────────────
private Response handleAllocateHosts(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "dedicated-host");
List<String> assetIds = getList(p, "AssetId");
List<Host> allocated = service.allocateHosts(
region,
@@ -4195,7 +4175,7 @@ public class Ec2QueryHandler {
.elem("requestId", UUID.randomUUID().toString())
.start("hostIdSet");
for (Host host : allocated) {
applyResourceTags(p, region, "dedicated-host", host.getHostId());
applyResourceTags(resourceTags, region, host.getHostId());
xml.elem("item", host.getHostId());
}
xml.end("hostIdSet").end("AllocateHostsResponse");
@@ -4312,8 +4292,9 @@ public class Ec2QueryHandler {
// ─── Elastic IP handlers ──────────────────────────────────────────────────
private Response handleAllocateAddress(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "elastic-ip");
Address addr = service.allocateAddress(region);
applyResourceTags(p, region, "elastic-ip", addr.getAllocationId());
applyResourceTags(resourceTags, region, addr.getAllocationId());
XmlBuilder xml = new XmlBuilder()
.start("AllocateAddressResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -5801,6 +5782,11 @@ public class Ec2QueryHandler {
if (key == null) {
break;
}
if (key.startsWith("aws:")) {
throw new AwsException("InvalidTagKey.Malformed",
"The tag key ‘" + key + "’ is not valid. "
+ "Tag keys starting with 'aws:' are reserved for internal use.", 400);
}
tagList.add(creationTag(key, p.getFirst(base + ".Tag." + j + ".Value")));
}
specs.add(new LaunchTemplateData.TagSpecification(resourceType, tagList));
@@ -6018,19 +6004,7 @@ public class Ec2QueryHandler {
String snapshotId = p.getFirst("SnapshotId");
List<Tag> volumeTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
if ("volume".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
volumeTags.add(creationTag(k, v));
}
}
}
List<Tag> volumeTags = parseTagsForResource(p, "volume");
Volume vol = service.createVolume(region, availabilityZone, volumeType, size,
encrypted, iops, throughput, snapshotId, volumeTags);
@@ -6287,28 +6261,8 @@ public class Ec2QueryHandler {
String userData = Ec2UserDataDecoder.decode(userDataEncoded);
String iamInstanceProfileArn = p.getFirst("LaunchSpecification.IamInstanceProfile.Arn");
// Parse TagSpecifications
List<Tag> spotRequestTags = new ArrayList<>();
List<Tag> instanceTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
if ("spot-instances-request".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
spotRequestTags.add(creationTag(k, v));
}
} else if ("instance".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
instanceTags.add(creationTag(k, v));
}
}
}
List<Tag> spotRequestTags = parseTagsForResource(p, "spot-instances-request");
List<Tag> instanceTags = parseTagsForResource(p, "instance");
List<SpotInstanceRequest> requests = service.requestSpotInstances(region, spotPrice, instanceCount,
type, productDescription, imageId, instanceType, keyName, subnetId, securityGroupIds, userData, iamInstanceProfileArn,
@@ -7785,6 +7785,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// ─── Tags ──────────────────────────────────────────────────────────────────
public void createTags(String region, List<String> resourceIds, List<Tag> tagList) {
validateUserTagKeys(tagList);
createSystemTags(region, resourceIds, tagList);
}
/** Service-owned tags, separate from the public EC2 CreateTags operation. */
public void createSystemTags(String region, List<String> resourceIds, List<Tag> tagList) {
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
withTopologyLockIfNeeded(region, resourceId, () -> {
@@ -7822,6 +7828,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public void deleteTags(String region, List<String> resourceIds, List<Tag> tagList) {
validateUserTagKeys(tagList);
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
withTopologyLockIfNeeded(region, resourceId, () -> {
@@ -7832,6 +7839,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
});
if (stored != null) {
List<Tag> existing = new ArrayList<>(stored);
if (tagList.isEmpty()) {
existing.removeIf(tag -> !isAwsTagKey(tag.getKey()));
}
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey())
&& (tag.getValue() == null || tag.getValue().equals(t.getValue())));
@@ -7844,6 +7854,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
public static void validateUserTagKeys(List<Tag> tagList) {
for (Tag tag : tagList) {
if (isAwsTagKey(tag.getKey())) {
throw new AwsException("InvalidParameterValue",
"Value ( " + tag.getKey() + " ) for parameter key is invalid. "
+ "Tag keys starting with 'aws:' are reserved for internal use", 400);
}
}
}
public static boolean isAwsTagKey(String key) {
return key != null && key.toLowerCase(Locale.ROOT).startsWith("aws:");
}
private void updateResourceTags(String region, String resourceId, List<Tag> tagList) {
String storeKey = key(region, resourceId);
Instance inst = instances.get(storeKey).orElse(null);
@@ -444,7 +444,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
new Tag("kubernetes.io/cluster/" + clusterName, "owned"),
new Tag("aws:eks:cluster-name", clusterName)
);
ec2Service.createTags(region, List.of(sg.getGroupId()), tags);
ec2Service.createSystemTags(region, List.of(sg.getGroupId()), tags);
UserIdGroupPair selfPair = new UserIdGroupPair();
selfPair.setGroupId(sg.getGroupId());
@@ -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");