fix(lambda): hold the subnets a function's VpcConfig names (#8609)

On AWS a function's Hyperplane network interfaces sit in the subnets
its VpcConfig names, and EC2 refuses DeleteSubnet, and so DeleteVpc,
while one is there. Floci's Lambda never told EC2 a function used a
subnet, so DeleteSubnet succeeded under a VPC-configured function and
left it naming a subnet that was gone.

- LambdaService is a VpcDependencyProvider: a function of the caller's
  account, or a published version of one, holds each subnet its
  VpcConfig names and the VPC it is configured in
  (LambdaFunctionStore.listWithVersionsForAccount, which also reads a
  record stored before accounts were kept apart, unprefixed until it
  is next read).
- CreateFunction and UpdateFunctionConfiguration save a function that
  names subnets under EC2's subnet lock, so a DeleteSubnet either sees
  it or runs before it is stored. A VpcConfig the request set is
  resolved again under the lock, so a subnet deleted since the request
  was validated is unknown, as one never created is, and the function
  infers no VPC from it.

ECS awsvpc tasks already hold their subnet through the network
interface each task is given, which DeleteSubnet counts.

LambdaVpcResourceValidationIntegrationTest has DeleteSubnet refused
under a function, then under its published version once $LATEST moves
to another subnet, and allowed once the version is deleted, and a
subnet deleted while a function is created leaves it no inferred VPC.
LambdaFunctionStoreAccountScopeTest covers the unprefixed record.
ec2.md and lambda.md say so.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 15:04:43 -04:00
1 parent 3d6f59c064
commit 94fcf5cbf3
6 files changed
+159 -6

No files matched your search

