diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 869e7b3a11..c1ec1b6e81 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -220,7 +220,7 @@ Floci seeds the following resources on first use in each region so Terraform, th | Action | Description | |--------|-------------| -| CreateVpc | Creates a VPC with the requested CIDR block. | +| CreateVpc | Creates a VPC with the requested CIDR block. `InstanceTenancy` accepts `default` or `dedicated`; `host` is rejected with `InvalidParameterValue`, as on AWS. | | DescribeVpcs | Lists or returns stored VPCs. | | DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, or an attached internet gateway. Instances, NAT gateways and other subnet-resident resources are not checked. | | ModifyVpcAttribute | Updates supported VPC attributes. | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java index 26b52c0d47..782f42293d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java @@ -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}. + * + *

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. + * + *

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. * - *

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. + *

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. * *

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. diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 67f7f3fa7f..0dc73eced0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -1550,7 +1550,7 @@ public class Ec2QueryHandler { private Response handleCreateVpc(MultivaluedMap 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 vpcTags = new ArrayList<>(); for (int i = 1; ; i++) { String resType = p.getFirst("TagSpecification." + i + ".ResourceType"); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 694969d487..4ab286462c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcPropertiesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcPropertiesIntegrationTest.java new file mode 100644 index 0000000000..a1f18cddd8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcPropertiesIntegrationTest.java @@ -0,0 +1,148 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@code AWS::EC2::VPC} applies Tags, EnableDnsHostnames/EnableDnsSupport and InstanceTenancy + * to the VPC it creates, so DescribeVpcs with a {@code tag:Name} filter (what CDK's + * {@code Vpc.fromLookup} issues) finds it, and an UpdateStack replaces the tag set in place. + */ +@QuarkusTest +class CloudFormationVpcPropertiesIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-3/cloudformation/aws4_request"; + private static final String EC2_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-3/ec2/aws4_request"; + + private static String template(String name, String extraTags) { + return """ + { + "Resources": { + "Vpc": { + "Type": "AWS::EC2::VPC", + "Properties": { + "CidrBlock": "10.44.0.0/16", + "EnableDnsHostnames": true, + "EnableDnsSupport": true, + "InstanceTenancy": "dedicated", + "Tags": [{"Key": "Name", "Value": "%s"}%s] + } + } + }, + "Outputs": { + "VpcId": {"Value": {"Ref": "Vpc"}}, + "Acl": {"Value": {"Fn::GetAtt": ["Vpc", "DefaultNetworkAcl"]}}, + "Assoc": {"Value": {"Fn::GetAtt": ["Vpc", "CidrBlockAssociations"]}} + } + } + """.formatted(name, extraTags); + } + + @Test + void vpcTagsAndAttributesAreAppliedOnCreateAndReplacedOnUpdate() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-vpc-props-" + suffix; + String name = "lookup-vpc-" + suffix; + + cfn("CreateStack", stackName, template(name, ", {\"Key\": \"team\", \"Value\": \"blue\"}")) + .statusCode(200); + String described = describeStacks(stackName, "CREATE_COMPLETE"); + String vpcId = output(described, "VpcId"); + assertTrue(vpcId.startsWith("vpc-"), "stack output should carry the vpc id: " + vpcId); + assertTrue(output(described, "Acl").startsWith("acl-"), "DefaultNetworkAcl should resolve: " + described); + assertTrue(output(described, "Assoc").startsWith("vpc-cidr-assoc-"), + "CidrBlockAssociations should resolve: " + described); + + given() + .header("Authorization", EC2_AUTH) + .formParam("Action", "DescribeVpcs") + .formParam("Filter.1.Name", "tag:Name") + .formParam("Filter.1.Value.1", name) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeVpcsResponse.vpcSet.item.vpcId", equalTo(vpcId)) + .body("DescribeVpcsResponse.vpcSet.item.instanceTenancy", equalTo("dedicated")) + .body("DescribeVpcsResponse.vpcSet.item.tagSet.item.find { it.key == 'team' }.value", equalTo("blue")); + + given() + .header("Authorization", EC2_AUTH) + .formParam("Action", "DescribeVpcAttribute") + .formParam("VpcId", vpcId) + .formParam("Attribute", "enableDnsHostnames") + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeVpcAttributeResponse.enableDnsHostnames.value", equalTo("true")); + + // Update: Name changes, team is dropped. CloudFormation replaces the tag set. + cfn("UpdateStack", stackName, template(name + "-v2", "")).statusCode(200); + describeStacks(stackName, "UPDATE_COMPLETE"); + + given() + .header("Authorization", EC2_AUTH) + .formParam("Action", "DescribeVpcs") + .formParam("Filter.1.Name", "tag:Name") + .formParam("Filter.1.Value.1", name + "-v2") + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeVpcsResponse.vpcSet.item.vpcId", equalTo(vpcId)) + .body(not(containsString("team"))); + + given() + .header("Authorization", EC2_AUTH) + .formParam("Action", "DescribeVpcs") + .formParam("Filter.1.Name", "tag:Name") + .formParam("Filter.1.Value.1", name) + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(vpcId))); + } + + private static ValidatableResponse cfn(String action, String stackName, String template) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then(); + } + + private static String describeStacks(String stackName, String expectedStatus) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + expectedStatus + "")) + .extract().asString(); + } + + private static String output(String describeStacksXml, String key) { + return XmlPath.from(describeStacksXml).getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member" + + ".Outputs.member.find { it.OutputKey == '" + key + "' }.OutputValue"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java index b765b864a0..dbd19f7bd4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java @@ -5,18 +5,26 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; 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.SecurityGroup; +import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.model.Vpc; +import io.github.hectorvent.floci.services.ec2.model.VpcCidrBlockAssociation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatcher; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -60,6 +68,17 @@ class Ec2VpcCfnProvisionerTest { return v; } + /** Matches a tag list by its {@code key=value} pairs as a set; {@link Tag} has no equals. */ + private static ArgumentMatcher> tags(String... expected) { + return actual -> actual != null + && actual.stream().map(t -> t.getKey() + "=" + t.getValue()).collect(Collectors.toSet()) + .equals(Set.of(expected)); + } + + private void stubCreate(Vpc created) { + when(ec2.createVpc(anyString(), anyString(), anyBoolean(), anyBoolean(), anyString())).thenReturn(created); + } + /** * Provisions the way the engine does: an update arrives with the prior id on both the context * and the resource, so a provisioner reading the wrong one still looks correct here. The @@ -82,12 +101,20 @@ class Ec2VpcCfnProvisionerTest { @Test void refIsTheVpcIdAndGetAttExposesTheDocumentedAttributes() { - when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16")); + Vpc created = vpc("vpc-new", "10.0.0.0/16"); + created.getCidrBlockAssociationSet().add(new VpcCidrBlockAssociation("vpc-cidr-assoc-1", "10.0.0.0/16")); + stubCreate(created); SecurityGroup def = new SecurityGroup(); def.setGroupId("sg-default"); def.setVpcId("vpc-new"); when(ec2.describeSecurityGroups(REGION, List.of(), List.of("default"), Map.of())) .thenReturn(List.of(def)); + NetworkAcl acl = new NetworkAcl(); + acl.setNetworkAclId("acl-default"); + acl.setVpcId("vpc-new"); + acl.setDefault(true); + when(ec2.describeNetworkAcls(REGION, List.of(), Map.of("vpc-id", List.of("vpc-new"), "default", List.of("true")))) + .thenReturn(List.of(acl)); StackResource r = provision(null, """ {"CidrBlock": "10.0.0.0/16"}"""); @@ -95,20 +122,69 @@ class Ec2VpcCfnProvisionerTest { assertEquals("vpc-new", r.getPhysicalId()); assertEquals("vpc-new", r.getAttributes().get("VpcId")); assertEquals("10.0.0.0/16", r.getAttributes().get("CidrBlock")); + assertEquals("vpc-cidr-assoc-1", r.getAttributes().get("CidrBlockAssociations")); assertEquals("sg-default", r.getAttributes().get("DefaultSecurityGroup")); + assertEquals("acl-default", r.getAttributes().get("DefaultNetworkAcl")); + assertEquals("", r.getAttributes().get("Ipv6CidrBlocks")); } @Test - void anUnchangedVpcIsReusedInsteadOfCreatedAgain() { - when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())) - .thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16"))); + void omittedDnsPropertiesApplyTheAwsDefaults() { + stubCreate(vpc("vpc-new", "10.0.0.0/16")); - StackResource r = provision("vpc-existing", """ + provision(null, """ {"CidrBlock": "10.0.0.0/16"}"""); - verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean()); + verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "default"); + verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsSupport", "true"); + verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsHostnames", "false"); + } + + @Test + void dnsPropertiesResolvingBlankApplyTheAwsDefaults() { + // Fn::If with AWS::NoValue renders as "" through the engine; Boolean.parseBoolean("") would + // otherwise silently switch DnsSupport off. + stubCreate(vpc("vpc-new", "10.0.0.0/16")); + + provision(null, """ + {"CidrBlock": "10.0.0.0/16", "EnableDnsSupport": "", "EnableDnsHostnames": ""}"""); + + verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsSupport", "true"); + verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsHostnames", "false"); + } + + @Test + void tagsDnsSettingsAndTenancyFromTheTemplateAreApplied() { + stubCreate(vpc("vpc-new", "10.0.0.0/16")); + + provision(null, """ + {"CidrBlock": "10.0.0.0/16", "EnableDnsHostnames": true, "EnableDnsSupport": "true", + "InstanceTenancy": "dedicated", + "Tags": [{"Key": "Name", "Value": "my-vpc"}, {"Key": "env", "Value": "dev"}]}"""); + + verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "dedicated"); + verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsHostnames", "true"); + verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsSupport", "true"); + verify(ec2).createTags(eq(REGION), eq(List.of("vpc-new")), argThat(tags("Name=my-vpc", "env=dev"))); + } + + @Test + void anUnchangedVpcIsReusedAndItsTagSetReplaced() { + when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())) + .thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16"))); + when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing")))).thenReturn(List.of( + Map.of("key", "Name", "value", "old"), + Map.of("key", "stale", "value", "x"))); + + StackResource r = provision("vpc-existing", """ + {"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "new"}]}"""); + + verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean(), anyBoolean(), any()); + verify(ec2, never()).modifyVpcTenancy(anyString(), anyString(), anyString()); assertEquals("vpc-existing", r.getPhysicalId(), "reusing must keep the id every subnet and route table already references"); + verify(ec2).deleteTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("stale=x"))); + verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=new"))); } @Test @@ -142,18 +218,38 @@ class Ec2VpcCfnProvisionerTest { void aChangedCidrBlockCreatesAReplacement() { when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())) .thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16"))); - when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-replaced", "10.1.0.0/16")); + stubCreate(vpc("vpc-replaced", "10.1.0.0/16")); StackResource r = provision("vpc-existing", """ {"CidrBlock": "10.1.0.0/16"}"""); - verify(ec2).createVpc(REGION, "10.1.0.0/16", false); + verify(ec2).createVpc(REGION, "10.1.0.0/16", false, false, "default"); assertEquals("vpc-replaced", r.getPhysicalId()); } + @Test + void tenancyDedicatedToDefaultIsAppliedInPlaceAnyOtherChangeReplaces() { + Vpc dedicated = vpc("vpc-existing", "10.0.0.0/16"); + dedicated.setInstanceTenancy("dedicated"); + when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(dedicated)); + + StackResource kept = provision("vpc-existing", """ + {"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "default"}"""); + assertEquals("vpc-existing", kept.getPhysicalId()); + verify(ec2).modifyVpcTenancy(REGION, "vpc-existing", "default"); + + // Now a default VPC asked to become dedicated: the only in-place direction is dedicated->default. + dedicated.setInstanceTenancy("default"); + stubCreate(vpc("vpc-replaced", "10.0.0.0/16")); + StackResource replaced = provision("vpc-existing", """ + {"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "dedicated"}"""); + assertEquals("vpc-replaced", replaced.getPhysicalId()); + verify(ec2).createVpc(eq(REGION), eq("10.0.0.0/16"), eq(false), eq(false), eq("dedicated")); + } + @Test void anIdOnTheResourceAloneDoesNotCountAsAnUpdate() { - when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16")); + stubCreate(vpc("vpc-new", "10.0.0.0/16")); // A resource carrying a physical id under a create context: what provision() itself // produces the moment it assigns the new id. Reading create-vs-update off the resource @@ -162,7 +258,7 @@ class Ec2VpcCfnProvisionerTest { {"CidrBlock": "10.0.0.0/16"}"""); verify(ec2, never()).describeVpcs(anyString(), any(), any()); - verify(ec2).createVpc(REGION, "10.0.0.0/16", false); + verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "default"); assertEquals("vpc-new", r.getPhysicalId()); } @@ -170,12 +266,12 @@ class Ec2VpcCfnProvisionerTest { void aVpcDeletedOutOfBandFallsBackToCreate() { when(ec2.describeVpcs(REGION, List.of("vpc-gone"), Map.of())) .thenReturn(List.of()); - when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-fresh", "10.0.0.0/16")); + stubCreate(vpc("vpc-fresh", "10.0.0.0/16")); StackResource r = provision("vpc-gone", """ {"CidrBlock": "10.0.0.0/16"}"""); - verify(ec2).createVpc(REGION, "10.0.0.0/16", false); + verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "default"); assertEquals("vpc-fresh", r.getPhysicalId()); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateVpcInstanceTenancyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateVpcInstanceTenancyIntegrationTest.java new file mode 100644 index 0000000000..b06aa3949a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateVpcInstanceTenancyIntegrationTest.java @@ -0,0 +1,75 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * CreateVpc's InstanceTenancy on the Query API: {@code default} or {@code dedicated} is stored and + * read back by DescribeVpcs; omitting it means {@code default}; {@code host} is refused, as the + * EC2 reference says ("The host value cannot be used with this parameter"). + */ +@QuarkusTest +class Ec2CreateVpcInstanceTenancyIntegrationTest { + + private final List createdVpcs = new ArrayList<>(); + + private static ValidatableResponse ec2(String action, String... formParams) { + RequestSpecification request = given().header("Authorization", + "AWS4-HMAC-SHA256 Credential=test/20261007/us-east-1/ec2/aws4_request") + .formParam("Action", action); + for (int i = 0; i < formParams.length; i += 2) { + request.formParam(formParams[i], formParams[i + 1]); + } + return request.when().post("/").then(); + } + + @AfterEach + void deleteCreatedVpcs() { + for (String vpcId : createdVpcs) { + ec2("DeleteVpc", "VpcId", vpcId).statusCode(200); + } + } + + @Test + void dedicatedTenancyIsStoredAndDescribed() { + String vpcId = createVpc("10.97.0.0/16", "InstanceTenancy", "dedicated"); + ec2("DescribeVpcs", "VpcId.1", vpcId).statusCode(200) + .body("DescribeVpcsResponse.vpcSet.item.instanceTenancy", equalTo("dedicated")); + } + + @Test + void omittedTenancyIsDefault() { + String vpcId = createVpc("10.98.0.0/16"); + ec2("DescribeVpcs", "VpcId.1", vpcId).statusCode(200) + .body("DescribeVpcsResponse.vpcSet.item.instanceTenancy", equalTo("default")); + } + + @Test + void hostTenancyIsRejected() { + ec2("CreateVpc", "CidrBlock", "10.99.0.0/16", "InstanceTenancy", "host").statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) + .body("Response.Errors.Error.Message", + equalTo("Value (host) for parameter instanceTenancy is invalid. " + + "Valid values are: default, dedicated.")); + } + + private String createVpc(String cidr, String... extraParams) { + String[] params = new String[2 + extraParams.length]; + params[0] = "CidrBlock"; + params[1] = cidr; + System.arraycopy(extraParams, 0, params, 2, extraParams.length); + String vpcId = ec2("CreateVpc", params).statusCode(200) + .extract().xmlPath().getString("CreateVpcResponse.vpc.vpcId"); + createdVpcs.add(vpcId); + return vpcId; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java index cb5a989638..50a7d9ebf9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java @@ -97,7 +97,7 @@ class Ec2QueryHandlerTest { Ec2Service service = mock(Ec2Service.class); Vpc vpc = new Vpc(); vpc.setVpcId("vpc-test"); - when(service.createVpc("us-east-1", "10.38.0.0/16", false, false)).thenReturn(vpc); + when(service.createVpc("us-east-1", "10.38.0.0/16", false, false, null)).thenReturn(vpc); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("CidrBlock", "10.38.0.0/16"); params.putSingle("TagSpecification.1.ResourceType", "vpc"); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index be7be21c77..cd9e569011 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -141,6 +141,52 @@ class Ec2ServiceTest { () -> service.requireVpc(region, unknown)).getErrorCode()); } + @Test + void createVpcAcceptsDefaultOrDedicatedAndDefaultsWhenOmitted() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String region = "us-east-1"; + + assertEquals("default", service.createVpc(region, "10.90.0.0/16", false, false, null).getInstanceTenancy()); + // A present blank is not an enum value; only an absent parameter defaults. + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, + () -> service.createVpc(region, "10.91.0.0/16", false, false, " ")).getErrorCode()); + assertEquals("dedicated", service.createVpc(region, "10.92.0.0/16", false, false, "dedicated").getInstanceTenancy()); + + AwsException bogus = assertThrows(AwsException.class, + () -> service.createVpc(region, "10.93.0.0/16", false, false, "bogus")); + assertEquals("InvalidParameterValue", bogus.getErrorCode()); + assertEquals(400, bogus.getHttpStatus()); + assertTrue(bogus.getMessage().contains("Value (bogus) for parameter instanceTenancy is invalid")); + + // The EC2 reference: "The host value cannot be used with this parameter." + AwsException host = assertThrows(AwsException.class, + () -> service.createVpc(region, "10.96.0.0/16", false, false, "host")); + assertEquals("InvalidParameterValue", host.getErrorCode()); + } + + @Test + void modifyVpcTenancyOnlyMovesADedicatedVpcToDefault() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String region = "us-east-1"; + String dedicated = service.createVpc(region, "10.94.0.0/16", false, false, "dedicated").getVpcId(); + String alreadyDefault = service.createVpc(region, "10.95.0.0/16", false, false, "default").getVpcId(); + + service.modifyVpcTenancy(region, dedicated, "default"); + assertEquals("default", service.requireVpc(region, dedicated).getInstanceTenancy()); + + AwsException fromDefault = assertThrows(AwsException.class, + () -> service.modifyVpcTenancy(region, alreadyDefault, "default")); + assertEquals("InvalidParameterValue", fromDefault.getErrorCode()); + + AwsException toDedicated = assertThrows(AwsException.class, + () -> service.modifyVpcTenancy(region, dedicated, "dedicated")); + assertEquals("InvalidParameterValue", toDedicated.getErrorCode()); + } + @Test void deleteVpcRemovesVpcOwnedDefaultResourcesAndRules() { Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 59d22aff14..05be7256af 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -10,9 +10,6 @@ AWS::EC2::NatGateway RouteTableId availability-mode NAT gateways are not emulate AWS::EC2::Subnet BlockPublicAccessStates VPC block public access is not emulated AWS::EC2::Subnet Ipv6CidrBlocks IPv6 CIDR association is not emulated AWS::EC2::Subnet NetworkAclAssociationId the subnet's default network ACL association is not created with the subnet -AWS::EC2::VPC CidrBlockAssociations needs association ids Floci's VPC model does not track -AWS::EC2::VPC DefaultNetworkAcl needs a default network ACL Floci does not create with the VPC -AWS::EC2::VPC Ipv6CidrBlocks IPv6 CIDR association is not emulated AWS::EC2::VPCEndpoint NetworkInterfaceIds endpoint ENIs are not created AWS::EC2::VPCGatewayAttachment AttachmentType the exact literal AWS returns (internet vs vpn gateway) is not given by the schema AWS::Kinesis::Stream WarmThroughputObject warm throughput is not an emulated Kinesis feature