mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cloudformation): apply Tags, DNS attributes and InstanceTenancy on AWS::EC2::VPC (#5224)
* fix(cloudformation): apply Tags, DNS attributes and InstanceTenancy on AWS::EC2::VPC Ec2VpcCfnProvisioner read only CidrBlock, so a VPC from a template had no tags and DescribeVpcs with a tag:Name filter (CDK Vpc.from_lookup) never found it. EnableDnsSupport, EnableDnsHostnames and InstanceTenancy were dropped as well. Tags are now reconciled through Ec2Tags on create and on update (keys removed from the template are deleted), the DNS attributes are applied with the AWS defaults when omitted, and InstanceTenancy is passed to CreateVpc, with the dedicated-to-default change applied in place through a new modifyVpcTenancy and any other change treated as a replacement. CreateVpc on the EC2 Query API now honours InstanceTenancy too so the two paths agree. Fn::GetAtt gains CidrBlockAssociations, DefaultNetworkAcl and Ipv6CidrBlocks. * fix(cloudformation): validate VPC tenancy and treat blank DNS properties as omitted EnableDnsSupport/EnableDnsHostnames resolving blank (Fn::If with AWS::NoValue) now take the AWS default instead of false. CreateVpc rejects an InstanceTenancy outside default/dedicated/host with InvalidParameterValue, and ModifyVpcTenancy requires the VPC to be dedicated, as on AWS; the provisioner replaces on any other tenancy change. The integration test reads outputs with XmlPath, and the query-handler test stub follows the new createVpc overload. * style(cloudformation): no final on the VPC local; compare tag sets unordered in the test * fix(ec2): CreateVpc accepts default or dedicated tenancy only * fix(ec2): share the enumerated-parameter check for VPC tenancy and cover it on the Query API requireMetadataOptionValue becomes requireParameterValue and requireVpcTenancy uses it, so the InvalidParameterValue wording lives in one place. A Query API test sends InstanceTenancy to CreateVpc and reads it back from DescribeVpcs, the provisioner test no longer turns DNS hostnames on with DNS support off, and the CreateVpc docs row names the accepted tenancies. * fix(ec2): only an absent InstanceTenancy defaults; order the test static imports
This commit is contained in:
1 parent
34c11b8981
commit
2cade5cd21
10 files changed
+501
-34
No files matched your search
+73
-11
@@ -4,21 +4,41 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VpcCidrBlockAssociation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* CloudFormation provisioning for {@code AWS::EC2::VPC}. Extracted verbatim from
|
||||
* the former CloudFormation monolith as part of the per-service decomposition.
|
||||
* CloudFormation provisioning for {@code AWS::EC2::VPC}.
|
||||
*
|
||||
* <p>Property and attribute contract follows
|
||||
* https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html:
|
||||
* {@code CidrBlock} is create-only and a change replaces the VPC; {@code InstanceTenancy} is
|
||||
* applied in place only for the {@code dedicated} to {@code default} direction AWS allows, any
|
||||
* other change replaces; {@code EnableDnsSupport}, {@code EnableDnsHostnames} and {@code Tags} are
|
||||
* applied in place on every provision. {@code Ref} is the VPC id; {@code Fn::GetAtt} exposes
|
||||
* VpcId, CidrBlock, CidrBlockAssociations, DefaultNetworkAcl, DefaultSecurityGroup and
|
||||
* Ipv6CidrBlocks. List-valued attributes are comma-joined like the other provisioners' lists.
|
||||
*
|
||||
* <p>Tags are reconciled to the template's {@code Tags} the way {@link Ec2Tags} does for the
|
||||
* instance and security-group provisioners: a key the template dropped is deleted. Stack-level
|
||||
* tags and the {@code aws:cloudformation:*} system tags are not applied here, matching every other
|
||||
* EC2 provisioner in this package.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String DEFAULT_TENANCY = "default";
|
||||
private static final String DEDICATED_TENANCY = "dedicated";
|
||||
|
||||
private final Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
@@ -33,20 +53,53 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String region = ctx.region();
|
||||
String cidr = ctx.resolveOptional(props, "CidrBlock");
|
||||
Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, ctx.region());
|
||||
final Vpc vpc = reconciled != null ? reconciled : ec2Service.createVpc(ctx.region(), cidr, false);
|
||||
r.setPhysicalId(vpc.getVpcId());
|
||||
r.getAttributes().put("VpcId", vpc.getVpcId());
|
||||
String tenancy = ctx.resolveOptional(props, "InstanceTenancy");
|
||||
String desiredTenancy = tenancy == null || tenancy.isBlank() ? DEFAULT_TENANCY : tenancy;
|
||||
Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, desiredTenancy, region);
|
||||
Vpc vpc = reconciled != null
|
||||
? reconciled
|
||||
: ec2Service.createVpc(region, cidr, false, false, desiredTenancy);
|
||||
String vpcId = vpc.getVpcId();
|
||||
if (reconciled != null && isDedicatedToDefault(vpc, desiredTenancy)) {
|
||||
ec2Service.modifyVpcTenancy(region, vpcId, desiredTenancy);
|
||||
}
|
||||
|
||||
// AWS defaults for a non-default VPC: DnsSupport on, DnsHostnames off. A template that
|
||||
// omits the property (or resolves it to AWS::NoValue, which the engine renders blank) gets
|
||||
// the default, as CloudFormation applies it on every update too.
|
||||
String dnsSupport = ctx.resolveOrDefault(props, "EnableDnsSupport", "true");
|
||||
String dnsHostnames = ctx.resolveOrDefault(props, "EnableDnsHostnames", "false");
|
||||
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport",
|
||||
String.valueOf(Boolean.parseBoolean(dnsSupport)));
|
||||
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames",
|
||||
String.valueOf(Boolean.parseBoolean(dnsHostnames)));
|
||||
|
||||
Ec2Tags.reconcile(ec2Service, region, vpcId, ctx.resolveTags(props, "Tags"));
|
||||
|
||||
r.setPhysicalId(vpcId);
|
||||
r.getAttributes().put("VpcId", vpcId);
|
||||
if (vpc.getCidrBlock() != null) {
|
||||
r.getAttributes().put("CidrBlock", vpc.getCidrBlock());
|
||||
}
|
||||
r.getAttributes().put("CidrBlockAssociations", vpc.getCidrBlockAssociationSet().stream()
|
||||
.map(VpcCidrBlockAssociation::getAssociationId)
|
||||
.collect(Collectors.joining(",")));
|
||||
r.getAttributes().put("Ipv6CidrBlocks", vpc.getIpv6CidrBlockAssociationSet().stream()
|
||||
.map(VpcIpv6CidrBlockAssociation::getIpv6CidrBlock)
|
||||
.collect(Collectors.joining(",")));
|
||||
// Fn::GetAtt DefaultSecurityGroup — CDK's Custom::VpcRestrictDefaultSG handler
|
||||
// depends on it resolving to the VPC's default security group id.
|
||||
ec2Service.describeSecurityGroups(ctx.region(), List.of(), List.of("default"), Map.of()).stream()
|
||||
.filter(sg -> vpc.getVpcId().equals(sg.getVpcId()))
|
||||
ec2Service.describeSecurityGroups(region, List.of(), List.of("default"), Map.of()).stream()
|
||||
.filter(sg -> vpcId.equals(sg.getVpcId()))
|
||||
.findFirst()
|
||||
.ifPresent(sg -> r.getAttributes().put("DefaultSecurityGroup", sg.getGroupId()));
|
||||
ec2Service.describeNetworkAcls(region, List.of(),
|
||||
Map.of("vpc-id", List.of(vpcId), "default", List.of("true"))).stream()
|
||||
.map(NetworkAcl::getNetworkAclId)
|
||||
.findFirst()
|
||||
.ifPresent(aclId -> r.getAttributes().put("DefaultNetworkAcl", aclId));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,14 +108,15 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
* unconditionally would mint a fresh VPC id and silently orphan every subnet, route table and
|
||||
* security group that referenced the old one.
|
||||
*
|
||||
* <p>Returns {@code null} for a fresh create, for a CidrBlock change (which AWS treats as a
|
||||
* replacement), or when the VPC is gone from the backend - the caller then creates.
|
||||
* <p>Returns {@code null} for a fresh create, for a CidrBlock change or an InstanceTenancy
|
||||
* change other than {@code dedicated} to {@code default} (which AWS treats as a replacement),
|
||||
* or when the VPC is gone from the backend - the caller then creates.
|
||||
*
|
||||
* <p>The prior id is the one the context captured, not the one on the {@link StackResource}:
|
||||
* {@code provision} assigns the new id onto that resource as it runs, so a resource-derived
|
||||
* check flips from create to update mid-method.
|
||||
*/
|
||||
private Vpc existingVpcToReconcile(String priorPhysicalId, String cidr, String region) {
|
||||
private Vpc existingVpcToReconcile(String priorPhysicalId, String cidr, String tenancy, String region) {
|
||||
if (priorPhysicalId == null || priorPhysicalId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
@@ -78,9 +132,17 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
&& !CidrCanonicalizer.sameBlock(cidr, existing.getCidrBlock())) {
|
||||
return null;
|
||||
}
|
||||
// ModifyVpcTenancy only goes dedicated -> default; every other tenancy change replaces.
|
||||
if (!tenancy.equals(existing.getInstanceTenancy()) && !isDedicatedToDefault(existing, tenancy)) {
|
||||
return null;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
private static boolean isDedicatedToDefault(Vpc existing, String desiredTenancy) {
|
||||
return DEDICATED_TENANCY.equals(existing.getInstanceTenancy()) && DEFAULT_TENANCY.equals(desiredTenancy);
|
||||
}
|
||||
|
||||
// No delete override: the switch this replaces had no AWS::EC2::VPC delete arm,
|
||||
// so stack teardown leaves the VPC alone. Adding one here would change teardown
|
||||
// behavior beyond the scope of this extraction.
|
||||
|
||||
@@ -1550,7 +1550,7 @@ public class Ec2QueryHandler {
|
||||
private Response handleCreateVpc(MultivaluedMap<String, String> p, String region) {
|
||||
String cidrBlock = p.getFirst("CidrBlock");
|
||||
boolean amazonProvidedIpv6 = "true".equalsIgnoreCase(p.getFirst("AmazonProvidedIpv6CidrBlock"));
|
||||
Vpc vpc = service.createVpc(region, cidrBlock, false, amazonProvidedIpv6);
|
||||
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");
|
||||
|
||||
@@ -4475,10 +4475,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (options == null) {
|
||||
return;
|
||||
}
|
||||
requireMetadataOptionValue("HttpTokens", options.getHttpTokens(), "optional", "required");
|
||||
requireMetadataOptionValue("HttpEndpoint", options.getHttpEndpoint(), "enabled", "disabled");
|
||||
requireMetadataOptionValue("HttpProtocolIpv6", options.getHttpProtocolIpv6(), "enabled", "disabled");
|
||||
requireMetadataOptionValue("InstanceMetadataTags", options.getInstanceMetadataTags(), "enabled", "disabled");
|
||||
requireParameterValue("HttpTokens", options.getHttpTokens(), "optional", "required");
|
||||
requireParameterValue("HttpEndpoint", options.getHttpEndpoint(), "enabled", "disabled");
|
||||
requireParameterValue("HttpProtocolIpv6", options.getHttpProtocolIpv6(), "enabled", "disabled");
|
||||
requireParameterValue("InstanceMetadataTags", options.getInstanceMetadataTags(), "enabled", "disabled");
|
||||
Integer hopLimit = options.getHttpPutResponseHopLimit();
|
||||
if (hopLimit != null && (hopLimit < 1 || hopLimit > 64)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
@@ -4487,7 +4487,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireMetadataOptionValue(String parameter, String value, String... allowed) {
|
||||
/** Rejects a value outside an enumerated parameter's allowed set with EC2's InvalidParameterValue. */
|
||||
private static void requireParameterValue(String parameter, String value, String... allowed) {
|
||||
if (value == null || List.of(allowed).contains(value)) {
|
||||
return;
|
||||
}
|
||||
@@ -4630,6 +4631,26 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
public Vpc createVpc(String region, String requestedCidrBlock, boolean isDefault,
|
||||
boolean amazonProvidedIpv6CidrBlock) {
|
||||
return createVpc(region, requestedCidrBlock, isDefault, amazonProvidedIpv6CidrBlock, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateVpc takes {@code default} or {@code dedicated} only: "The host value cannot be used with
|
||||
* this parameter" (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpc.html).
|
||||
*/
|
||||
private static String requireVpcTenancy(String instanceTenancy) {
|
||||
// Only an absent parameter defaults; a present blank is not one of the enum values.
|
||||
String tenancy = instanceTenancy == null ? "default" : instanceTenancy;
|
||||
requireParameterValue("instanceTenancy", tenancy, "default", "dedicated");
|
||||
return tenancy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param instanceTenancy {@code default} or {@code dedicated} as CreateVpc's
|
||||
* InstanceTenancy parameter; null means {@code default}.
|
||||
*/
|
||||
public Vpc createVpc(String region, String requestedCidrBlock, boolean isDefault,
|
||||
boolean amazonProvidedIpv6CidrBlock, String instanceTenancy) {
|
||||
// AWS stores the CIDR in canonical form: "100.68.0.18/18" becomes "100.68.0.0/18".
|
||||
String cidrBlock = canonicalizeIpv4Cidr(requestedCidrBlock);
|
||||
ensureDefaultResources(region);
|
||||
@@ -4639,6 +4660,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
vpc.setCidrBlock(cidrBlock);
|
||||
vpc.setState("available");
|
||||
vpc.setDefault(isDefault);
|
||||
vpc.setInstanceTenancy(requireVpcTenancy(instanceTenancy));
|
||||
vpc.setOwnerId(callerAccountId());
|
||||
vpc.setRegion(region);
|
||||
vpc.getCidrBlockAssociationSet().add(
|
||||
@@ -4799,6 +4821,27 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
vpcs.put(key(region, vpcId), vpc);
|
||||
}
|
||||
|
||||
/**
|
||||
* ModifyVpcTenancy: only {@code dedicated} to {@code default} is allowed, as on AWS
|
||||
* (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyVpcTenancy.html).
|
||||
*/
|
||||
public void modifyVpcTenancy(String region, String vpcId, String instanceTenancy) {
|
||||
ensureDefaultResources(region);
|
||||
Vpc vpc = getRequiredVpc(region, vpcId);
|
||||
if (!"default".equals(instanceTenancy)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Value (" + instanceTenancy + ") for parameter instanceTenancy is invalid. "
|
||||
+ "Only 'default' is supported.", 400);
|
||||
}
|
||||
if (!"dedicated".equals(vpc.getInstanceTenancy())) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Value (" + instanceTenancy + ") for parameter instanceTenancy is invalid. "
|
||||
+ "The instance tenancy of a VPC can only be changed from 'dedicated' to 'default'.", 400);
|
||||
}
|
||||
vpc.setInstanceTenancy(instanceTenancy);
|
||||
vpcs.put(key(region, vpcId), vpc);
|
||||
}
|
||||
|
||||
public Vpc describeVpcAttribute(String region, String vpcId, String attribute) {
|
||||
ensureDefaultResources(region);
|
||||
Vpc vpc = getRequiredVpc(region, vpcId);
|
||||
|
||||
Reference in new issue
Block a user