+2 -2
View File
@@ -396,7 +396,7 @@ naming different VPCs find nothing.
|--------|-------------|
| CreateVpc | Creates a VPC with the requested CIDR block. `InstanceTenancy` accepts `default` or `dedicated`; `host` is rejected with `InvalidParameterValue`, as on AWS. `DryRun=true` is answered with `DryRunOperation` and creates nothing. A tag specification error keeps its own error; the CIDR block and the tenancy are checked only without `DryRun`. |
| 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. Docker network cleanup waits for an in-flight creation and prevents queued attaches from recreating the deleted network. 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, an attached internet gateway or egress-only internet gateway, a transit gateway attachment, an Elastic Load Balancing v2 load balancer, or anything still holding a network interface in one of its subnets: an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone network interface, or an interface endpoint. |
| DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Docker network cleanup waits for an in-flight creation and prevents queued attaches from recreating the deleted network. 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, an attached internet gateway or egress-only internet gateway, a transit gateway attachment, an Elastic Load Balancing v2 load balancer, or anything still holding a network interface in one of its subnets: an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone network interface, an interface endpoint, or a Lambda function or published version configured in the VPC. |
| ModifyVpcAttribute | Updates supported VPC attributes. |
| DescribeVpcAttribute | Returns a supported VPC attribute. |
| CreateDhcpOptions | Creates a DHCP options set with the supplied configurations and optional tags. |
@@ -422,7 +422,7 @@ private gateway lifecycles are not modelled.
|--------|-------------|
| CreateSubnet | Creates a subnet in a VPC. `DryRun=true` is answered with `DryRunOperation` and creates nothing. A tag specification error or a missing `VpcId` or VPC keeps its own error; the CIDR block, zone, IPv6 block and overlap with other subnets are checked only without `DryRun`. |
| DescribeSubnets | Lists or returns stored subnets. The `default-for-az` filter and its `defaultForAz` alias select default or non-default subnets; values are ORed and separate filters are ANDed. |
| DeleteSubnet | Deletes a subnet from the local EC2 store. Fails with `DependencyViolation` while the subnet still has a transit gateway attachment, an Elastic Load Balancing v2 load balancer, or anything holding a network interface in it: an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone network interface, or an interface endpoint. |
| DeleteSubnet | Deletes a subnet from the local EC2 store. Fails with `DependencyViolation` while the subnet still has a transit gateway attachment, an Elastic Load Balancing v2 load balancer, or anything holding a network interface in it: an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone network interface, an interface endpoint, or a Lambda function or published version whose `VpcConfig` names the subnet. |
| ModifySubnetAttribute | Updates supported subnet attributes. |
### Security Groups
+4
View File
@@ -1091,6 +1091,10 @@ A rejected update preserves the configuration and revision. Empty subnet and sec
group lists detach the function, and the response then omits `VpcConfig`. Published
versions retain their network configuration when `$LATEST` changes.
As on AWS, where a function's network interfaces sit in the subnets its `VpcConfig` names,
EC2's `DeleteSubnet` and `DeleteVpc` fail with `DependencyViolation` while a function, or a
published version of one, names the subnet or is configured in the VPC.
These checks validate the declaration. Function containers still use the configured
Docker network. With Docker-backed VPC networks (`FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=true`
and `FLOCI_SERVICES_EC2_MOCK=false`) and a known `VpcId`, the container also joins that VPC's
@@ -152,6 +152,25 @@ public class LambdaFunctionStore implements Resettable {
return backend.scan(key -> key.startsWith(prefix) && key.endsWith("::$LATEST"));
}
/**
* Lists an account's functions and their published versions without relying on request context, including one
* stored before accounts were kept apart, which stays unprefixed until it is next read.
*/
public List<LambdaFunction> listWithVersionsForAccount(String accountId, String region) {
String prefix = "lambda::" + region + "::";
if (backend instanceof AccountAwareStorageBackend<LambdaFunction> aware) {
List<LambdaFunction> functions = new ArrayList<>(
aware.scanForAccount(accountId, key -> key.startsWith(prefix)));
aware.scanRaw(rawKey -> rawKey.startsWith(prefix)).stream()
.filter(function -> belongsToAccount(function, accountId))
.forEach(functions::add);
return functions;
}
return backend.scan(key -> key.startsWith(prefix)).stream()
.filter(function -> belongsToAccount(function, accountId))
.toList();
}
/** Lists the caller's {@code $LATEST} functions without relying on request context. */
public List<LambdaFunction> listForAccount(String accountId, String region) {
String prefix = "lambda::" + region + "::";
@@ -23,6 +23,7 @@ import io.floci.aws.core.resource.SupportedResourceType;
import io.floci.aws.core.storage.StorageBackedMap;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.VpcDependencyProvider;
import io.floci.aws.services.ec2.model.SecurityGroup;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType;
@@ -93,7 +94,7 @@ import java.util.stream.Collectors;
* Business logic for Lambda function management and invocation.
*/
@ApplicationScoped
public class LambdaService implements ResourceProvider {
public class LambdaService implements ResourceProvider, VpcDependencyProvider {
private static final Logger LOG = Logger.getLogger(LambdaService.class);
@@ -695,7 +696,7 @@ public class LambdaService implements ResourceProvider {
}
}
functionStore.save(region, fn);
saveHoldingSubnets(region, fn, vpcConfig != null);
LOG.infov("Created Lambda function: {0} in region {1}", functionName, region);
if (Boolean.TRUE.equals(request.get("Publish"))) {
return publishVersion(region, functionName, null);
@@ -1220,7 +1221,7 @@ public class LambdaService implements ResourceProvider {
// Drain warm containers so the next invocation picks up the new configuration
warmPool.drainEnvironment(fn);
functionStore.save(region, fn);
saveHoldingSubnets(region, fn, requestedVpcConfigUpdate != null);
// LastUpdateStatus reports the last update of either kind, so this one replaces a failed sync's.
failedReactiveSyncs.remove(fn.getFunctionArn());
LOG.infov("Updated configuration for function: {0}", functionName);
@@ -2811,6 +2812,53 @@ public class LambdaService implements ResourceProvider {
}
}
// ─── VPC dependencies ────────────────────────────────────────────────────────
/**
* Whether a function of the caller's account, or a published version of one, names the subnet in its VpcConfig:
* Lambda creates a Hyperplane network interface in each subnet a function's VpcConfig names, and EC2 refuses
* DeleteSubnet while one is there.
*/
@Override
public boolean hasSubnetDependency(String region, String subnetId) {
return functionStore.listWithVersionsForAccount(regionResolver.getAccountId(), region).stream()
.anyMatch(fn -> namesSubnet(fn, subnetId));
}
/** Whether a function of the caller's account, or a version of one, is configured in the VPC. */
@Override
public boolean hasVpcDependency(String region, String vpcId) {
return functionStore.listWithVersionsForAccount(regionResolver.getAccountId(), region).stream()
.anyMatch(fn -> vpcId.equals(fn.getVpcId()));
}
private static boolean namesSubnet(LambdaFunction fn, String subnetId) {
Object subnets = fn.getVpcConfig() == null ? null : fn.getVpcConfig().get("SubnetIds");
return subnets instanceof List<?> list && list.contains(subnetId);
}
/**
* Saves a function, under EC2's subnet lock when its VpcConfig names subnets, so a DeleteSubnet or DeleteVpc
* either sees it or runs before it is stored, never between. A VpcConfig this request set is resolved again under
* the lock: a subnet deleted since the request was validated is then unknown, as one never created is, and the
* function infers no VPC from it.
*
* @param vpcConfigSet whether this request set the function's VpcConfig
*/
private void saveHoldingSubnets(String region, LambdaFunction fn, boolean vpcConfigSet) {
Object subnets = fn.getVpcConfig() == null ? null : fn.getVpcConfig().get("SubnetIds");
if (ec2Service != null && subnets instanceof List<?> list && !list.isEmpty()) {
ec2Service.runWithSubnetReferencesHeld(region, () -> {
if (vpcConfigSet) {
fn.setVpcId(resolveVpcId(region, fn.getVpcConfig()));
}
functionStore.save(region, fn);
});
} else {
functionStore.save(region, fn);
}
}
/** Resolve the common VPC only after every requested subnet and security group is validated. */
private String resolveVpcId(String region, Map<String, Object> vpcConfig) {
List<String> subnetIds = vpcResourceIds(vpcConfig, "SubnetIds");
@@ -1,6 +1,7 @@
package io.floci.aws.services.lambda;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.lambda.model.LambdaFunction;
import org.junit.jupiter.api.Test;
@@ -80,6 +81,28 @@ class LambdaFunctionStoreAccountScopeTest {
assertEquals(2, store.listAll().size());
}
/**
* A record stored before accounts were kept apart stays unprefixed until it is next read, and still holds the
* subnets its VpcConfig names, so the account's listing of functions and versions finds it.
*/
@Test
void listWithVersionsForAccountIncludesARecordStoredBeforeAccountsWereKeptApart() {
InMemoryStorage<String, LambdaFunction> raw = new InMemoryStorage<>();
LambdaFunctionStore store = new LambdaFunctionStore(
new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT));
store.saveForAccount(OTHER_ACCOUNT, REGION, function("current-fn", OTHER_ACCOUNT));
LambdaFunction legacyVersion = function("legacy-fn", OTHER_ACCOUNT);
legacyVersion.setVersion("1");
raw.put("lambda::" + REGION + "::legacy-fn::1", legacyVersion);
raw.put("lambda::" + REGION + "::legacy-default-fn::$LATEST", function("legacy-default-fn", DEFAULT_ACCOUNT));
raw.put("lambda::eu-west-1::legacy-elsewhere-fn::$LATEST", function("legacy-elsewhere-fn", OTHER_ACCOUNT));
assertEquals(List.of("current-fn", "legacy-fn"), store.listWithVersionsForAccount(OTHER_ACCOUNT, REGION)
.stream().map(LambdaFunction::getFunctionName).sorted().toList());
assertEquals(List.of("legacy-default-fn"), store.listWithVersionsForAccount(DEFAULT_ACCOUNT, REGION)
.stream().map(LambdaFunction::getFunctionName).toList());
}
private LambdaFunctionStore accountAwareStore() {
return new LambdaFunctionStore(AccountAwareStorageBackend.<LambdaFunction>inMemory(DEFAULT_ACCOUNT));
}
@@ -1,8 +1,10 @@
package io.floci.aws.services.lambda;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -14,6 +16,7 @@ import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.FunctionCode;
@@ -35,6 +38,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
@QuarkusTest
class LambdaVpcResourceValidationIntegrationTest {
@@ -52,6 +58,9 @@ class LambdaVpcResourceValidationIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@InjectSpy
Ec2Service ec2Service;
@BeforeEach
void createDeclaredNetworksAndRole() throws Exception {
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(
@@ -205,11 +214,61 @@ class LambdaVpcResourceValidationIntegrationTest {
&& (current.vpcId() == null || current.vpcId().isEmpty())));
}
/**
* A function, and a published version of it, hold the subnets their VpcConfig names, as their network interfaces
* do on AWS: DeleteSubnet is refused until neither names the subnet.
*/
@Test
void aFunctionAndItsVersionsHoldTheSubnetsTheirVpcConfigNames() {
createFunction(first.config());
assertEquals("DependencyViolation", subnetDeletionError(first.subnet()));
String version = lambda.publishVersion(r -> r.functionName(name)).version();
lambda.updateFunctionConfiguration(r -> r.functionName(name).vpcConfig(second.config()));
assertEquals("DependencyViolation", subnetDeletionError(first.subnet()), "the version still names it");
assertEquals("DependencyViolation", subnetDeletionError(second.subnet()));
lambda.deleteFunction(r -> r.functionName(name).qualifier(version));
ec2.deleteSubnet(r -> r.subnetId(first.subnet()));
}
/**
* A DeleteSubnet that runs after CreateFunction validated its subnets but before it stored the function sees no
* function naming the subnet and deletes it. The function then infers no VPC from it, as from a subnet never
* created, rather than storing the VPC of a subnet that is gone.
*/
@Test
void aSubnetDeletedWhileAFunctionIsCreatedLeavesItNoInferredVpc() {
doAnswer(invocation -> {
ec2.deleteSubnet(r -> r.subnetId(first.subnet()));
return invocation.callRealMethod();
}).when(ec2Service).runWithSubnetReferencesHeld(anyString(), any(Runnable.class));
createFunction(first.config());
assertEquals(List.of(first.subnet()), configuration().vpcConfig().subnetIds());
assertNull(configuration().vpcConfig().vpcId());
}
private String subnetDeletionError(String subnet) {
return assertThrows(Ec2Exception.class, () -> ec2.deleteSubnet(r -> r.subnetId(subnet)))
.awsErrorDetails().errorCode();
}
private Network network(String prefix) {
String vpc = ec2.createVpc(r -> r.cidrBlock(prefix + ".0.0/16")).vpc().vpcId();
cleanup.add(() -> ec2.deleteVpc(r -> r.vpcId(vpc)));
String subnet = ec2.createSubnet(r -> r.vpcId(vpc).cidrBlock(prefix + ".1.0/24")).subnet().subnetId();
cleanup.add(() -> ec2.deleteSubnet(r -> r.subnetId(subnet)));
cleanup.add(() -> {
try {
ec2.deleteSubnet(r -> r.subnetId(subnet));
} catch (Ec2Exception e) {
// A test may have deleted it already, once nothing held it.
if (!"InvalidSubnetID.NotFound".equals(e.awsErrorDetails().errorCode())) {
throw e;
}
}
});
String group = ec2.createSecurityGroup(
r -> r.vpcId(vpc).groupName(name).description("Declared Lambda network")).groupId();
cleanup.add(() -> ec2.deleteSecurityGroup(r -> r.groupId(group)));