Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ec2): support ModifyVpcEndpoint and persist the endpoint policy (#2526)

Allen Sanborn2e8cbc13d729
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 794622da27..cae0562675 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -179,8 +179,9 @@ Floci seeds the following resources on first use in each region so Terraform, th
| ModifyVpcAttribute | Updates supported VPC attributes. |
| DescribeVpcAttribute | Returns a supported VPC attribute. |
| DescribeVpcEndpointServices | Returns an empty local VPC endpoint service catalog. |
-| CreateVpcEndpoint | Creates a VPC endpoint record. |
+| CreateVpcEndpoint | Creates a VPC endpoint record, including its `PolicyDocument`. |
| DescribeVpcEndpoints | Lists or returns stored VPC endpoints. |
+| ModifyVpcEndpoint | Associates or disassociates route tables, subnets and security groups, and sets or resets the endpoint policy. `DnsOptions`, `IpAddressType` and `SubnetConfiguration.N` are accepted and ignored. |
| DeleteVpcEndpoints | Deletes VPC endpoint records. |
| CreateDefaultVpc | Creates or returns the default VPC for the region. |
| AssociateVpcCidrBlock | Adds a secondary CIDR block association to a VPC. |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisioner.java
index 1f2d0f4095..616f389f22 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisioner.java
@@ -59,6 +59,7 @@ public class Ec2VpcEndpointCfnProvisioner implements CfnResourceProvisioner {
resolveIdList(props, "SubnetIds", ctx),
resolveIdList(props, "SecurityGroupIds", ctx),
privateDnsEnabled,
+ policyDocument(props, ctx),
List.of());
r.setPhysicalId(endpoint.getVpcEndpointId());
r.getAttributes().put("Id", endpoint.getVpcEndpointId());
@@ -77,6 +78,29 @@ public class Ec2VpcEndpointCfnProvisioner implements CfnResourceProvisioner {
ec2Service.deleteVpcEndpoints(region, List.of(physicalId));
}
+ /**
+ * {@code PolicyDocument} is declared as JSON in the template, so it arrives as an object node
+ * whose fields may still carry intrinsics ({@code Ref}, {@code Fn::Sub}, {@code Fn::Join}).
+ * Serialising the raw node would store literal template syntax and DescribeVpcEndpoints would
+ * report it verbatim, so it goes through
+ * {@link io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine#resolveJsonAttribute},
+ * the engine helper for JSON-valued attributes (policy documents, RedrivePolicy,
+ * FilterPolicy, Step Functions definitions). That helper also avoids the double-encoding
+ * trap a naive {@code resolveNode(...).toString()} hits: resolveNode collapses an intrinsic
+ * to a TextNode holding already-serialized JSON, which {@code toString()} then re-quotes.
+ *
+ * <p>It returns null for a null or missing node, so no {@code has}/{@code isNull} guard is
+ * needed here beyond the null-props check.
+ *
+ * @see <a href="https://github.com/floci-io/floci/issues/2317">#2317</a>
+ */
+ private String policyDocument(JsonNode props, ProvisionContext ctx) {
+ if (props == null) {
+ return null;
+ }
+ return ctx.engine().resolveJsonAttribute(props.path("PolicyDocument"));
+ }
+
/** 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<>();
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 a2c7139801..d2af0c9caf 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
@@ -73,6 +73,7 @@ public class Ec2QueryHandler {
case "DescribeVpcEndpointServices" -> handleDescribeVpcEndpointServices(params, region);
case "CreateVpcEndpoint" -> handleCreateVpcEndpoint(params, region);
case "DescribeVpcEndpoints" -> handleDescribeVpcEndpoints(params, region);
+ case "ModifyVpcEndpoint" -> handleModifyVpcEndpoint(params, region);
case "DeleteVpcEndpoints" -> handleDeleteVpcEndpoints(params, region);
// Flow Logs
case "CreateFlowLogs" -> handleCreateFlowLogs(params, region);
@@ -1102,6 +1103,7 @@ public class Ec2QueryHandler {
getList(p, "SubnetId"),
getList(p, "SecurityGroupId"),
p.getFirst("PrivateDnsEnabled") != null ? Boolean.valueOf(p.getFirst("PrivateDnsEnabled")) : null,
+ p.getFirst("PolicyDocument"),
parseTagsForResource(p, "vpc-endpoint"));
XmlBuilder xml = new XmlBuilder()
.start("CreateVpcEndpointResponse", AwsNamespaces.EC2)
@@ -1111,6 +1113,29 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
+ private Response handleModifyVpcEndpoint(MultivaluedMap<String, String> p, String region) {
+ service.modifyVpcEndpoint(
+ region,
+ p.getFirst("VpcEndpointId"),
+ getList(p, "AddRouteTableId"),
+ getList(p, "RemoveRouteTableId"),
+ getList(p, "AddSubnetId"),
+ getList(p, "RemoveSubnetId"),
+ getList(p, "AddSecurityGroupId"),
+ getList(p, "RemoveSecurityGroupId"),
+ p.getFirst("PolicyDocument"),
+ p.getFirst("ResetPolicy") != null ? Boolean.valueOf(p.getFirst("ResetPolicy")) : null,
+ p.getFirst("PrivateDnsEnabled") != null ? Boolean.valueOf(p.getFirst("PrivateDnsEnabled")) : null);
+ // ModifyVpcEndpoint returns only a boolean; the caller re-reads the endpoint
+ // through DescribeVpcEndpoints to see the result.
+ XmlBuilder xml = new XmlBuilder()
+ .start("ModifyVpcEndpointResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("return", true)
+ .end("ModifyVpcEndpointResponse");
+ return xmlResponse(xml.build());
+ }
+
private Response handleDescribeVpcEndpoints(MultivaluedMap<String, String> p, String region) {
List<String> endpointIds = getList(p, "VpcEndpointId");
Map<String, List<String>> filters = getFilters(p);
@@ -3415,8 +3440,11 @@ public class Ec2QueryHandler {
for (String securityGroupId : endpoint.getSecurityGroupIds()) {
xml.start("item").elem("groupId", securityGroupId).end("item");
}
- xml.end("groupSet")
- .raw(tagSetXml(endpoint.getTags()));
+ xml.end("groupSet");
+ if (endpoint.getPolicyDocument() != null) {
+ xml.elem("policyDocument", endpoint.getPolicyDocument());
+ }
+ xml.raw(tagSetXml(endpoint.getTags()));
return xml.build();
}
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 f0a4301f4c..c54cab6468 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
@@ -2738,7 +2738,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
public VpcEndpoint createVpcEndpoint(String region, String vpcId, String serviceName, String endpointType,
List<String> routeTableIds, List<String> subnetIds,
- List<String> securityGroupIds, Boolean privateDnsEnabled, List<Tag> endpointTags) {
+ List<String> securityGroupIds, Boolean privateDnsEnabled,
+ String policyDocument, List<Tag> endpointTags) {
ensureDefaultResources(region);
getRequiredVpc(region, vpcId);
for (String routeTableId : routeTableIds) {
@@ -2763,6 +2764,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
endpoint.setRouteTableIds(new ArrayList<>(routeTableIds));
endpoint.setSubnetIds(new ArrayList<>(subnetIds));
endpoint.setSecurityGroupIds(new ArrayList<>(securityGroupIds));
+ endpoint.setPolicyDocument(policyDocument);
if (endpointTags != null && !endpointTags.isEmpty()) {
endpoint.setTags(new ArrayList<>(endpointTags));
tags.put(endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags));
@@ -2771,6 +2773,89 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return endpoint;
}
+ /**
+ * Applies a ModifyVpcEndpoint request. Every parameter is optional and each applies
+ * independently, so one request may move route tables and rewrite the policy.
+ *
+ * <p>The add/remove parameters are set operations. AWS accepts an id that is already
+ * associated, or a removal of one that is not, without complaint, so this is
+ * idempotent on both sides. {@code resetPolicy} returns the endpoint to the default
+ * full-access policy, modelled here as carrying no document at all.
+ */
+ public VpcEndpoint modifyVpcEndpoint(String region, String endpointId,
+ List<String> addRouteTableIds, List<String> removeRouteTableIds,
+ List<String> addSubnetIds, List<String> removeSubnetIds,
+ List<String> addSecurityGroupIds, List<String> removeSecurityGroupIds,
+ String policyDocument, Boolean resetPolicy, Boolean privateDnsEnabled) {
+ // VpcEndpointId is the one required member of ModifyVpcEndpointRequest. The model
+ // requires it to be present, not to be non-empty, so only an absent value is a
+ // MissingParameter; a present-but-unknown id is an InvalidVpcEndpointId.NotFound.
+ if (endpointId == null) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter VpcEndpointId", 400);
+ }
+ ensureDefaultResources(region);
+ // Terraform declares each aws_vpc_endpoint_route_table_association as its own
+ // resource and applies them in parallel, so several ModifyVpcEndpoint calls land
+ // on one endpoint at once. Without the lock this read-modify-write loses updates:
+ // each caller reads the same association list, adds its own id, and the last write
+ // wins -- leaving the other caller's waiter polling for an association that was
+ // silently dropped.
+ synchronized (lockFor(key(region, endpointId))) {
+ return modifyVpcEndpointLocked(region, endpointId,
+ addRouteTableIds, removeRouteTableIds, addSubnetIds, removeSubnetIds,
+ addSecurityGroupIds, removeSecurityGroupIds,
+ policyDocument, resetPolicy, privateDnsEnabled);
+ }
+ }
+
+ private VpcEndpoint modifyVpcEndpointLocked(String region, String endpointId,
+ List<String> addRouteTableIds, List<String> removeRouteTableIds,
+ List<String> addSubnetIds, List<String> removeSubnetIds,
+ List<String> addSecurityGroupIds, List<String> removeSecurityGroupIds,
+ String policyDocument, Boolean resetPolicy,
+ Boolean privateDnsEnabled) {
+ VpcEndpoint endpoint = getRequiredVpcEndpoint(region, endpointId);
+
+ // Validate every referenced id before mutating anything, so a request naming one
+ // bad id does not leave the endpoint half-modified.
+ for (String routeTableId : addRouteTableIds) {
+ getRequiredRouteTable(region, routeTableId);
+ }
+ for (String subnetId : addSubnetIds) {
+ requireSubnet(region, subnetId);
+ }
+ for (String securityGroupId : addSecurityGroupIds) {
+ getRequiredSecurityGroup(region, securityGroupId);
+ }
+
+ applyIdChanges(endpoint.getRouteTableIds(), addRouteTableIds, removeRouteTableIds);
+ applyIdChanges(endpoint.getSubnetIds(), addSubnetIds, removeSubnetIds);
+ applyIdChanges(endpoint.getSecurityGroupIds(), addSecurityGroupIds, removeSecurityGroupIds);
+
+ if (Boolean.TRUE.equals(resetPolicy)) {
+ endpoint.setPolicyDocument(null);
+ } else if (policyDocument != null) {
+ endpoint.setPolicyDocument(policyDocument);
+ }
+ if (privateDnsEnabled != null) {
+ endpoint.setPrivateDnsEnabled(privateDnsEnabled);
+ }
+
+ vpcEndpoints.put(key(region, endpointId), endpoint);
+ return endpoint;
+ }
+
+ /** Removals apply before additions, and an id is never added twice. */
+ private static void applyIdChanges(List<String> current, List<String> toAdd, List<String> toRemove) {
+ current.removeAll(toRemove);
+ for (String id : toAdd) {
+ if (!current.contains(id)) {
+ current.add(id);
+ }
+ }
+ }
+
public List<VpcEndpoint> describeVpcEndpoints(String region, List<String> endpointIds,
Map<String, List<String>> filters) {
ensureDefaultResources(region);
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/VpcEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/VpcEndpoint.java
index b611702e0d..12bfe2d869 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/VpcEndpoint.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/VpcEndpoint.java
@@ -22,6 +22,7 @@ public class VpcEndpoint {
private List<String> subnetIds = new ArrayList<>();
private List<String> securityGroupIds = new ArrayList<>();
private boolean privateDnsEnabled;
+ private String policyDocument;
private List<Tag> tags = new ArrayList<>();
public VpcEndpoint() {}
@@ -59,6 +60,9 @@ public class VpcEndpoint {
public boolean isPrivateDnsEnabled() { return privateDnsEnabled; }
public void setPrivateDnsEnabled(boolean privateDnsEnabled) { this.privateDnsEnabled = privateDnsEnabled; }
+ public String getPolicyDocument() { return policyDocument; }
+ public void setPolicyDocument(String policyDocument) { this.policyDocument = policyDocument; }
+
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisionerTest.java
index 50d1497a2f..d4688df301 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcEndpointCfnProvisionerTest.java
@@ -2,18 +2,23 @@ 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.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.TextNode;
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 org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
@@ -36,21 +41,59 @@ class Ec2VpcEndpointCfnProvisionerTest {
// 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) {
+ when(engine.resolve(any())).thenAnswer(inv -> fakeResolve(inv.getArgument(0)));
+ when(engine.resolveNode(any())).thenAnswer(inv -> fakeResolveNode(inv.getArgument(0)));
+ // Same contract as the real resolveJsonAttribute: resolve the tree, then unwrap a
+ // textual result rather than re-serialising it (#2317's double-encoding trap).
+ when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> {
+ JsonNode resolved = fakeResolveNode(inv.getArgument(0));
+ if (resolved == null || resolved.isNull() || resolved.isMissingNode()) {
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 resolved.isTextual() ? resolved.asText() : resolved.toString();
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
}
+ /** The subset of intrinsic handling these tests need. */
+ private String fakeResolve(JsonNode node) {
+ 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;
+ }
+ if (node.isObject() && node.has("Fn::Sub")) {
+ return node.get("Fn::Sub").asText()
+ .replace("${AWS::Region}", "us-east-1")
+ .replace("${AWS::AccountId}", "000000000000");
+ }
+ return node.asText();
+ }
+
+ /** Mirrors CloudFormationTemplateEngine.resolveNode: intrinsics collapse to a TextNode. */
+ private JsonNode fakeResolveNode(JsonNode node) {
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return node;
+ }
+ if (node.isObject()) {
+ if (node.has("Ref") || node.has("Fn::Sub")) {
+ return TextNode.valueOf(fakeResolve(node));
+ }
+ ObjectNode resolved = mapper.createObjectNode();
+ node.fields().forEachRemaining(e -> resolved.set(e.getKey(), fakeResolveNode(e.getValue())));
+ return resolved;
+ }
+ if (node.isArray()) {
+ ArrayNode arr = mapper.createArrayNode();
+ node.forEach(item -> arr.add(fakeResolveNode(item)));
+ return arr;
+ }
+ return node;
+ }
+
private StackResource resource() {
StackResource r = new StackResource();
r.setLogicalId("S3Endpoint");
@@ -69,7 +112,7 @@ class Ec2VpcEndpointCfnProvisionerTest {
@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()))
+ eq("Gateway"), eq(List.of("resolved-Rt")), eq(List.of()), eq(List.of()), isNull(), isNull(), anyList()))
.thenReturn(endpoint("vpce-123"));
StackResource r = resource();
ObjectNode props = mapper.createObjectNode()
@@ -87,7 +130,7 @@ class Ec2VpcEndpointCfnProvisionerTest {
@Test
void privateDnsEnabledResolvesThroughEngine() {
when(ec2.createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
- anyList(), anyList(), anyList(), eq(Boolean.TRUE), anyList()))
+ anyList(), anyList(), anyList(), eq(Boolean.TRUE), any(), anyList()))
.thenReturn(endpoint("vpce-dns"));
StackResource r = resource();
ObjectNode props = mapper.createObjectNode()
@@ -101,13 +144,90 @@ class Ec2VpcEndpointCfnProvisionerTest {
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());
+ eq("Interface"), anyList(), anyList(), anyList(), eq(Boolean.TRUE), any(), anyList());
+ }
+
+ @Test
+ void policyDocumentIsSerialisedAndPassedThrough() {
+ // The template declares PolicyDocument as JSON, so it arrives as an object node.
+ // Passing null here would drop a CloudFormation-declared policy exactly as the
+ // EC2 API path used to.
+ when(ec2.createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
+ anyList(), anyList(), anyList(), any(), any(), anyList()))
+ .thenReturn(endpoint("vpce-policy"));
+ StackResource r = resource();
+ ObjectNode props = mapper.createObjectNode()
+ .put("VpcId", "vpc-1")
+ .put("ServiceName", "com.amazonaws.us-east-1.s3");
+ ObjectNode statement = mapper.createObjectNode()
+ .put("Effect", "Allow")
+ .put("Principal", "*")
+ .put("Action", "s3:GetObject")
+ .put("Resource", "*");
+ ObjectNode policy = mapper.createObjectNode().put("Version", "2012-10-17");
+ policy.putArray("Statement").add(statement);
+ props.set("PolicyDocument", policy);
+
+ provisioner.provision(r, props, ctx());
+
+ verify(ec2).createVpcEndpoint(eq("us-east-1"), eq("vpc-1"), eq("com.amazonaws.us-east-1.s3"),
+ anyString(), anyList(), anyList(), anyList(), any(),
+ eq(policy.toString()), anyList());
+ }
+
+ @Test
+ void policyDocumentIntrinsicsAreResolvedNotStoredAsTemplateSyntax() {
+ // A PolicyDocument carrying Fn::Sub/Ref must reach Ec2Service resolved, or
+ // DescribeVpcEndpoints hands the caller back literal template text.
+ when(ec2.createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
+ anyList(), anyList(), anyList(), any(), any(), anyList()))
+ .thenReturn(endpoint("vpce-sub"));
+ StackResource r = resource();
+ ObjectNode props = mapper.createObjectNode()
+ .put("VpcId", "vpc-1")
+ .put("ServiceName", "com.amazonaws.us-east-1.s3");
+ ObjectNode statement = mapper.createObjectNode()
+ .put("Effect", "Allow")
+ .put("Action", "s3:GetObject");
+ statement.set("Resource",
+ mapper.createObjectNode().put("Fn::Sub", "arn:aws:s3:::${AWS::Region}-artifacts/*"));
+ statement.set("Principal", mapper.createObjectNode().put("Ref", "AppRole"));
+ ObjectNode policy = mapper.createObjectNode().put("Version", "2012-10-17");
+ policy.putArray("Statement").add(statement);
+ props.set("PolicyDocument", policy);
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<String> stored = ArgumentCaptor.forClass(String.class);
+ verify(ec2).createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
+ anyList(), anyList(), anyList(), any(), stored.capture(), anyList());
+ String document = stored.getValue();
+ assertTrue(document.contains("arn:aws:s3:::us-east-1-artifacts/*"), document);
+ assertTrue(document.contains("resolved-AppRole"), document);
+ assertFalse(document.contains("Fn::Sub"), document);
+ assertFalse(document.contains("\"Ref\""), document);
+ }
+
+ @Test
+ void anAbsentPolicyDocumentStaysNull() {
+ when(ec2.createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
+ anyList(), anyList(), anyList(), any(), isNull(), anyList()))
+ .thenReturn(endpoint("vpce-nopolicy"));
+ StackResource r = resource();
+ ObjectNode props = mapper.createObjectNode()
+ .put("VpcId", "vpc-1")
+ .put("ServiceName", "com.amazonaws.us-east-1.s3");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(ec2).createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
+ anyList(), anyList(), anyList(), any(), isNull(), anyList());
}
@Test
void updateReplacesAndDeletesPreviousEndpoint() {
when(ec2.createVpcEndpoint(anyString(), anyString(), anyString(), anyString(),
- anyList(), anyList(), anyList(), any(), anyList()))
+ anyList(), anyList(), anyList(), any(), any(), anyList()))
.thenReturn(endpoint("vpce-new"));
StackResource r = resource();
r.setPhysicalId("vpce-old");
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ModifyVpcEndpointTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ModifyVpcEndpointTest.java
new file mode 100644
index 0000000000..93168f760a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ModifyVpcEndpointTest.java
@@ -0,0 +1,292 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+import jakarta.inject.Inject;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.hamcrest.xml.HasXPath.hasXPath;
+
+/**
+ * ModifyVpcEndpoint. A gateway endpoint is normally declared with its route tables and
+ * policy attached after the endpoint exists, so without this action an endpoint can be
+ * created but never wired to anything.
+ *
+ * @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyVpcEndpoint.html">ModifyVpcEndpoint</a>
+ */
+@QuarkusTest
+class Ec2ModifyVpcEndpointTest {
+
+ @Inject
+ Ec2Service service;
+
+ private static final String AUTH_HEADER =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
+
+ private static final String POLICY =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
+
+ private String ec2(String action, String... formParams) {
+ var req = given().formParam("Action", action).header("Authorization", AUTH_HEADER);
+ for (int i = 0; i < formParams.length; i += 2) {
+ req = req.formParam(formParams[i], formParams[i + 1]);
+ }
+ return req.when().post("/").then().statusCode(200).extract().asString();
+ }
+
+ private String xmlValue(String xml, String element) {
+ String open = "<" + element + ">";
+ String close = "</" + element + ">";
+ int start = xml.indexOf(open);
+ return start < 0 ? null : xml.substring(start + open.length(), xml.indexOf(close, start));
+ }
+
+ private record Fixture(String vpcId, String routeTableId, String endpointId) {}
+
+ private Fixture fixture(String cidr) {
+ String vpcId = xmlValue(ec2("CreateVpc", "CidrBlock", cidr), "vpcId");
+ String routeTableId = xmlValue(ec2("CreateRouteTable", "VpcId", vpcId), "routeTableId");
+ String endpointId = xmlValue(ec2("CreateVpcEndpoint",
+ "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.s3"), "vpcEndpointId");
+ return new Fixture(vpcId, routeTableId, endpointId);
+ }
+
+ private String describe(String endpointId) {
+ return ec2("DescribeVpcEndpoints", "VpcEndpointId.1", endpointId);
+ }
+
+ @Test
+ void addRouteTableIdAssociatesTheRouteTable() {
+ Fixture f = fixture("10.90.0.0/16");
+
+ given()
+ .formParam("Action", "ModifyVpcEndpoint")
+ .formParam("VpcEndpointId", f.endpointId())
+ .formParam("AddRouteTableId.1", f.routeTableId())
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(hasXPath("//*[local-name()='ModifyVpcEndpointResponse']"
+ + "/*[local-name()='return']", equalTo("true")));
+
+ given()
+ .formParam("Action", "DescribeVpcEndpoints")
+ .formParam("VpcEndpointId.1", f.endpointId())
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(hasXPath("//*[local-name()='routeTableIdSet']/*[local-name()='item']",
+ equalTo(f.routeTableId())));
+ }
+
+ @Test
+ void removeRouteTableIdDisassociatesIt() {
+ Fixture f = fixture("10.91.0.0/16");
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "AddRouteTableId.1", f.routeTableId());
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "RemoveRouteTableId.1", f.routeTableId());
+
+ given()
+ .formParam("Action", "DescribeVpcEndpoints")
+ .formParam("VpcEndpointId.1", f.endpointId())
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(hasXPath("count(//*[local-name()='routeTableIdSet']/*[local-name()='item'])",
+ equalTo("0")));
+ }
+
+ @Test
+ void addingAnAlreadyAssociatedRouteTableDoesNotDuplicateIt() {
+ // AWS is idempotent here, and a duplicate would show as drift on the next plan.
+ Fixture f = fixture("10.92.0.0/16");
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "AddRouteTableId.1", f.routeTableId());
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "AddRouteTableId.1", f.routeTableId());
+
+ given()
+ .formParam("Action", "DescribeVpcEndpoints")
+ .formParam("VpcEndpointId.1", f.endpointId())
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(hasXPath("count(//*[local-name()='routeTableIdSet']/*[local-name()='item'])",
+ equalTo("1")));
+ }
+
+ @Test
+ void policyDocumentIsStoredAndReportedBack() {
+ Fixture f = fixture("10.93.0.0/16");
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "PolicyDocument", POLICY);
+
+ String xml = describe(f.endpointId());
+ org.junit.jupiter.api.Assertions.assertTrue(xml.contains("s3:GetObject"),
+ "expected the policy document to be reported back, got: " + xml);
+ }
+
+ @Test
+ void resetPolicyClearsTheDocument() {
+ Fixture f = fixture("10.94.0.0/16");
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "PolicyDocument", POLICY);
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "ResetPolicy", "true");
+
+ String xml = describe(f.endpointId());
+ org.junit.jupiter.api.Assertions.assertFalse(xml.contains("s3:GetObject"),
+ "expected ResetPolicy to clear the document, got: " + xml);
+ }
+
+ @Test
+ void createVpcEndpointHonoursAPolicyDocument() {
+ // Without this, an endpoint declared with a policy reads back without one and
+ // shows as drift on every plan even when ModifyVpcEndpoint is never called.
+ String vpcId = xmlValue(ec2("CreateVpc", "CidrBlock", "10.95.0.0/16"), "vpcId");
+ String endpointId = xmlValue(ec2("CreateVpcEndpoint",
+ "VpcId", vpcId,
+ "ServiceName", "com.amazonaws.us-east-1.s3",
+ "PolicyDocument", POLICY), "vpcEndpointId");
+
+ String xml = describe(endpointId);
+ org.junit.jupiter.api.Assertions.assertTrue(xml.contains("s3:GetObject"),
+ "expected the create-time policy to be reported back, got: " + xml);
+ }
+
+ @Test
+ void concurrentAssociationsAllSurvive() throws Exception {
+ // Terraform declares each aws_vpc_endpoint_route_table_association separately and
+ // applies them in parallel, so several ModifyVpcEndpoint calls arrive at one
+ // endpoint at once. A read-modify-write without a lock loses all but the last,
+ // and the losers' waiters poll for an association that was silently dropped:
+ // waiting for VPC Endpoint Route Table Association (vpce-.../rtb-...) to become
+ // available: couldn't find resource (21 retries)
+ //
+ // Driven through the service rather than over HTTP: requests through the test
+ // server are serialized enough that the HTTP path does not reliably reproduce the
+ // lost update, so an HTTP-level test would pass with the lock removed.
+ String vpcId = service.createVpc("us-east-1", "10.97.0.0/16", false).getVpcId();
+ String endpointId = service.createVpcEndpoint("us-east-1", vpcId,
+ "com.amazonaws.us-east-1.s3", "Gateway",
+ List.of(), List.of(), List.of(), null, null, List.of()).getVpcEndpointId();
+
+ int n = 16;
+ List<String> routeTableIds = new ArrayList<>();
+ for (int i = 0; i < n; i++) {
+ routeTableIds.add(service.createRouteTable("us-east-1", vpcId).getRouteTableId());
+ }
+
+ ExecutorService pool = Executors.newFixedThreadPool(n);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<?>> futures = new ArrayList<>();
+ for (String routeTableId : routeTableIds) {
+ futures.add(pool.submit(() -> {
+ start.await();
+ service.modifyVpcEndpoint("us-east-1", endpointId,
+ List.of(routeTableId), List.of(), List.of(), List.of(),
+ List.of(), List.of(), null, null, null);
+ return null;
+ }));
+ }
+ start.countDown();
+ for (Future<?> f : futures) {
+ f.get(30, TimeUnit.SECONDS);
+ }
+ pool.shutdown();
+
+ List<String> associated = service
+ .describeVpcEndpoints("us-east-1", List.of(endpointId), Map.of())
+ .getFirst().getRouteTableIds();
+ assertEquals(n, associated.size(),
+ "every concurrent association must survive; got " + associated);
+ }
+
+ @Test
+ void modifyingAnUnknownEndpointIsRejected() {
+ given()
+ .formParam("Action", "ModifyVpcEndpoint")
+ .formParam("VpcEndpointId", "vpce-does-not-exist")
+ .formParam("ResetPolicy", "true")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ // Assert the code, not just the status: UnsupportedOperation is also a 400, so a
+ // status-only assertion passes even when the action is not implemented at all.
+ .body(hasXPath("//*[local-name()='Code']", equalTo("InvalidVpcEndpointId.NotFound")));
+ }
+
+ @Test
+ void omittingVpcEndpointIdIsRejectedAsMissingParameter() {
+ // VpcEndpointId is the sole required member of ModifyVpcEndpointRequest. An absent
+ // required Query parameter is MissingParameter, not a lookup failure for the id "null".
+ given()
+ .formParam("Action", "ModifyVpcEndpoint")
+ .formParam("ResetPolicy", "true")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(hasXPath("//*[local-name()='Code']", equalTo("MissingParameter")));
+ }
+
+ @Test
+ void aPresentEmptyPolicyDocumentIsStoredRatherThanDropped() {
+ // The model gives PolicyDocument no `min`, so "present" is the only test the request
+ // supports; treating an empty string as absent would silently discard a supplied value.
+ Fixture f = fixture("10.98.0.0/16");
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "PolicyDocument", POLICY);
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "PolicyDocument", "");
+
+ assertEquals("", service
+ .describeVpcEndpoints("us-east-1", List.of(f.endpointId()), Map.of())
+ .getFirst().getPolicyDocument());
+ }
+
+ @Test
+ void anUnknownRouteTableIsRejectedWithoutMutatingTheEndpoint() {
+ Fixture f = fixture("10.96.0.0/16");
+ ec2("ModifyVpcEndpoint", "VpcEndpointId", f.endpointId(), "AddRouteTableId.1", f.routeTableId());
+
+ given()
+ .formParam("Action", "ModifyVpcEndpoint")
+ .formParam("VpcEndpointId", f.endpointId())
+ .formParam("AddRouteTableId.1", "rtb-does-not-exist")
+ .formParam("RemoveRouteTableId.1", f.routeTableId())
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(hasXPath("//*[local-name()='Code']", equalTo("InvalidRouteTableID.NotFound")));
+
+ // The valid removal in the same request must not have been applied.
+ given()
+ .formParam("Action", "DescribeVpcEndpoints")
+ .formParam("VpcEndpointId.1", f.endpointId())
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(hasXPath("//*[local-name()='routeTableIdSet']/*[local-name()='item']",
+ equalTo(f.routeTableId())));
+ }
+}
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 ff612c3ea0..f7bb5eb429 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
@@ -389,10 +389,10 @@ class Ec2ServiceTest {
Map.of("vpc-id", List.of(Ec2Service.defaultVpcId("us-east-1")))).getFirst().getSubnetId();
VpcEndpoint endpoint = service.createVpcEndpoint("us-east-1", Ec2Service.defaultVpcId("us-east-1"),
"com.amazonaws.us-east-1.s3", "Interface",
- List.of(), List.of(subnetId), List.of(), null, List.of());
+ List.of(), List.of(subnetId), List.of(), null, null, List.of());
service.createVpcEndpoint("us-east-1", Ec2Service.defaultVpcId("us-east-1"),
"com.amazonaws.us-east-1.dynamodb", "Gateway",
- List.of(), List.of(), List.of(), null, List.of());
+ List.of(), List.of(), List.of(), null, null, List.of());
List<NetworkInterface> enis = service.endpointNetworkInterfaces("us-east-1");