feat(lambda): version network connectors as AWS does (#6595)

* feat(lambdamicrovms): version network connectors as AWS does

* fix(lambda): lock connector versions and refresh them after a CFN rollback

Updates, deletes and version reads hold one lock, so two updates cannot
take the same version number.

A CloudFormation rollback restores the connector through an update. On
AWS that makes the next version, and a later Fn::GetAtt returns it. The
resource now keeps that version in LatestVersion and LatestVersionArn.

Read the connector ARN through AwsArnUtils.parse.

AWS refuses LatestVersion, an integer, as a string Output, so the stack
test reads LatestVersionArn only.

* fix(lambda): type the connector LatestVersion attribute as an integer

AWS::Lambda::NetworkConnector declares LatestVersion as an integer. On AWS
a stack whose string Output reads it fails with "Template format error:
Every Value member must be a string.", and Fn::Sub refuses it with
"variable Connector.LatestVersion in Fn::Sub expression does not resolve
to a string".

* chore(lambda): share the connector version ARN and integer attribute helpers
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-26 08:38:47 -04:00
1 parent f32db4fe49
commit 3438a00daf
14 files changed
+650 -78

No files matched your search

@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
@@ -136,10 +137,12 @@ class CloudFormationLambdaMicrovmsIntegrationTest {
assertTrue(connectorArn.contains(":network-connector:nc-"), connectorArn);
assertEquals(connectorArn, created.get("ConnectorRef"), "Ref is the connector ARN, its primaryIdentifier");
assertEquals(created.get("ImageArn"), created.get("ImageRef"), "Ref is the image ARN, its primaryIdentifier");
assertEquals(connectorArn + ":1", created.get("ConnectorLatestVersionArn"));
cloudFormation(stackName, "UpdateStack", refTemplate(connectorName, "subnet-0cfn000000000002"));
Map<String, String> updated = outputs(describeStacks(stackName, "UPDATE_COMPLETE"));
assertEquals(connectorArn, updated.get("ConnectorRef"), "a subnet change updates the connector in place");
assertEquals(connectorArn + ":2", updated.get("ConnectorLatestVersionArn"));
given()
.when()
.get("/2026-04-04/network-connectors/" + connectorArn)
@@ -157,6 +160,49 @@ class CloudFormationLambdaMicrovmsIntegrationTest {
.statusCode(404));
}
@Test
void latestVersionIsAnIntegerSoAStringOutputFailsTheStack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-microvm-version-" + suffix;
String connectorName = "cfn-microvm-version-connector-" + suffix;
String template = """
{
"Resources": {
"Connector": {
"Type": "AWS::Lambda::NetworkConnector",
"Properties": {
"Name": "%s",
"OperatorRole": "arn:aws:iam::000000000000:role/cfn-microvm-connector-operator",
"Configuration": {
"VpcEgressConfiguration": {
"AssociatedComputeResourceTypes": ["WebFunction"],
"SubnetIds": ["subnet-0cfn000000000001"],
"SecurityGroupIds": ["sg-0cfn000000000001"],
"NetworkProtocol": "IPv4"
}
}
}
}
},
"Outputs": {
"LatestVersion": {"Value": {"Fn::GetAtt": ["Connector", "LatestVersion"]}}
}
}
""".formatted(connectorName);
cloudFormation(stackName, "CreateStack", template);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName, CFN_AUTH);
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
given()
.when()
.get("/2026-04-04/network-connectors/" + connectorName)
.then()
.statusCode(404);
cloudFormation(stackName, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stackName, CFN_AUTH);
}
private static String refTemplate(String connectorName, String subnetId) {
return """
{
@@ -190,7 +236,8 @@ class CloudFormationLambdaMicrovmsIntegrationTest {
"ImageRef": {"Value": {"Ref": "Image"}},
"ImageArn": {"Value": {"Fn::GetAtt": ["Image", "ImageArn"]}},
"ConnectorRef": {"Value": {"Ref": "Connector"}},
"ConnectorArn": {"Value": {"Fn::GetAtt": ["Connector", "Arn"]}}
"ConnectorArn": {"Value": {"Fn::GetAtt": ["Connector", "Arn"]}},
"ConnectorLatestVersionArn": {"Value": {"Fn::GetAtt": ["Connector", "LatestVersionArn"]}}
}
}
""".formatted(connectorName, subnetId);
@@ -210,6 +210,15 @@ class LambdaMicrovmsCfnProvisionerTest {
assertEquals(arn, r.getAttributes().get("Arn"));
assertEquals("nc-1", r.getAttributes().get("Id"));
assertEquals("nc", r.getAttributes().get("Name"));
assertEquals("1", r.getAttributes().get("LatestVersion"));
assertEquals(arn + ":1", r.getAttributes().get("LatestVersionArn"));
}
@Test
void latestVersionIsTheOnlyNumericConnectorAttribute() {
assertTrue(provisioner.attributeValue(CONNECTOR_TYPE, "LatestVersion", "2").isIntegralNumber());
assertTrue(provisioner.attributeValue(CONNECTOR_TYPE, "LatestVersionArn", "arn:2").isTextual());
assertTrue(provisioner.attributeValue("AWS::Lambda::MicrovmImage", "LatestVersion", "2").isTextual());
}
@Test
@@ -241,8 +250,12 @@ class LambdaMicrovmsCfnProvisionerTest {
prior.setPhysicalId(arn);
prior.getAttributes().put("Name", "nc");
when(service.getConnector(REGION, arn)).thenReturn(connector("nc-1", "nc"));
LambdaMicrovmsService.NetworkConnector attempted = connector("nc-1", "nc");
attempted.latestVersion = 2;
LambdaMicrovmsService.NetworkConnector restored = connector("nc-1", "nc");
restored.latestVersion = 3;
when(service.updateConnector(anyString(), anyString(), any(), any(), any(), any(), any()))
.thenReturn(connector("nc-1", "nc"));
.thenReturn(attempted, restored);
ObjectNode props = connectorProps("nc", "subnet-2");
props.put("OperatorRole", "arn:aws:iam::000000000000:role/operator-v2");
ObjectNode vpc = (ObjectNode) props.path("Configuration").path("VpcEgressConfiguration");
@@ -253,9 +266,12 @@ class LambdaMicrovmsCfnProvisionerTest {
verify(service).updateConnector(REGION, arn, List.of("subnet-2"), List.of("sg-1"),
"arn:aws:iam::000000000000:role/operator-v2", "DUAL_STACK", List.of("MICROVM"));
assertEquals(arn + ":2", updated.getAttributes().get("LatestVersionArn"));
assertTrue(provisioner.rollbackUpdate(updated));
verify(service).updateConnector(REGION, arn, List.of("subnet-1"), List.of("sg-1"), OPERATOR_ROLE, "IPv4",
List.of("MICROVM"));
assertEquals("3", updated.getAttributes().get("LatestVersion"));
assertEquals(arn + ":3", updated.getAttributes().get("LatestVersionArn"));
assertFalse(updated.getAttributes().containsKey(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR),
"the snapshot is spent");
}
@@ -7,8 +7,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
@@ -416,4 +418,142 @@ class LambdaMicrovmsIntegrationTest {
.statusCode(200)
.body("name", equalTo(name));
}
@Test
@Order(16)
void anUpdateThatChangesTheConnectorMakesTheNextVersion() {
String create = """
{
"Name": "microvm-it-versions",
"ClientToken": "microvm-it-token-versions",
"OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator",
"Configuration": { "VpcEgressConfiguration": {
"AssociatedComputeResourceTypes": ["WebFunction"],
"NetworkProtocol": "IPv4",
"SubnetIds": ["subnet-0000000000000ver1"],
"SecurityGroupIds": ["sg-0000000000000ver1"]
} }
}
""";
String arn = given().contentType("application/json").body(create)
.when().post(CORE + "/network-connectors")
.then().statusCode(202)
.body("Version", equalTo(1))
.body("State", equalTo("PENDING"))
.extract().path("Arn");
String id = arn.substring(arn.lastIndexOf(':') + 1);
given().when().get(CORE + "/network-connectors/microvm-it-versions")
.then().statusCode(200)
.body("Id", equalTo(id))
.body("LatestVersion", equalTo(1))
.body("LatestVersionArn", equalTo(arn + ":1"))
.body("$", not(hasKey("Version")));
String same = """
{ "Configuration": { "VpcEgressConfiguration": {
"SubnetIds": ["subnet-0000000000000ver1"], "SecurityGroupIds": ["sg-0000000000000ver1"] } } }
""";
given().contentType("application/json").body(same)
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(1))
.body("LastUpdateStatus", equalTo("Successful"))
.body("LastUpdateStatusReason", equalTo("No configuration changes detected"));
String moreSubnets = """
{ "Configuration": { "VpcEgressConfiguration": {
"SubnetIds": ["subnet-0000000000000ver1", "subnet-0000000000000ver2"] } } }
""";
given().contentType("application/json").body(moreSubnets)
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(2))
.body("VersionArn", equalTo(arn + ":2"))
.body("LastUpdateStatus", equalTo("InProgress"))
.body("LastUpdateStatusReason", equalTo("Update in progress"));
String reordered = """
{ "Configuration": { "VpcEgressConfiguration": {
"SubnetIds": ["subnet-0000000000000ver2", "subnet-0000000000000ver1"] } } }
""";
given().contentType("application/json").body(reordered)
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(2))
.body("LastUpdateStatusReason", equalTo("No configuration changes detected"))
.body("Configuration.VpcEgressConfiguration.SubnetIds",
contains("subnet-0000000000000ver1", "subnet-0000000000000ver2"));
given().contentType("application/json")
.body("""
{ "OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator-v2" }
""")
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(3));
given().when().get(CORE + "/network-connectors/" + arn)
.then().statusCode(200)
.body("LatestVersion", equalTo(3))
.body("StateReason", equalTo("Update initiated"))
.body("LastUpdateStatus", equalTo("Successful"))
.body("LastUpdateStatusReason", equalTo("Update was successful"));
given().when().get(CORE + "/network-connectors/" + id + ":1")
.then().statusCode(200)
.body("Version", equalTo(1))
.body("VersionArn", equalTo(arn + ":1"))
.body("StateReason", equalTo("Initial creation"))
.body("OperatorRole", equalTo("arn:aws:iam::000000000000:role/microvm-connector-operator"))
.body("Configuration.VpcEgressConfiguration.SubnetIds", contains("subnet-0000000000000ver1"))
.body("$", not(hasKey("LatestVersion")))
.body("$", not(hasKey("LastUpdateStatus")));
given().when().get(CORE + "/network-connectors/" + arn + ":2")
.then().statusCode(200)
.body("Version", equalTo(2))
.body("Configuration.VpcEgressConfiguration.SubnetIds",
contains("subnet-0000000000000ver1", "subnet-0000000000000ver2"));
given().when().get(CORE + "/network-connectors/" + arn + ":4")
.then().statusCode(404)
.body("message", equalTo("Network connector not found: " + arn + ":4"));
given().when().get(CORE + "/network-connectors/" + id + "/versions")
.then().statusCode(200)
.body("NetworkConnectorVersions.Version", contains(1, 2, 3))
.body("NetworkConnectorVersions[1].VersionArn", equalTo(arn + ":2"))
.body("NetworkConnectorVersions[1].StateReason", equalTo("Update initiated"));
given().when().get(CORE + "/network-connectors/" + id + ":9/versions")
.then().statusCode(400)
.body("message", equalTo("Identifier must not include a version qualifier"));
given().when().get(CORE + "/network-connectors")
.then().statusCode(200)
.body("NetworkConnectors.find { it.Id == '%s' }.LatestVersion".formatted(id), equalTo(3));
given().contentType("application/json")
.body("""
{ "Configuration": { "VpcEgressConfiguration": { "AssociatedComputeResourceTypes": ["MicroVm"] } } }
""")
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(400)
.body("message", equalTo("AssociatedComputeResourceTypes cannot be changed on an existing network"
+ " connector. Current: [WebFunction], requested: [MicroVm]."));
given().when().delete(CORE + "/network-connectors/" + id + ":3")
.then().statusCode(400)
.body("message", equalTo("Cannot delete the latest version of a network connector."));
given().when().delete(CORE + "/network-connectors/" + id + ":1")
.then().statusCode(202)
.body("Version", equalTo(1))
.body("State", equalTo("DELETING"))
.body("Configuration.VpcEgressConfiguration.SubnetIds", contains("subnet-0000000000000ver1"));
given().when().get(CORE + "/network-connectors/" + id + ":1")
.then().statusCode(404)
.body("message", equalTo("Network connector not found: " + arn + ":1"));
given().when().get(CORE + "/network-connectors/" + id + "/versions")
.then().statusCode(200)
.body("NetworkConnectorVersions.Version", contains(2, 3));
given().when().delete(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("State", equalTo("DELETING"))
.body("$", not(hasKey("Version")));
given().when().get(CORE + "/network-connectors/" + id)
.then().statusCode(404)
.body("message", equalTo("Network connector not found: " + arn));
}
}
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.lambdamicrovms;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
@@ -9,6 +12,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
@@ -154,6 +158,38 @@ class LambdaMicrovmsServicePersistenceTest {
* reached the backend. Only a JSON round trip separates state that was written from state that
* was merely mutated.
*/
@Test
void connectorVersionsSurviveARestart() {
LambdaMicrovmsService first = process();
String connectorId = createConnector(first);
first.updateConnector(REGION, connectorId, List.of("subnet-2"), null, null, null, null);
LambdaMicrovmsService reloaded = process();
assertEquals(2, reloaded.getConnector(REGION, connectorId).latestVersion);
assertEquals(List.of("subnet-1"),
reloaded.getConnectorVersion(REGION, connectorId + ":1").version().subnetIds);
}
@Test
void aConnectorStoredBeforeVersionsIsItsFirstVersion() throws IOException {
String connectorId = createConnector(process());
Path file = storageDir.resolve("lambda-network-connectors.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode stored = mapper.readTree(file.toFile());
stored.findParents("versions").forEach(node -> ((ObjectNode) node).remove(List.of("versions", "latestVersion")));
mapper.writeValue(file.toFile(), stored);
LambdaMicrovmsService.NetworkConnectorVersion first =
process().getConnectorVersion(REGION, connectorId + ":1").version();
assertEquals(List.of("subnet-1"), first.subnetIds);
}
private static String createConnector(LambdaMicrovmsService service) {
return service.createConnector(REGION, ACCOUNT_ID, "probe-connector",
List.of("subnet-1"), List.of("sg-1"), "arn:aws:iam::000000000000:role/operator",
"token-1", List.of("WebFunction"), "IPv4").id;
}
private static final class FileStorageFactory extends StorageFactory {
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
private final Path directory;
@@ -0,0 +1,61 @@
package io.github.hectorvent.floci.services.lambdamicrovms;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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 org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class LambdaMicrovmsServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000000";
@Test
void concurrentConnectorUpdatesEachMakeTheirOwnVersion() throws Exception {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
LambdaMicrovmsService service = new LambdaMicrovmsService(regionResolver, mock(StorageFactory.class));
LambdaMicrovmsService.NetworkConnector created = service.createConnector(REGION, ACCOUNT_ID, "concurrent",
List.of("subnet-00000000000000001"), List.of("sg-00000000000000000"),
"arn:aws:iam::000000000000:role/operator", "token", List.of("WebFunction"), "IPv4");
int updates = 16;
ExecutorService executor = Executors.newFixedThreadPool(updates);
CountDownLatch start = new CountDownLatch(1);
List<Future<LambdaMicrovmsService.NetworkConnector>> results = new ArrayList<>();
for (int i = 1; i <= updates; i++) {
List<String> groups = List.of(String.format("sg-%017d", i));
results.add(executor.submit(() -> {
start.await();
return service.updateConnector(REGION, created.id, null, groups, null, null, null);
}));
}
start.countDown();
Set<Long> versions = new HashSet<>();
for (Future<LambdaMicrovmsService.NetworkConnector> result : results) {
LambdaMicrovmsService.NetworkConnector updated = result.get(10, TimeUnit.SECONDS);
versions.add(updated.latestVersion);
LambdaMicrovmsService.ConnectorVersion named =
service.getConnectorVersion(REGION, created.id + ":" + updated.latestVersion);
assertEquals(updated.securityGroupIds, named.version().securityGroupIds);
}
executor.shutdown();
assertEquals(updates, versions.size());
assertEquals(updates + 1, service.getConnector(REGION, created.id).latestVersion);
assertEquals(updates + 1, service.listConnectorVersions(REGION, created.id).size());
}
}