feat(cloudformation): provision AWS::EC2::VPCEndpoint (#1995)

* feat(cloudformation): provision AWS::EC2::VPCEndpoint

Maps VpcId/ServiceName/VpcEndpointType and the RouteTableIds/SubnetIds/
SecurityGroupIds reference lists onto the existing
Ec2Service.createVpcEndpoint; DeleteStack removes the endpoint.

Fixes #1994

* refactor(cloudformation): move VPCEndpoint into the per-service provisioner structure

Ec2VpcEndpointCfnProvisioner implements CfnResourceProvisioner for
AWS::EC2::VPCEndpoint and injects only Ec2Service. The registry discovers it
via CDI, so the provision and delete switch arms plus the resolveIdList helper
come out of CloudFormationResourceProvisioner.

Two review fixes carried in with the move:

- PrivateDnsEnabled now resolves through the template engine instead of
  props.path(...).asBoolean(false), so a Ref or parameter no longer collapses
  to false. An absent property passes null and Ec2Service applies the AWS
  default (true for Interface endpoints).
- An update deletes the endpoint it replaced, so re-deploys no longer leave
  orphaned endpoints behind. A missing prior endpoint is tolerated.

Adds an isolated unit test for the new provisioner; the existing
CloudFormationVpcEndpointIntegrationTest still covers the end-to-end path.

* feat(cloudformation): VPCEndpoint sets the CreationTimestamp attribute

The registry schema lists Id, CreationTimestamp, NetworkInterfaceIds and
DnsEntries as Fn::GetAtt attributes, and only Id was set. An unset attribute
resolves to the literal "LogicalId.CreationTimestamp" rather than failing, so a
template asking for it got a wrong value with nothing to signal it.

Ec2Service already stamps the timestamp at create, so the provisioner renders it
with the same format DescribeVpcEndpoints uses. NetworkInterfaceIds and
DnsEntries are not modelled yet and stay unset.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-14 21:03:56 -04:00
1 parent 105a8eeb7e
commit a985fa4640
3 files changed
+330

No files matched your search

@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::EC2::VPCEndpoint}.
*
* <p>Updates are handled as replacement: a new endpoint is created and the previous one is
* deleted, so re-deploys do not accumulate orphaned endpoints. {@code Ec2Service} has no
* modify operation, so mutable-property updates also replace; this matches how the other
* EC2 networking types behave here while still cleaning up the prior endpoint.
*/
@ApplicationScoped
public class Ec2VpcEndpointCfnProvisioner implements CfnResourceProvisioner {
/** Same rendering DescribeVpcEndpoints uses, so the attribute reads as the API reports it. */
private static final DateTimeFormatter ISO_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
private final Ec2Service ec2Service;
@Inject
public Ec2VpcEndpointCfnProvisioner(Ec2Service ec2Service) {
this.ec2Service = ec2Service;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::EC2::VPCEndpoint");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String vpcId = ctx.resolveOptional(props, "VpcId");
String serviceName = ctx.resolveOptional(props, "ServiceName");
String endpointType = ctx.resolveOptional(props, "VpcEndpointType");
// Resolve through the engine so Refs/parameters work, not just literal booleans. When the
// property is absent, pass null and let Ec2Service apply its own default (true for
// Interface endpoints, false otherwise), matching the AWS default.
String privateDns = ctx.resolveOptional(props, "PrivateDnsEnabled");
Boolean privateDnsEnabled = privateDns != null && !privateDns.isBlank()
? Boolean.parseBoolean(privateDns)
: null;
String previousEndpointId = r.getPhysicalId();
var endpoint = ec2Service.createVpcEndpoint(ctx.region(), vpcId, serviceName,
endpointType != null ? endpointType : "Gateway",
resolveIdList(props, "RouteTableIds", ctx),
resolveIdList(props, "SubnetIds", ctx),
resolveIdList(props, "SecurityGroupIds", ctx),
privateDnsEnabled,
List.of());
r.setPhysicalId(endpoint.getVpcEndpointId());
r.getAttributes().put("Id", endpoint.getVpcEndpointId());
// An unset attribute resolves to the literal "LogicalId.CreationTimestamp" rather than
// failing, so leaving it out hands the template a wrong value quietly.
if (endpoint.getCreationTimestamp() != null) {
r.getAttributes().put("CreationTimestamp", ISO_FMT.format(endpoint.getCreationTimestamp()));
}
if (previousEndpointId != null && !previousEndpointId.equals(endpoint.getVpcEndpointId())) {
deleteReplacedEndpoint(previousEndpointId, ctx.region());
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
ec2Service.deleteVpcEndpoints(region, List.of(physicalId));
}
/** Resolve an array property of Ref/GetAtt entries into plain id strings. */
private List<String> resolveIdList(JsonNode props, String field, ProvisionContext ctx) {
List<String> ids = new ArrayList<>();
if (props != null && props.has(field) && props.get(field).isArray()) {
for (JsonNode entry : props.get(field)) {
String id = ctx.engine().resolve(entry);
if (id != null && !id.isBlank()) ids.add(id);
}
}
return ids;
}
private void deleteReplacedEndpoint(String endpointId, String region) {
try {
ec2Service.deleteVpcEndpoints(region, List.of(endpointId));
} catch (AwsException e) {
if (!"InvalidVpcEndpointId.NotFound".equals(e.getErrorCode()) && e.getHttpStatus() != 404) {
throw e;
}
}
}
}
@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/**
* End-to-end check that CloudFormation provisions AWS::EC2::VPCEndpoint for
* real (issue #1994): the endpoint lands in Ec2Service with its route-table
* association, and DeleteStack removes it. Metadata-only — Docker-free.
*/
@QuarkusTest
class CloudFormationVpcEndpointIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
@Test
void createStackProvisionsGatewayEndpointAndDeleteRemovesIt() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-vpce-stack-" + suffix;
String template = """
{
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.60.0.0/16"}},
"Rt": {"Type": "AWS::EC2::RouteTable", "Properties": {"VpcId": {"Ref": "Vpc"}}},
"S3Endpoint": {
"Type": "AWS::EC2::VPCEndpoint",
"Properties": {
"VpcId": {"Ref": "Vpc"},
"ServiceName": "com.amazonaws.us-east-1.s3",
"VpcEndpointType": "Gateway",
"RouteTableIds": [{"Ref": "Rt"}]
}
}
},
"Outputs": {
"EndpointId": {"Value": {"Ref": "S3Endpoint"}}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
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>"))
.body(containsString("<OutputValue>vpce-"));
given()
.formParam("Action", "DescribeVpcEndpoints")
.header("Authorization", EC2_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("com.amazonaws.us-east-1.s3"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "DescribeVpcEndpoints")
.header("Authorization", EC2_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("com.amazonaws.us-east-1.s3")));
}
}
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.VpcEndpoint;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The VPC-endpoint CFN provisioner in isolation, mocking only Ec2Service. */
class Ec2VpcEndpointCfnProvisionerTest {
private static final Instant CREATED_AT = Instant.parse("2026-08-13T10:15:30Z");
private final Ec2Service ec2 = mock(Ec2Service.class);
private final Ec2VpcEndpointCfnProvisioner provisioner = new Ec2VpcEndpointCfnProvisioner(ec2);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
// Scalars resolve to their text; {"Ref": "X"} resolves to a fake physical id, which is
// enough to prove properties go through the engine instead of being read raw.
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
if (node == null) {
return null;
}
if (node.isObject() && node.has("Ref")) {
String ref = node.get("Ref").asText();
// Models a template parameter carrying a boolean value.
return "EnableDns".equals(ref) ? "true" : "resolved-" + ref;
}
return node.asText();
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
}
private StackResource resource() {
StackResource r = new StackResource();
r.setLogicalId("S3Endpoint");
r.setResourceType("AWS::EC2::VPCEndpoint");
r.setAttributes(new HashMap<>());
return r;
}
private VpcEndpoint endpoint(String id) {
VpcEndpoint e = new VpcEndpoint();
e.setVpcEndpointId(id);
e.setCreationTimestamp(CREATED_AT);
return e;
}
@Test
void gatewayEndpointSetsPhysicalIdAndResolvesRefs() {
when(ec2.createVpcEndpoint(eq("us-east-1"), eq("resolved-Vpc"), eq("com.amazonaws.us-east-1.s3"),
eq("Gateway"), eq(List.of("resolved-Rt")), eq(List.of()), eq(List.of()), isNull(), anyList()))
.thenReturn(endpoint("vpce-123"));
StackResource r = resource();
ObjectNode props = mapper.createObjectNode()
.put("ServiceName", "com.amazonaws.us-east-1.s3");
props.set("VpcId", mapper.createObjectNode().put("Ref", "Vpc"));
props.putArray("RouteTableIds").add(mapper.createObjectNode().put("Ref", "Rt"));
provisioner.provision(r, props, ctx());
assertEquals("vpce-123", r.getPhysicalId());
assertEquals("vpce-123", r.getAttributes().get("Id"));
assertEquals("2026-08-13T10:15:30.000Z", r.getAttributes().get("CreationTimestamp"));
}
@Test
void privateDnsEnabledResolvesThroughEngine() {
when(ec2.createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
anyList(), anyList(), anyList(), eq(Boolean.TRUE), anyList()))
.thenReturn(endpoint("vpce-dns"));
StackResource r = resource();
ObjectNode props = mapper.createObjectNode()
.put("VpcId", "vpc-1")
.put("ServiceName", "com.amazonaws.us-east-1.ecr.api")
.put("VpcEndpointType", "Interface");
// A Ref, not a literal boolean: raw props.asBoolean(false) would silently yield false.
props.set("PrivateDnsEnabled", mapper.createObjectNode().put("Ref", "EnableDns"));
provisioner.provision(r, props, ctx());
assertEquals("vpce-dns", r.getPhysicalId());
verify(ec2).createVpcEndpoint(eq("us-east-1"), eq("vpc-1"), eq("com.amazonaws.us-east-1.ecr.api"),
eq("Interface"), anyList(), anyList(), anyList(), eq(Boolean.TRUE), anyList());
}
@Test
void updateReplacesAndDeletesPreviousEndpoint() {
when(ec2.createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
anyList(), anyList(), anyList(), any(), anyList()))
.thenReturn(endpoint("vpce-new"));
StackResource r = resource();
r.setPhysicalId("vpce-old");
ObjectNode props = mapper.createObjectNode()
.put("VpcId", "vpc-1")
.put("ServiceName", "com.amazonaws.us-east-1.s3");
provisioner.provision(r, props, ctx());
assertEquals("vpce-new", r.getPhysicalId());
verify(ec2).deleteVpcEndpoints("us-east-1", List.of("vpce-old"));
}
@Test
void deleteDelegatesToService() {
provisioner.delete("AWS::EC2::VPCEndpoint", "vpce-123", "us-east-1");
verify(ec2).deleteVpcEndpoints("us-east-1", List.of("vpce-123"));
}
}