mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(ec2): preserve security group deletion scope and dependencies (#7920)
* fix(ec2): preserve security group deletion scope and dependencies Coordinate group publication, attachment and deletion, preserve instance/interface group state, and reject invalid DryRun values before deletion. Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(ec2): tolerate absent persisted group dependency fields Keep unknown-state instance attachments blocking deletion while treating absent dependency collections as empty. Cover all nullable scan fields and missing identifiers without changing normal dependency semantics. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(ec2): roll back failed security group creation Retain the default rule identity before publication and compensate both group and rule writes when either store fails. Preserve the original exception and record cleanup failures without skipping the remaining cleanup. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(ec2): serialize group rule references with deletion Acquire the regional topology monitor before the source group monitor while resolving and publishing ingress and egress rules. Keep runtime reconciliation outside the mutation locks and preserve existing unknown-reference compatibility. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(ec2): retain groups used by Instance Connect endpoints Reject deletion before mutation when an Instance Connect endpoint uses the group. Return CannotDelete for default groups and reuse shared SDK clients in the existing fixtures. Signed-off-by: Andre Kurait <akurait@amazon.com> * refactor(ec2): share resource locks and deletion race helpers Reuse the reference-counted lock lifecycle for volume operations and instance group assignments. Keep scoped keys and lock ordering unchanged. Reuse deletion tasks and blocked-or-done observations without weakening race assertions. Signed-off-by: Andre Kurait <akurait@amazon.com> --------- Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
4b3b5cc211
commit
1820d6470d
12 files changed
+2205
-286
No files matched your search
@@ -0,0 +1,106 @@
|
||||
"""Security group deletion through the public EC2 API."""
|
||||
|
||||
import uuid
|
||||
from contextlib import ExitStack
|
||||
|
||||
import pytest
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def delete_if_present(client, group_id):
|
||||
try:
|
||||
client.delete_security_group(GroupId=group_id)
|
||||
except ClientError as error:
|
||||
if error.response["Error"]["Code"] != "InvalidGroup.NotFound":
|
||||
raise
|
||||
|
||||
|
||||
def create_group(client, cleanup, vpc, name=None):
|
||||
group = client.create_security_group(
|
||||
VpcId=vpc, GroupName=name or "delete-" + uuid.uuid4().hex,
|
||||
Description="SDK deletion contract",
|
||||
)["GroupId"]
|
||||
cleanup.callback(delete_if_present, client, group)
|
||||
return group
|
||||
|
||||
|
||||
def create_vpc(client, cleanup):
|
||||
vpc = client.create_vpc(CidrBlock="10.231.0.0/24")["Vpc"]["VpcId"]
|
||||
cleanup.callback(client.delete_vpc, VpcId=vpc)
|
||||
return vpc
|
||||
|
||||
|
||||
def test_delete_by_name_only_selects_the_default_vpc(ec2_client):
|
||||
default_vpc = ec2_client.describe_vpcs(
|
||||
Filters=[{"Name": "is-default", "Values": ["true"]}])["Vpcs"][0]["VpcId"]
|
||||
with ExitStack() as cleanup:
|
||||
vpc = create_vpc(ec2_client, cleanup)
|
||||
name = "same-name-" + uuid.uuid4().hex
|
||||
default_group = create_group(ec2_client, cleanup, default_vpc, name)
|
||||
custom_group = create_group(ec2_client, cleanup, vpc, name)
|
||||
assert ec2_client.delete_security_group(GroupName=name)["Return"]
|
||||
groups = ec2_client.describe_security_groups(
|
||||
Filters=[{"Name": "group-name", "Values": [name]}])["SecurityGroups"]
|
||||
assert [group["GroupId"] for group in groups] == [custom_group]
|
||||
assert all(group["GroupId"] != default_group for group in groups)
|
||||
with pytest.raises(ClientError) as caught:
|
||||
ec2_client.delete_security_group(GroupName=name)
|
||||
assert caught.value.response["Error"]["Code"] == "InvalidGroup.NotFound"
|
||||
assert ec2_client.describe_security_groups(
|
||||
GroupIds=[custom_group])["SecurityGroups"][0]["VpcId"] == vpc
|
||||
|
||||
|
||||
@pytest.mark.parametrize("direction", ["ingress", "egress"])
|
||||
def test_referenced_group_cannot_be_deleted(ec2_client, direction):
|
||||
with ExitStack() as cleanup:
|
||||
vpc = create_vpc(ec2_client, cleanup)
|
||||
target = create_group(ec2_client, cleanup, vpc)
|
||||
referrer = create_group(ec2_client, cleanup, vpc)
|
||||
permission = [{
|
||||
"IpProtocol": "tcp", "FromPort": 8443, "ToPort": 8443,
|
||||
"UserIdGroupPairs": [{"GroupId": target}],
|
||||
}]
|
||||
authorize = getattr(ec2_client, "authorize_security_group_" + direction)
|
||||
revoke = getattr(ec2_client, "revoke_security_group_" + direction)
|
||||
authorize(GroupId=referrer, IpPermissions=permission)
|
||||
with ExitStack() as rule_cleanup:
|
||||
rule_cleanup.callback(revoke, GroupId=referrer, IpPermissions=permission)
|
||||
with pytest.raises(ClientError) as caught:
|
||||
ec2_client.delete_security_group(GroupId=target)
|
||||
assert caught.value.response["Error"]["Code"] == "DependencyViolation"
|
||||
assert caught.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
|
||||
assert ec2_client.describe_security_groups(
|
||||
GroupIds=[target])["SecurityGroups"][0]["GroupId"] == target
|
||||
assert ec2_client.delete_security_group(GroupId=target)["Return"]
|
||||
|
||||
|
||||
def test_network_interface_prevents_group_deletion(ec2_client):
|
||||
with ExitStack() as cleanup:
|
||||
vpc = create_vpc(ec2_client, cleanup)
|
||||
subnet = ec2_client.create_subnet(
|
||||
VpcId=vpc, CidrBlock="10.231.0.0/26")["Subnet"]["SubnetId"]
|
||||
cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet)
|
||||
group = create_group(ec2_client, cleanup, vpc)
|
||||
interface = ec2_client.create_network_interface(
|
||||
SubnetId=subnet, Groups=[group])["NetworkInterface"]["NetworkInterfaceId"]
|
||||
with ExitStack() as interface_cleanup:
|
||||
interface_cleanup.callback(
|
||||
ec2_client.delete_network_interface, NetworkInterfaceId=interface)
|
||||
with pytest.raises(ClientError) as caught:
|
||||
ec2_client.delete_security_group(GroupId=group)
|
||||
assert caught.value.response["Error"]["Code"] == "DependencyViolation"
|
||||
assert ec2_client.describe_network_interfaces(
|
||||
NetworkInterfaceIds=[interface])["NetworkInterfaces"][0]["Groups"][0]["GroupId"] == group
|
||||
assert ec2_client.delete_security_group(GroupId=group)["Return"]
|
||||
|
||||
|
||||
def test_delete_dry_run_preserves_group_and_rules(ec2_client):
|
||||
with ExitStack() as cleanup:
|
||||
vpc = create_vpc(ec2_client, cleanup)
|
||||
group = create_group(ec2_client, cleanup, vpc)
|
||||
before = ec2_client.describe_security_groups(GroupIds=[group])["SecurityGroups"]
|
||||
with pytest.raises(ClientError) as caught:
|
||||
ec2_client.delete_security_group(GroupId=group, DryRun=True)
|
||||
assert caught.value.response["Error"]["Code"] == "DryRunOperation"
|
||||
assert caught.value.response["ResponseMetadata"]["HTTPStatusCode"] == 412
|
||||
assert ec2_client.describe_security_groups(GroupIds=[group])["SecurityGroups"] == before
|
||||
@@ -384,7 +384,7 @@ private gateway lifecycles are not modelled.
|
||||
|--------|-------------|
|
||||
| CreateSecurityGroup | Creates a security group in a VPC, the default VPC when `VpcId` is absent or empty. `DryRun=true` is answered with `DryRunOperation` and creates nothing. A tag specification error or a missing `GroupName`, `GroupDescription` or VPC keeps its own error; a taken group name is checked only without `DryRun`. |
|
||||
| DescribeSecurityGroups | Lists or returns stored security groups. |
|
||||
| DeleteSecurityGroup | Deletes a security group from the local EC2 store. |
|
||||
| DeleteSecurityGroup | Deletes a group and its rules by ID, or by name within the account and region's default VPC. Name lookup reports `VPCIdNotSpecified` when no default VPC exists. Default groups cannot be deleted. Existing network-interface, active-instance and other same-VPC group references report `DependencyViolation`; self-references do not prevent deletion. `DryRun` reports `DryRunOperation` without deleting the group or rules. Blank or malformed boolean values are rejected before deletion. |
|
||||
| AuthorizeSecurityGroupIngress | Adds inbound permissions. Sources may be IPv4 ranges, IPv6 ranges, or another security group (`UserIdGroupPairs`, sent on the wire as `Groups`); prefix list sources are not stored. One rule is stored per source, each carrying its own description. |
|
||||
| AuthorizeSecurityGroupEgress | Adds outbound permissions, with the same source types as the inbound call. |
|
||||
| RevokeSecurityGroupIngress | Removes inbound permissions. Matches on protocol and port range only, so it removes every permission on that port regardless of source. Protocol numbers and names match each other (`6` is `tcp`), and an all-traffic (`-1`) permission matches whatever ports the request names, as on AWS (Terraform revokes the default egress rule as `-1` with ports `0`). |
|
||||
|
||||
@@ -3649,10 +3649,15 @@ public class Ec2QueryHandler {
|
||||
}
|
||||
|
||||
private Response handleDeleteSecurityGroup(MultivaluedMap<String, String> p, String region) {
|
||||
String groupId = p.getFirst("GroupId");
|
||||
if (groupId == null) groupId = p.getFirst("GroupName");
|
||||
service.deleteSecurityGroup(region, groupId);
|
||||
return booleanResponse("DeleteSecurityGroup");
|
||||
String dryRun = p.getFirst("DryRun");
|
||||
if (dryRun != null && dryRun.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "DryRun is not a valid boolean.", 400);
|
||||
}
|
||||
String groupId = service.deleteSecurityGroup(region, p.getFirst("GroupId"), p.getFirst("GroupName"),
|
||||
Boolean.TRUE.equals(parseOptionalBoolean(dryRun, "DryRun")));
|
||||
return xmlResponse(new XmlBuilder().start("DeleteSecurityGroupResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString()).elem("return", "true")
|
||||
.elem("groupId", groupId).end("DeleteSecurityGroupResponse").build());
|
||||
}
|
||||
|
||||
private Response handleAuthorizeSecurityGroupIngress(MultivaluedMap<String, String> p, String region) {
|
||||
|
||||
@@ -341,6 +341,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// released between the launch's availability check and the store of its instance.
|
||||
private final Object hostLock = new Object();
|
||||
private final Set<String> seededAccountRegions = ConcurrentHashMap.newKeySet();
|
||||
// References held while a group assignment applies firewall state before publishing its instance.
|
||||
private final Map<String, Integer> pendingSecurityGroupAssignments = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, RefCountedLock> instanceGroupLocks = new ConcurrentHashMap<>();
|
||||
// region::subnetId → offset the next synthesised address is tried at. Only an ordering hint:
|
||||
// restart forgets it, and privateIpsInUse is what keeps addresses from being handed out twice.
|
||||
private final Map<String, Long> subnetIpCursors = new HashMap<>();
|
||||
@@ -4156,141 +4159,149 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (dryRun) {
|
||||
throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412);
|
||||
}
|
||||
synchronized (privateIpAllocationLock) {
|
||||
int admitted = !config.services().ec2().enforceVcpuQuotas() || spot || "host".equals(tenancy)
|
||||
? count : admittedInstanceCount(region, effectiveInstanceType, minCount, capacityMaxCount);
|
||||
synchronized (hostLock) {
|
||||
if (hostId != null) {
|
||||
// Re-checked under hostLock: a ReleaseHosts or ModifyHosts may have landed
|
||||
// since the unlocked check above.
|
||||
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
|
||||
}
|
||||
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni,
|
||||
privateIpAddress, admitted);
|
||||
for (int i = 0; i < admitted; i++) {
|
||||
String instanceId = "i-" + randomHex(17);
|
||||
String privateIp = privateIps.get(i);
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
if (finalSubnetId != null) {
|
||||
requireSubnet(region, finalSubnetId);
|
||||
}
|
||||
for (GroupIdentifier group : sgIdentifiers) {
|
||||
getRequiredSecurityGroup(region, group.getGroupId());
|
||||
}
|
||||
synchronized (privateIpAllocationLock) {
|
||||
int admitted = !config.services().ec2().enforceVcpuQuotas() || spot || "host".equals(tenancy)
|
||||
? count : admittedInstanceCount(region, effectiveInstanceType, minCount, capacityMaxCount);
|
||||
synchronized (hostLock) {
|
||||
if (hostId != null) {
|
||||
// Re-checked under hostLock: a ReleaseHosts or ModifyHosts may have landed
|
||||
// since the unlocked check above.
|
||||
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
|
||||
}
|
||||
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni,
|
||||
privateIpAddress, admitted);
|
||||
for (int i = 0; i < admitted; i++) {
|
||||
String instanceId = "i-" + randomHex(17);
|
||||
String privateIp = privateIps.get(i);
|
||||
|
||||
Instance inst = new Instance();
|
||||
inst.setInstanceId(instanceId);
|
||||
inst.setOwnerId(callerAccountId());
|
||||
inst.setImageId(imageId);
|
||||
inst.setState(InstanceState.pending());
|
||||
inst.setInstanceType(effectiveInstanceType);
|
||||
inst.setSpot(spot);
|
||||
inst.setCapacityReservationPlatform(capacityReservationPlatform(region, imageId));
|
||||
inst.setCapacityReservationPreference(capacityTargetId == null ? capacityPreference : null);
|
||||
inst.setCapacityReservationTarget(capacityTargetId);
|
||||
inst.setCapacityReservationGroupArn(capacityGroupArn);
|
||||
Placement placement = new Placement(az);
|
||||
placement.setHostId(hostId);
|
||||
if (tenancy != null && !tenancy.isBlank()) {
|
||||
placement.setTenancy(tenancy);
|
||||
}
|
||||
inst.setPlacement(placement);
|
||||
inst.setSubnetId(finalSubnetId);
|
||||
inst.setVpcId(vpcId);
|
||||
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
|
||||
// override wins in both directions; the subnet's MapPublicIpOnLaunch
|
||||
// attribute is only the default when the launch does not specify it. An
|
||||
// interface the caller created never takes an automatic address.
|
||||
inst.setAssociatePublicIp(suppliedEni == null && (associatePublicIp != null
|
||||
? associatePublicIp
|
||||
: subnet != null && subnet.isMapPublicIpOnLaunch()));
|
||||
inst.setPrivateIpAddress(privateIp);
|
||||
inst.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(privateIp, region));
|
||||
inst.setKeyName(keyName);
|
||||
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
|
||||
inst.setArchitecture(architecture);
|
||||
inst.setLaunchTime(Instant.now());
|
||||
inst.setAmiLaunchIndex(i);
|
||||
inst.setClientToken(clientToken);
|
||||
inst.setRegion(region);
|
||||
inst.setUserData(userData);
|
||||
inst.setEncodedUserData(encodedUserData);
|
||||
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
|
||||
if (launchProfile != null) {
|
||||
inst.setIamInstanceProfileId(launchProfile.getInstanceProfileId());
|
||||
inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime());
|
||||
}
|
||||
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
|
||||
inst.setCreditSpecificationCpuCredits(
|
||||
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
|
||||
if (instanceTags != null && !instanceTags.isEmpty()) {
|
||||
inst.setTags(new ArrayList<>(instanceTags));
|
||||
putTags(region, instanceId, new ArrayList<>(instanceTags));
|
||||
}
|
||||
|
||||
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
|
||||
// floci-kt9) or a freshly-minted implicit primary interface.
|
||||
InstanceNetworkInterface eni = new InstanceNetworkInterface();
|
||||
eni.setNetworkInterfaceId(suppliedEni != null
|
||||
? suppliedEni.getNetworkInterfaceId()
|
||||
: "eni-" + randomHex(17));
|
||||
eni.setSubnetId(finalSubnetId);
|
||||
eni.setVpcId(vpcId);
|
||||
eni.setOwnerId(callerAccountId());
|
||||
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
|
||||
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
|
||||
eni.setPrivateIpAddress(privateIp);
|
||||
eni.setPrivateDnsName(inst.getPrivateDnsName());
|
||||
eni.setGroups(new ArrayList<>(sgIdentifiers));
|
||||
eni.setAttachmentId("eni-attach-" + randomHex(17));
|
||||
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
|
||||
if (inst.getLaunchTime() != null) {
|
||||
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
|
||||
}
|
||||
inst.getNetworkInterfaces().add(eni);
|
||||
if (suppliedEni != null) {
|
||||
// The standalone record stays authoritative rather than being folded into the
|
||||
// instance: AWS defaults deleteOnTermination to false for an interface the caller
|
||||
// created and handed to a launch, so it outlives the instance and returns to
|
||||
// "available" on termination instead of vanishing with it. Double-counting is
|
||||
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
|
||||
// id the standalone store owns.
|
||||
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
|
||||
launchAttachment.setAttachmentId(eni.getAttachmentId());
|
||||
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
|
||||
launchAttachment.setStatus("attached");
|
||||
launchAttachment.setInstanceId(instanceId);
|
||||
launchAttachment.setInstanceOwnerId(callerAccountId());
|
||||
launchAttachment.setAttachTime(eni.getAttachTime());
|
||||
launchAttachment.setDeleteOnTermination(false);
|
||||
suppliedEni.setAttachment(launchAttachment);
|
||||
suppliedEni.setStatus("in-use");
|
||||
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
|
||||
// An Elastic IP the interface kept from an earlier instance is this one's
|
||||
// public address; with a container, the launch re-points it once it runs.
|
||||
Address carried = primaryElasticAddress(region, inst);
|
||||
if (carried != null) {
|
||||
setPublicAddress(inst, carried.getPublicIp());
|
||||
Instance inst = new Instance();
|
||||
inst.setInstanceId(instanceId);
|
||||
inst.setOwnerId(callerAccountId());
|
||||
inst.setImageId(imageId);
|
||||
inst.setState(InstanceState.pending());
|
||||
inst.setInstanceType(effectiveInstanceType);
|
||||
inst.setSpot(spot);
|
||||
inst.setCapacityReservationPlatform(capacityReservationPlatform(region, imageId));
|
||||
inst.setCapacityReservationPreference(capacityTargetId == null ? capacityPreference : null);
|
||||
inst.setCapacityReservationTarget(capacityTargetId);
|
||||
inst.setCapacityReservationGroupArn(capacityGroupArn);
|
||||
Placement placement = new Placement(az);
|
||||
placement.setHostId(hostId);
|
||||
if (tenancy != null && !tenancy.isBlank()) {
|
||||
placement.setTenancy(tenancy);
|
||||
}
|
||||
}
|
||||
|
||||
inst.setRootDeviceName(rootDeviceName);
|
||||
for (LaunchVolume planned : launchVolumes) {
|
||||
Volume volume = newVolume(region, az, planned.volumeType(), planned.size(),
|
||||
planned.encrypted(), planned.kmsKeyId(), planned.iops(), planned.throughput(),
|
||||
planned.snapshotId());
|
||||
volume.setState("in-use");
|
||||
VolumeAttachment attachment = new VolumeAttachment();
|
||||
attachment.setVolumeId(volume.getVolumeId());
|
||||
attachment.setInstanceId(instanceId);
|
||||
attachment.setDevice(planned.deviceName());
|
||||
attachment.setState("attached");
|
||||
attachment.setDeleteOnTermination(planned.deleteOnTermination());
|
||||
attachment.setAttachTime(inst.getLaunchTime());
|
||||
volume.getAttachments().add(attachment);
|
||||
volumes.put(key(region, volume.getVolumeId()), volume);
|
||||
reservation.getLaunchVolumeIds().add(volume.getVolumeId());
|
||||
if (rootDeviceName.equals(planned.deviceName())) {
|
||||
inst.setRootVolumeId(volume.getVolumeId());
|
||||
inst.setPlacement(placement);
|
||||
inst.setSubnetId(finalSubnetId);
|
||||
inst.setVpcId(vpcId);
|
||||
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
|
||||
// override wins in both directions; the subnet's MapPublicIpOnLaunch
|
||||
// attribute is only the default when the launch does not specify it. An
|
||||
// interface the caller created never takes an automatic address.
|
||||
inst.setAssociatePublicIp(suppliedEni == null && (associatePublicIp != null
|
||||
? associatePublicIp
|
||||
: subnet != null && subnet.isMapPublicIpOnLaunch()));
|
||||
inst.setPrivateIpAddress(privateIp);
|
||||
inst.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(privateIp, region));
|
||||
inst.setKeyName(keyName);
|
||||
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
|
||||
inst.setArchitecture(architecture);
|
||||
inst.setLaunchTime(Instant.now());
|
||||
inst.setAmiLaunchIndex(i);
|
||||
inst.setClientToken(clientToken);
|
||||
inst.setRegion(region);
|
||||
inst.setUserData(userData);
|
||||
inst.setEncodedUserData(encodedUserData);
|
||||
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
|
||||
if (launchProfile != null) {
|
||||
inst.setIamInstanceProfileId(launchProfile.getInstanceProfileId());
|
||||
inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime());
|
||||
}
|
||||
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
|
||||
inst.setCreditSpecificationCpuCredits(
|
||||
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
|
||||
if (instanceTags != null && !instanceTags.isEmpty()) {
|
||||
inst.setTags(new ArrayList<>(instanceTags));
|
||||
putTags(region, instanceId, new ArrayList<>(instanceTags));
|
||||
}
|
||||
}
|
||||
|
||||
instances.put(key(region, instanceId), inst);
|
||||
launched.add(inst);
|
||||
reservation.getInstances().add(inst);
|
||||
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
|
||||
// floci-kt9) or a freshly-minted implicit primary interface.
|
||||
InstanceNetworkInterface eni = new InstanceNetworkInterface();
|
||||
eni.setNetworkInterfaceId(suppliedEni != null
|
||||
? suppliedEni.getNetworkInterfaceId()
|
||||
: "eni-" + randomHex(17));
|
||||
eni.setSubnetId(finalSubnetId);
|
||||
eni.setVpcId(vpcId);
|
||||
eni.setOwnerId(callerAccountId());
|
||||
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
|
||||
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
|
||||
eni.setPrivateIpAddress(privateIp);
|
||||
eni.setPrivateDnsName(inst.getPrivateDnsName());
|
||||
eni.setGroups(new ArrayList<>(sgIdentifiers));
|
||||
eni.setAttachmentId("eni-attach-" + randomHex(17));
|
||||
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
|
||||
if (inst.getLaunchTime() != null) {
|
||||
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
|
||||
}
|
||||
inst.getNetworkInterfaces().add(eni);
|
||||
if (suppliedEni != null) {
|
||||
// The standalone record stays authoritative rather than being folded into the
|
||||
// instance: AWS defaults deleteOnTermination to false for an interface the caller
|
||||
// created and handed to a launch, so it outlives the instance and returns to
|
||||
// "available" on termination instead of vanishing with it. Double-counting is
|
||||
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
|
||||
// id the standalone store owns.
|
||||
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
|
||||
launchAttachment.setAttachmentId(eni.getAttachmentId());
|
||||
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
|
||||
launchAttachment.setStatus("attached");
|
||||
launchAttachment.setInstanceId(instanceId);
|
||||
launchAttachment.setInstanceOwnerId(callerAccountId());
|
||||
launchAttachment.setAttachTime(eni.getAttachTime());
|
||||
launchAttachment.setDeleteOnTermination(false);
|
||||
suppliedEni.setAttachment(launchAttachment);
|
||||
suppliedEni.setStatus("in-use");
|
||||
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
|
||||
// An Elastic IP the interface kept from an earlier instance is this one's
|
||||
// public address; with a container, the launch re-points it once it runs.
|
||||
Address carried = primaryElasticAddress(region, inst);
|
||||
if (carried != null) {
|
||||
setPublicAddress(inst, carried.getPublicIp());
|
||||
}
|
||||
}
|
||||
|
||||
inst.setRootDeviceName(rootDeviceName);
|
||||
for (LaunchVolume planned : launchVolumes) {
|
||||
Volume volume = newVolume(region, az, planned.volumeType(), planned.size(),
|
||||
planned.encrypted(), planned.kmsKeyId(), planned.iops(), planned.throughput(),
|
||||
planned.snapshotId());
|
||||
volume.setState("in-use");
|
||||
VolumeAttachment attachment = new VolumeAttachment();
|
||||
attachment.setVolumeId(volume.getVolumeId());
|
||||
attachment.setInstanceId(instanceId);
|
||||
attachment.setDevice(planned.deviceName());
|
||||
attachment.setState("attached");
|
||||
attachment.setDeleteOnTermination(planned.deleteOnTermination());
|
||||
attachment.setAttachTime(inst.getLaunchTime());
|
||||
volume.getAttachments().add(attachment);
|
||||
volumes.put(key(region, volume.getVolumeId()), volume);
|
||||
reservation.getLaunchVolumeIds().add(volume.getVolumeId());
|
||||
if (rootDeviceName.equals(planned.deviceName())) {
|
||||
inst.setRootVolumeId(volume.getVolumeId());
|
||||
}
|
||||
}
|
||||
|
||||
instances.put(key(region, instanceId), inst);
|
||||
launched.add(inst);
|
||||
reservation.getInstances().add(inst);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5834,37 +5845,69 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
*/
|
||||
public void modifyInstanceGroups(String region, String instanceId, List<String> groupIds) {
|
||||
ensureDefaultResources(region);
|
||||
String instanceKey = callerAccountId() + "::" + key(region, instanceId);
|
||||
// This per-instance lock precedes the topology lock; external I/O holds only this lock.
|
||||
withResourceLock(instanceGroupLocks, instanceKey, () -> {
|
||||
modifyInstanceGroupsLocked(region, instanceId, groupIds);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void modifyInstanceGroupsLocked(String region, String instanceId, List<String> groupIds) {
|
||||
Instance inst = getRequiredInstance(region, instanceId);
|
||||
|
||||
List<GroupIdentifier> identifiers = new ArrayList<>();
|
||||
for (String groupId : groupIds) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
if (!Objects.equals(inst.getVpcId(), sg.getVpcId())) {
|
||||
throw new AwsException("InvalidGroup.NotFound", "Security group is not in the instance VPC", 400);
|
||||
List<String> protectedGroups = new ArrayList<>();
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
for (String groupId : groupIds) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
if (!Objects.equals(inst.getVpcId(), sg.getVpcId())) {
|
||||
throw new AwsException("InvalidGroup.NotFound", "Security group is not in the instance VPC", 400);
|
||||
}
|
||||
identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
|
||||
protectedGroups.add(callerAccountId() + "::" + key(region, sg.getGroupId()));
|
||||
}
|
||||
identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
|
||||
protectedGroups.forEach(group -> pendingSecurityGroupAssignments.merge(group, 1, Integer::sum));
|
||||
}
|
||||
|
||||
if (securityGroupEnforcementEnabled() && !config.services().ec2().mock()
|
||||
&& inst.getState() != null && "running".equals(inst.getState().getName())
|
||||
&& inst.getNetworkInterfaces() != null && !inst.getNetworkInterfaces().isEmpty()) {
|
||||
List<SecurityGroup> current = securityGroups.scan(k -> k.startsWith(region + "::"));
|
||||
Map<String, SecurityGroup> byId = current.stream().collect(Collectors.toMap(
|
||||
SecurityGroup::getGroupId, Function.identity()));
|
||||
containerManager.updateSecurityGroups(inst.getNetworkInterfaces().getFirst().getNetworkInterfaceId(),
|
||||
new HashSet<>(groupIds), byId, policyPrefixLists(region, current));
|
||||
}
|
||||
try {
|
||||
if (securityGroupEnforcementEnabled() && !config.services().ec2().mock()
|
||||
&& inst.getState() != null && "running".equals(inst.getState().getName())
|
||||
&& inst.getNetworkInterfaces() != null && !inst.getNetworkInterfaces().isEmpty()) {
|
||||
List<SecurityGroup> current = securityGroups.scan(k -> k.startsWith(region + "::"));
|
||||
Map<String, SecurityGroup> byId = current.stream().collect(Collectors.toMap(
|
||||
SecurityGroup::getGroupId, Function.identity()));
|
||||
containerManager.updateSecurityGroups(inst.getNetworkInterfaces().getFirst().getNetworkInterfaceId(),
|
||||
new HashSet<>(groupIds), byId, policyPrefixLists(region, current));
|
||||
}
|
||||
|
||||
inst.setSecurityGroups(new ArrayList<>(identifiers));
|
||||
if (inst.getNetworkInterfaces() != null) {
|
||||
inst.getNetworkInterfaces().forEach(eni -> eni.setGroups(new ArrayList<>(identifiers)));
|
||||
}
|
||||
instances.put(key(region, instanceId), inst);
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
inst.setSecurityGroups(new ArrayList<>(identifiers));
|
||||
if (inst.getNetworkInterfaces() != null) {
|
||||
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
|
||||
eni.setGroups(new ArrayList<>(identifiers));
|
||||
networkInterfaces.get(key(region, eni.getNetworkInterfaceId())).ifPresent(stored -> {
|
||||
NetworkInterfaceAttachment attachment = stored.getAttachment();
|
||||
if (attachment != null && instanceId.equals(attachment.getInstanceId())) {
|
||||
stored.setGroups(new ArrayList<>(identifiers));
|
||||
networkInterfaces.put(key(region, stored.getNetworkInterfaceId()), stored);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
instances.put(key(region, instanceId), inst);
|
||||
}
|
||||
|
||||
if (config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock()
|
||||
&& inst.getDockerContainerId() != null
|
||||
&& inst.getState() != null && "running".equals(inst.getState().getName())) {
|
||||
portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));
|
||||
if (config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock()
|
||||
&& inst.getDockerContainerId() != null
|
||||
&& inst.getState() != null && "running".equals(inst.getState().getName())) {
|
||||
portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));
|
||||
}
|
||||
} finally {
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
protectedGroups.forEach(group -> pendingSecurityGroupAssignments.computeIfPresent(
|
||||
group, (ignored, count) -> count == 1 ? null : count - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6864,10 +6907,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
endpoint.setPolicyDocument(policyDocument);
|
||||
if (endpointTags != null && !endpointTags.isEmpty()) {
|
||||
endpoint.setTags(new ArrayList<>(endpointTags));
|
||||
putTags(region, endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags));
|
||||
}
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
getRequiredVpc(region, vpcId);
|
||||
for (String securityGroupId : securityGroupIds) {
|
||||
getRequiredSecurityGroup(region, securityGroupId);
|
||||
}
|
||||
if (endpointTags != null && !endpointTags.isEmpty()) {
|
||||
putTags(region, endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags));
|
||||
}
|
||||
vpcEndpoints.put(key(region, endpoint.getVpcEndpointId()), endpoint);
|
||||
}
|
||||
return endpoint;
|
||||
@@ -6931,11 +6979,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// 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, subnetConfigurations, ipAddressType);
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
synchronized (lockFor(key(region, endpointId))) {
|
||||
return modifyVpcEndpointLocked(region, endpointId,
|
||||
addRouteTableIds, removeRouteTableIds, addSubnetIds, removeSubnetIds,
|
||||
addSecurityGroupIds, removeSecurityGroupIds,
|
||||
policyDocument, resetPolicy, privateDnsEnabled, subnetConfigurations, ipAddressType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7083,11 +7133,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
ensureDefaultResources(region);
|
||||
List<VpcEndpoint> deleted = new ArrayList<>();
|
||||
for (String endpointId : endpointIds) {
|
||||
VpcEndpoint endpoint = getRequiredVpcEndpoint(region, endpointId);
|
||||
endpoint.setState("deleted");
|
||||
vpcEndpoints.delete(key(region, endpointId));
|
||||
removeTags(region, endpointId);
|
||||
deleted.add(endpoint);
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
synchronized (lockFor(key(region, endpointId))) {
|
||||
VpcEndpoint endpoint = getRequiredVpcEndpoint(region, endpointId);
|
||||
endpoint.setState("deleted");
|
||||
vpcEndpoints.delete(key(region, endpointId));
|
||||
removeTags(region, endpointId);
|
||||
deleted.add(endpoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
@@ -7804,14 +7858,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
public SecurityGroup createSecurityGroup(String region, String groupName, String description, String vpcId) {
|
||||
vpcId = requireSecurityGroupVpc(region, vpcId).getVpcId();
|
||||
// Check duplicate
|
||||
String finalVpcId = vpcId;
|
||||
boolean exists = securityGroups.scan(k -> true).stream()
|
||||
.anyMatch(sg -> sg.getRegion().equals(region) && Objects.equals(sg.getGroupName(), groupName)
|
||||
&& finalVpcId.equals(sg.getVpcId()));
|
||||
if (exists) {
|
||||
throw new AwsException("InvalidGroup.Duplicate", "The security group '" + groupName + "' already exists", 400);
|
||||
}
|
||||
String sgId = "sg-" + randomHex(17);
|
||||
SecurityGroup sg = new SecurityGroup();
|
||||
sg.setGroupId(sgId);
|
||||
@@ -7827,14 +7873,46 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
sg.getIpPermissionsEgress().add(egressAll);
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
getRequiredVpc(region, sg.getVpcId());
|
||||
securityGroups.put(key(region, sgId), sg);
|
||||
boolean exists = securityGroups.scan(k -> true).stream()
|
||||
.anyMatch(existing -> existing.getRegion().equals(region)
|
||||
&& Objects.equals(existing.getGroupName(), groupName)
|
||||
&& sg.getVpcId().equals(existing.getVpcId()));
|
||||
if (exists) {
|
||||
throw new AwsException("InvalidGroup.Duplicate",
|
||||
"The security group '" + groupName + "' already exists", 400);
|
||||
}
|
||||
SecurityGroupRule defaultRule = newRule(sgId, egressAll, true);
|
||||
defaultRule.setCidrIpv4("0.0.0.0/0");
|
||||
try {
|
||||
securityGroups.put(key(region, sgId), sg);
|
||||
// Publish the default rule before a concurrent delete can remove this group.
|
||||
securityGroupRules.put(key(region, defaultRule.getSecurityGroupRuleId()), defaultRule);
|
||||
} catch (RuntimeException failure) {
|
||||
rollbackSecurityGroupCreation(region, sgId, defaultRule.getSecurityGroupRuleId(), failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
// Persist the default egress rule as a SecurityGroupRule so that
|
||||
// DescribeSecurityGroupRules can find it immediately (#1093).
|
||||
createRules(region, sgId, egressAll, true);
|
||||
return sg;
|
||||
}
|
||||
|
||||
private void rollbackSecurityGroupCreation(String region, String groupId, String ruleId,
|
||||
RuntimeException failure) {
|
||||
try {
|
||||
securityGroupRules.delete(key(region, ruleId));
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
LOG.errorv(cleanupFailure, "Failed to remove default rule {0} after group creation failed in {1}",
|
||||
ruleId, region);
|
||||
}
|
||||
try {
|
||||
securityGroups.delete(key(region, groupId));
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
LOG.errorv(cleanupFailure, "Failed to remove security group {0} after creation failed in {1}",
|
||||
groupId, region);
|
||||
}
|
||||
}
|
||||
|
||||
public List<SecurityGroup> describeSecurityGroups(String region, List<String> groupIds,
|
||||
List<String> groupNames, Map<String, List<String>> filters) {
|
||||
return describeSecurityGroups(region, groupIds, groupNames, filterList(filters));
|
||||
@@ -7879,27 +7957,102 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
|
||||
public void deleteSecurityGroup(String region, String groupId) {
|
||||
ensureDefaultResources(region);
|
||||
if (securityGroups.get(key(region, groupId)).isEmpty()) {
|
||||
throw new AwsException("InvalidGroup.NotFound", "The security group '" + groupId + "' does not exist", 400);
|
||||
deleteSecurityGroup(region, groupId, null, false);
|
||||
}
|
||||
|
||||
public String deleteSecurityGroup(String region, String groupId, String groupName, boolean dryRun) {
|
||||
if ((groupId == null || groupId.isBlank()) && (groupName == null || groupName.isBlank())) {
|
||||
throw new AwsException("MissingParameter", "The request must contain GroupId or GroupName", 400);
|
||||
}
|
||||
securityGroups.delete(key(region, groupId));
|
||||
ensureDefaultResources(region);
|
||||
String selectedId = groupId;
|
||||
if (selectedId == null || selectedId.isBlank()) {
|
||||
Vpc defaultVpc = vpcs.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(Vpc::isDefault).findFirst().orElseThrow(() ->
|
||||
new AwsException("VPCIdNotSpecified", "No default VPC for this user", 400));
|
||||
selectedId = securityGroups.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(group -> defaultVpc.getVpcId().equals(group.getVpcId())
|
||||
&& groupName.equals(group.getGroupName()))
|
||||
.map(SecurityGroup::getGroupId).findFirst().orElseThrow(() ->
|
||||
new AwsException("InvalidGroup.NotFound",
|
||||
"The security group '" + groupName + "' does not exist in the default VPC", 400));
|
||||
}
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
synchronized (lockFor(key(region, selectedId))) {
|
||||
SecurityGroup selected = getRequiredSecurityGroup(region, selectedId);
|
||||
if ("default".equals(selected.getGroupName())) {
|
||||
throw new AwsException("CannotDelete", "The default security group cannot be deleted", 400);
|
||||
}
|
||||
if (hasSecurityGroupDependencies(region, selected)) {
|
||||
throw new AwsException("DependencyViolation",
|
||||
"The security group '" + selectedId + "' has a dependent object", 400);
|
||||
}
|
||||
if (dryRun) {
|
||||
throw new AwsException("DryRunOperation",
|
||||
"Request would have succeeded, but DryRun flag is set.", 412);
|
||||
}
|
||||
securityGroups.delete(key(region, selectedId));
|
||||
removeTags(region, selectedId);
|
||||
securityGroupRules.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(rule -> selected.getGroupId().equals(rule.getGroupId()))
|
||||
.forEach(rule -> {
|
||||
securityGroupRules.delete(key(region, rule.getSecurityGroupRuleId()));
|
||||
removeTags(region, rule.getSecurityGroupRuleId());
|
||||
});
|
||||
}
|
||||
}
|
||||
return selectedId;
|
||||
}
|
||||
|
||||
private boolean hasSecurityGroupDependencies(String region, SecurityGroup selected) {
|
||||
String groupId = selected.getGroupId();
|
||||
if (pendingSecurityGroupAssignments.containsKey(callerAccountId() + "::" + key(region, groupId))) {
|
||||
return true;
|
||||
}
|
||||
if (networkInterfaces.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.anyMatch(eni -> nullToEmpty(eni.getGroups()).stream().anyMatch(group -> groupId.equals(group.getGroupId())))) {
|
||||
return true;
|
||||
}
|
||||
if (instances.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(instance -> instance.getState() == null || !"terminated".equals(instance.getState().getName()))
|
||||
.anyMatch(instance -> nullToEmpty(instance.getSecurityGroups()).stream()
|
||||
.anyMatch(group -> groupId.equals(group.getGroupId())))) {
|
||||
return true;
|
||||
}
|
||||
if (vpcEndpoints.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.anyMatch(endpoint -> nullToEmpty(endpoint.getSecurityGroupIds()).contains(groupId))) {
|
||||
return true;
|
||||
}
|
||||
if (instanceConnectEndpoints.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.anyMatch(endpoint -> nullToEmpty(endpoint.getSecurityGroupIds()).contains(groupId))) {
|
||||
return true;
|
||||
}
|
||||
return securityGroups.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(group -> !groupId.equals(group.getGroupId())
|
||||
&& Objects.equals(selected.getVpcId(), group.getVpcId()))
|
||||
.flatMap(group -> Stream.concat(
|
||||
nullToEmpty(group.getIpPermissions()).stream(), nullToEmpty(group.getIpPermissionsEgress()).stream()))
|
||||
.flatMap(permission -> nullToEmpty(permission.getUserIdGroupPairs()).stream())
|
||||
.anyMatch(pair -> groupId.equals(pair.getGroupId())
|
||||
&& (pair.getUserId() == null || Objects.equals(selected.getOwnerId(), pair.getUserId())));
|
||||
}
|
||||
|
||||
public List<SecurityGroupRule> authorizeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
|
||||
ensureDefaultResources(region);
|
||||
List<SecurityGroupRule> rules = new ArrayList<>();
|
||||
synchronized (lockFor(key(region, groupId))) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
requireKnownPrefixLists(region, permissions);
|
||||
List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());
|
||||
for (IpPermission perm : permissions) {
|
||||
resolveGroupReferences(region, sg.getVpcId(), perm);
|
||||
next.add(perm);
|
||||
rules.addAll(createRules(region, groupId, perm, false));
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
synchronized (lockFor(key(region, groupId))) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
requireKnownPrefixLists(region, permissions);
|
||||
List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());
|
||||
for (IpPermission perm : permissions) {
|
||||
resolveGroupReferences(region, sg.getVpcId(), perm);
|
||||
next.add(perm);
|
||||
rules.addAll(createRules(region, groupId, perm, false));
|
||||
}
|
||||
sg.setIpPermissions(next);
|
||||
securityGroups.put(key(region, groupId), sg);
|
||||
}
|
||||
sg.setIpPermissions(next);
|
||||
securityGroups.put(key(region, groupId), sg);
|
||||
}
|
||||
reconcilePublishedPortsForGroup(region, groupId);
|
||||
return rules;
|
||||
@@ -7908,17 +8061,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
public List<SecurityGroupRule> authorizeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
|
||||
ensureDefaultResources(region);
|
||||
List<SecurityGroupRule> rules = new ArrayList<>();
|
||||
synchronized (lockFor(key(region, groupId))) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
requireKnownPrefixLists(region, permissions);
|
||||
List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());
|
||||
for (IpPermission perm : permissions) {
|
||||
resolveGroupReferences(region, sg.getVpcId(), perm);
|
||||
next.add(perm);
|
||||
rules.addAll(createRules(region, groupId, perm, true));
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
synchronized (lockFor(key(region, groupId))) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
requireKnownPrefixLists(region, permissions);
|
||||
List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());
|
||||
for (IpPermission perm : permissions) {
|
||||
resolveGroupReferences(region, sg.getVpcId(), perm);
|
||||
next.add(perm);
|
||||
rules.addAll(createRules(region, groupId, perm, true));
|
||||
}
|
||||
sg.setIpPermissionsEgress(next);
|
||||
securityGroups.put(key(region, groupId), sg);
|
||||
}
|
||||
sg.setIpPermissionsEgress(next);
|
||||
securityGroups.put(key(region, groupId), sg);
|
||||
}
|
||||
reconcileFirewallPolicies(region);
|
||||
return rules;
|
||||
@@ -14729,10 +14884,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
private record VolumeDevice(String accountId, String region, String instanceId, String device) {}
|
||||
|
||||
private <T> T withVolumeLock(String volumeId, Supplier<T> action) {
|
||||
if (volumeId == null) {
|
||||
return withResourceLock(volumeLocks, volumeId, action);
|
||||
}
|
||||
|
||||
private <T> T withResourceLock(ConcurrentHashMap<String, RefCountedLock> locks, String resourceId, Supplier<T> action) {
|
||||
if (resourceId == null) {
|
||||
return action.get();
|
||||
}
|
||||
RefCountedLock refLock = volumeLocks.compute(volumeId, (k, v) -> {
|
||||
RefCountedLock refLock = locks.compute(resourceId, (k, v) -> {
|
||||
if (v == null) {
|
||||
return new RefCountedLock();
|
||||
}
|
||||
@@ -14744,7 +14903,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return action.get();
|
||||
} finally {
|
||||
refLock.lock.unlock();
|
||||
volumeLocks.computeIfPresent(volumeId, (k, v) -> {
|
||||
locks.computeIfPresent(resourceId, (k, v) -> {
|
||||
if (v.refCount.decrementAndGet() <= 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -15414,86 +15573,88 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
"The request must contain the parameter SubnetId", 400);
|
||||
}
|
||||
ensureDefaultResources(region);
|
||||
Subnet subnet = requireSubnet(region, subnetId);
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
Subnet subnet = requireSubnet(region, subnetId);
|
||||
|
||||
List<GroupIdentifier> sgIdentifiers = new ArrayList<>();
|
||||
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
|
||||
for (String sgId : securityGroupIds) {
|
||||
SecurityGroup sg = securityGroups.get(key(region, sgId)).orElseThrow(() ->
|
||||
new AwsException("InvalidSecurityGroupID.NotFound",
|
||||
"The securityGroup ID '" + sgId + "' does not exist", 400));
|
||||
if (!subnet.getVpcId().equals(sg.getVpcId())) {
|
||||
throw new AwsException("InvalidGroup.NotFound",
|
||||
"Security group " + sgId + " does not belong to the subnet VPC", 400);
|
||||
List<GroupIdentifier> sgIdentifiers = new ArrayList<>();
|
||||
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
|
||||
for (String sgId : securityGroupIds) {
|
||||
SecurityGroup sg = securityGroups.get(key(region, sgId)).orElseThrow(() ->
|
||||
new AwsException("InvalidSecurityGroupID.NotFound",
|
||||
"The securityGroup ID '" + sgId + "' does not exist", 400));
|
||||
if (!subnet.getVpcId().equals(sg.getVpcId())) {
|
||||
throw new AwsException("InvalidGroup.NotFound",
|
||||
"Security group " + sgId + " does not belong to the subnet VPC", 400);
|
||||
}
|
||||
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
|
||||
}
|
||||
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
|
||||
} else {
|
||||
defaultSecurityGroupOf(region, subnet.getVpcId()).ifPresent(defaultSg ->
|
||||
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName())));
|
||||
}
|
||||
} else {
|
||||
defaultSecurityGroupOf(region, subnet.getVpcId()).ifPresent(defaultSg ->
|
||||
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName())));
|
||||
}
|
||||
|
||||
// An explicit address is checked the way RunInstances checks its PrivateIpAddress: it must be
|
||||
// one the subnet can assign, in canonical form, and no other resource may hold it. Unlike a
|
||||
// launch it takes no lease on the VPC network (see requireRequestedPrivateIpFree).
|
||||
String requestedIp = (privateIpAddress != null && !privateIpAddress.isBlank())
|
||||
? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null;
|
||||
synchronized (privateIpAllocationLock) {
|
||||
String eniId = "eni-" + randomHex(17);
|
||||
if (requestedIp != null) {
|
||||
requireRequestedPrivateIpFree(region, subnetId, requestedIp);
|
||||
}
|
||||
// Secondaries are folded and checked before the primary is allocated, so a refused one
|
||||
// leaves no lease behind on the VPC network. Their range is not checked, as before.
|
||||
Set<String> secondaries = new LinkedHashSet<>();
|
||||
for (String extra : privateIpAddresses == null ? List.<String>of() : privateIpAddresses) {
|
||||
if (extra == null || extra.isBlank()) {
|
||||
continue;
|
||||
// An explicit address is checked the way RunInstances checks its PrivateIpAddress: it must be
|
||||
// one the subnet can assign, in canonical form, and no other resource may hold it. Unlike a
|
||||
// launch it takes no lease on the VPC network (see requireRequestedPrivateIpFree).
|
||||
String requestedIp = (privateIpAddress != null && !privateIpAddress.isBlank())
|
||||
? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null;
|
||||
synchronized (privateIpAllocationLock) {
|
||||
String eniId = "eni-" + randomHex(17);
|
||||
if (requestedIp != null) {
|
||||
requireRequestedPrivateIpFree(region, subnetId, requestedIp);
|
||||
}
|
||||
String ip = canonicalIpv4(extra).orElse(extra);
|
||||
if (!ip.equals(requestedIp) && secondaries.add(ip)) {
|
||||
requireRequestedPrivateIpFree(region, subnetId, ip);
|
||||
// Secondaries are folded and checked before the primary is allocated, so a refused one
|
||||
// leaves no lease behind on the VPC network. Their range is not checked, as before.
|
||||
Set<String> secondaries = new LinkedHashSet<>();
|
||||
for (String extra : privateIpAddresses == null ? List.<String>of() : privateIpAddresses) {
|
||||
if (extra == null || extra.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String ip = canonicalIpv4(extra).orElse(extra);
|
||||
if (!ip.equals(requestedIp) && secondaries.add(ip)) {
|
||||
requireRequestedPrivateIpFree(region, subnetId, ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
String primaryIp = requestedIp != null ? requestedIp : assignPrivateIp(region, subnetId);
|
||||
String primaryDns = AwsRegions.ec2PrivateIpDnsName(primaryIp, region);
|
||||
String primaryIp = requestedIp != null ? requestedIp : assignPrivateIp(region, subnetId);
|
||||
String primaryDns = AwsRegions.ec2PrivateIpDnsName(primaryIp, region);
|
||||
|
||||
NetworkInterface ni = new NetworkInterface();
|
||||
ni.setNetworkInterfaceId(eniId);
|
||||
ni.setSubnetId(subnetId);
|
||||
ni.setVpcId(subnet.getVpcId());
|
||||
ni.setAvailabilityZone(subnet.getAvailabilityZone());
|
||||
ni.setDescription(description);
|
||||
ni.setOwnerId(callerAccountId());
|
||||
ni.setStatus("available");
|
||||
ni.setMacAddress(randomMac());
|
||||
ni.setPrivateIpAddress(primaryIp);
|
||||
ni.setPrivateDnsName(primaryDns);
|
||||
ni.setGroups(sgIdentifiers);
|
||||
if (tagList != null) {
|
||||
ni.getTagSet().addAll(tagList);
|
||||
}
|
||||
|
||||
List<NetworkInterfacePrivateIpAddress> ipList = new ArrayList<>();
|
||||
NetworkInterfacePrivateIpAddress primary = new NetworkInterfacePrivateIpAddress();
|
||||
primary.setPrivateIpAddress(primaryIp);
|
||||
primary.setPrivateDnsName(primaryDns);
|
||||
primary.setPrimary(true);
|
||||
ipList.add(primary);
|
||||
for (String extra : secondaries) {
|
||||
if (extra.equals(primaryIp)) {
|
||||
continue;
|
||||
NetworkInterface ni = new NetworkInterface();
|
||||
ni.setNetworkInterfaceId(eniId);
|
||||
ni.setSubnetId(subnetId);
|
||||
ni.setVpcId(subnet.getVpcId());
|
||||
ni.setAvailabilityZone(subnet.getAvailabilityZone());
|
||||
ni.setDescription(description);
|
||||
ni.setOwnerId(callerAccountId());
|
||||
ni.setStatus("available");
|
||||
ni.setMacAddress(randomMac());
|
||||
ni.setPrivateIpAddress(primaryIp);
|
||||
ni.setPrivateDnsName(primaryDns);
|
||||
ni.setGroups(sgIdentifiers);
|
||||
if (tagList != null) {
|
||||
ni.getTagSet().addAll(tagList);
|
||||
}
|
||||
NetworkInterfacePrivateIpAddress secondary = new NetworkInterfacePrivateIpAddress();
|
||||
secondary.setPrivateIpAddress(extra);
|
||||
secondary.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(extra, region));
|
||||
secondary.setPrimary(false);
|
||||
ipList.add(secondary);
|
||||
}
|
||||
ni.setPrivateIpAddresses(ipList);
|
||||
|
||||
networkInterfaces.put(key(region, eniId), ni);
|
||||
return ni;
|
||||
List<NetworkInterfacePrivateIpAddress> ipList = new ArrayList<>();
|
||||
NetworkInterfacePrivateIpAddress primary = new NetworkInterfacePrivateIpAddress();
|
||||
primary.setPrivateIpAddress(primaryIp);
|
||||
primary.setPrivateDnsName(primaryDns);
|
||||
primary.setPrimary(true);
|
||||
ipList.add(primary);
|
||||
for (String extra : secondaries) {
|
||||
if (extra.equals(primaryIp)) {
|
||||
continue;
|
||||
}
|
||||
NetworkInterfacePrivateIpAddress secondary = new NetworkInterfacePrivateIpAddress();
|
||||
secondary.setPrivateIpAddress(extra);
|
||||
secondary.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(extra, region));
|
||||
secondary.setPrimary(false);
|
||||
ipList.add(secondary);
|
||||
}
|
||||
ni.setPrivateIpAddresses(ipList);
|
||||
|
||||
networkInterfaces.put(key(region, eniId), ni);
|
||||
return ni;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -83,6 +83,31 @@ class Ec2InstanceConnectEndpointServiceTest {
|
||||
.describeInstanceConnectEndpoints(REGION, List.of(id), Map.of())).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointGroupsRemainUntilTheEndpointIsDeleted() {
|
||||
Ec2Service service = mockModeService();
|
||||
String vpc = service.createVpc(REGION, "10.73.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(REGION, vpc, "10.73.1.0/24", "us-east-1a").getSubnetId();
|
||||
String group = service.createSecurityGroup(REGION, "endpoint-group", "owned endpoint group", vpc).getGroupId();
|
||||
String unrelated = service.createSecurityGroup(REGION, "unrelated-group", "unattached group", vpc).getGroupId();
|
||||
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnet, List.of(group),
|
||||
null, null, List.of(), null);
|
||||
String endpointId = endpoint.getInstanceConnectEndpointId();
|
||||
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(REGION, group)).getErrorCode());
|
||||
assertEquals(group, service.describeSecurityGroups(REGION, List.of(group), List.of(), Map.of())
|
||||
.getFirst().getGroupId());
|
||||
assertEquals(List.of(group), service.describeInstanceConnectEndpoints(REGION, List.of(endpointId), Map.of())
|
||||
.getFirst().getSecurityGroupIds());
|
||||
service.deleteSecurityGroup(REGION, unrelated);
|
||||
assertTrue(service.describeSecurityGroups(REGION, List.of(unrelated), List.of(), Map.of()).isEmpty());
|
||||
|
||||
service.deleteInstanceConnectEndpoint(REGION, endpointId);
|
||||
service.deleteSecurityGroup(REGION, group);
|
||||
assertTrue(service.describeSecurityGroups(REGION, List.of(group), List.of(), Map.of()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLiveEndpointBlocksDeletingItsSubnetAndVpc() {
|
||||
Ec2Service service = mockModeService();
|
||||
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
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.ec2.model.Filter;
|
||||
import software.amazon.awssdk.services.ec2.model.GroupIdentifier;
|
||||
import software.amazon.awssdk.services.ec2.model.Instance;
|
||||
import software.amazon.awssdk.services.ec2.model.InstanceNetworkInterfaceSpecification;
|
||||
import software.amazon.awssdk.services.ec2.model.NetworkInterface;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void replacementUpdatesStoredAndEmbeddedGroupsWithoutChangingInterfaceMetadata(boolean primaryAtLaunch) {
|
||||
Fixture fixture = fixture(primaryAtLaunch);
|
||||
NetworkInterface before = networkInterface(fixture);
|
||||
|
||||
replace(fixture, fixture.replacement());
|
||||
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(networkInterface(fixture).groups()));
|
||||
Instance instance = instance(fixture);
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(instance.securityGroups()));
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(instance.networkInterfaces().stream()
|
||||
.filter(eni -> fixture.eni().equals(eni.networkInterfaceId())).findFirst().orElseThrow().groups()));
|
||||
NetworkInterface after = networkInterface(fixture);
|
||||
assertEquals(before.toBuilder().groups(after.groups()).build(), after,
|
||||
"Only stored group membership should change");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void detachedInterfaceProtectsReplacementAfterInstanceReferenceIsRemoved(boolean primaryAtLaunch) {
|
||||
Fixture fixture = fixture(primaryAtLaunch);
|
||||
replace(fixture, fixture.replacement());
|
||||
fixture.client().detachNetworkInterface(request -> request.attachmentId(fixture.attachment()));
|
||||
// Leave no instance reference to the replacement: only the standalone ENI protects it.
|
||||
replace(fixture, fixture.original());
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client()
|
||||
.deleteSecurityGroup(request -> request.groupId(fixture.replacement())));
|
||||
|
||||
assertEquals("DependencyViolation", error.awsErrorDetails().errorCode());
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(networkInterface(fixture).groups()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void replacementReleasesThePreviousGroupForDeletion(boolean primaryAtLaunch) {
|
||||
Fixture fixture = fixture(primaryAtLaunch);
|
||||
replace(fixture, fixture.replacement());
|
||||
|
||||
fixture.client().deleteSecurityGroup(request -> request.groupId(fixture.original()));
|
||||
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(networkInterface(fixture).groups()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidReplacementLeavesBothRepresentationsUnchanged() {
|
||||
Fixture fixture = fixture(false);
|
||||
NetworkInterface before = networkInterface(fixture);
|
||||
List<GroupIdentifier> beforeGroups = instance(fixture).securityGroups();
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client()
|
||||
.modifyInstanceAttribute(request -> request.instanceId(fixture.instance())
|
||||
.groups(fixture.replacement(), "sg-00000000000000000")));
|
||||
|
||||
assertEquals("InvalidGroup.NotFound", error.awsErrorDetails().errorCode());
|
||||
assertEquals(before, networkInterface(fixture));
|
||||
assertEquals(beforeGroups, instance(fixture).securityGroups());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void foreignAccountOrRegionCannotModifyTheOwnerInterfaceGroups(boolean otherRegion) {
|
||||
Fixture fixture = fixture(false);
|
||||
NetworkInterface before = networkInterface(fixture);
|
||||
Ec2Client foreign = client(otherRegion ? "555566667780" : "555566667781",
|
||||
otherRegion ? Region.US_EAST_2 : Region.US_WEST_2);
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> foreign.modifyInstanceAttribute(
|
||||
request -> request.instanceId(fixture.instance()).groups(fixture.replacement())));
|
||||
|
||||
assertEquals("InvalidInstanceID.NotFound", error.awsErrorDetails().errorCode());
|
||||
assertEquals(before, networkInterface(fixture));
|
||||
}
|
||||
|
||||
private Fixture fixture(boolean primaryAtLaunch) {
|
||||
Ec2Client client = client("555566667780", Region.US_WEST_2);
|
||||
String vpc = client.createVpc(request -> request.cidrBlock("10.232.0.0/16")).vpc().vpcId();
|
||||
cleanup.register(() -> client.deleteVpc(request -> request.vpcId(vpc)));
|
||||
String original = group(client, vpc);
|
||||
String replacement = group(client, vpc);
|
||||
String subnet = client.createSubnet(request -> request.vpcId(vpc).cidrBlock("10.232.0.0/24"))
|
||||
.subnet().subnetId();
|
||||
cleanup.register(() -> client.deleteSubnet(request -> request.subnetId(subnet)));
|
||||
String eni = client.createNetworkInterface(request -> request.subnetId(subnet).groups(original)
|
||||
.description("owned instance group synchronization fixture"))
|
||||
.networkInterface().networkInterfaceId();
|
||||
cleanup.register(() -> client.deleteNetworkInterface(request -> request.networkInterfaceId(eni)));
|
||||
String token = UUID.randomUUID().toString();
|
||||
cleanup.register(() -> client.describeInstances(request -> request.filters(
|
||||
Filter.builder().name("client-token").values(token).build())).reservations().forEach(reservation ->
|
||||
reservation.instances().forEach(instance -> {
|
||||
client.terminateInstances(request -> request.instanceIds(instance.instanceId()));
|
||||
client.describeInstances(request -> request.instanceIds(instance.instanceId()));
|
||||
})));
|
||||
String instance = client.runInstances(request -> {
|
||||
request.imageId("ami-amazonlinux2023").instanceType("t2.micro").minCount(1).maxCount(1)
|
||||
.clientToken(token);
|
||||
if (primaryAtLaunch) {
|
||||
request.networkInterfaces(InstanceNetworkInterfaceSpecification.builder()
|
||||
.networkInterfaceId(eni).deviceIndex(0).deleteOnTermination(false).build());
|
||||
} else {
|
||||
request.subnetId(subnet).securityGroupIds(original);
|
||||
}
|
||||
}).instances().getFirst().instanceId();
|
||||
client.describeInstances(request -> request.instanceIds(instance));
|
||||
String attachment = primaryAtLaunch
|
||||
? client.describeNetworkInterfaces(request -> request.networkInterfaceIds(eni))
|
||||
.networkInterfaces().getFirst().attachment().attachmentId()
|
||||
: client.attachNetworkInterface(request -> request.networkInterfaceId(eni)
|
||||
.instanceId(instance).deviceIndex(1)).attachmentId();
|
||||
cleanup.register(() -> {
|
||||
NetworkInterface current = client.describeNetworkInterfaces(request -> request.networkInterfaceIds(eni))
|
||||
.networkInterfaces().getFirst();
|
||||
if (current.attachment() != null) {
|
||||
client.detachNetworkInterface(request -> request.attachmentId(current.attachment().attachmentId()));
|
||||
}
|
||||
});
|
||||
return new Fixture(client, instance, eni, attachment, original, replacement);
|
||||
}
|
||||
|
||||
private Ec2Client client(String account, Region region) {
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), account, region);
|
||||
cleanup.register(client::close);
|
||||
return client;
|
||||
}
|
||||
|
||||
private String group(Ec2Client client, String vpc) {
|
||||
String name = "instance-groups-" + UUID.randomUUID();
|
||||
cleanup.register(() -> client.describeSecurityGroups(request -> request.filters(
|
||||
Filter.builder().name("vpc-id").values(vpc).build(),
|
||||
Filter.builder().name("group-name").values(name).build())).securityGroups().forEach(group ->
|
||||
client.deleteSecurityGroup(request -> request.groupId(group.groupId()))));
|
||||
return client.createSecurityGroup(request -> request.vpcId(vpc).groupName(name)
|
||||
.description("owned instance group synchronization fixture")).groupId();
|
||||
}
|
||||
|
||||
private static void replace(Fixture fixture, String group) {
|
||||
fixture.client().modifyInstanceAttribute(request -> request.instanceId(fixture.instance()).groups(group));
|
||||
}
|
||||
|
||||
private static NetworkInterface networkInterface(Fixture fixture) {
|
||||
return fixture.client().describeNetworkInterfaces(request -> request.networkInterfaceIds(fixture.eni()))
|
||||
.networkInterfaces().getFirst();
|
||||
}
|
||||
|
||||
private static Instance instance(Fixture fixture) {
|
||||
return fixture.client().describeInstances(request -> request.instanceIds(fixture.instance()))
|
||||
.reservations().getFirst().instances().getFirst();
|
||||
}
|
||||
|
||||
private static List<String> groupIds(List<GroupIdentifier> groups) {
|
||||
return groups.stream().map(GroupIdentifier::groupId).toList();
|
||||
}
|
||||
|
||||
private record Fixture(Ec2Client client, String instance, String eni, String attachment,
|
||||
String original, String replacement) { }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
@@ -10,6 +11,7 @@ import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
@@ -17,6 +19,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -24,6 +27,7 @@ import java.util.UUID;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
@@ -49,6 +53,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class Ec2IntegrationTest {
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private static final String AUTH_HEADER =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
|
||||
|
||||
@@ -2936,7 +2943,10 @@ class Ec2IntegrationTest {
|
||||
given().header("Authorization", AUTH_HEADER.replace("/ec2/", "/iam/"))
|
||||
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", "sample-profile-v2")
|
||||
.post("/").then().statusCode(200);
|
||||
String launchedInstanceId = given()
|
||||
cleanup.register(() -> given().header("Authorization", AUTH_HEADER.replace("/ec2/", "/iam/"))
|
||||
.formParam("Action", "DeleteInstanceProfile").formParam("InstanceProfileName", "sample-profile-v2")
|
||||
.post("/").then().statusCode(200));
|
||||
ExtractableResponse<Response> launched = given()
|
||||
.formParam("Action", "RunInstances")
|
||||
.formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId)
|
||||
.formParam("LaunchTemplate.Version", "$Default")
|
||||
@@ -2954,6 +2964,26 @@ class Ec2IntegrationTest {
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract();
|
||||
String launchedInstanceId = launched.path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
cleanup.register(() -> {
|
||||
given()
|
||||
.formParam("Action", "TerminateInstances")
|
||||
.formParam("InstanceId.1", launchedInstanceId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> given()
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("InstanceId.1", launchedInstanceId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
|
||||
equalTo("terminated")));
|
||||
});
|
||||
launched.response().then()
|
||||
.body("RunInstancesResponse.instancesSet.item.imageId", equalTo("ami-sample-override"))
|
||||
.body("RunInstancesResponse.instancesSet.item.instanceType", equalTo("c7g.large"))
|
||||
.body("RunInstancesResponse.instancesSet.item.keyName", equalTo("test-key"))
|
||||
@@ -2965,8 +2995,7 @@ class Ec2IntegrationTest {
|
||||
.body("RunInstancesResponse.instancesSet.item.tagSet.item.findAll { it.key == 'example:NodeType' }.size()",
|
||||
equalTo(1))
|
||||
.body("RunInstancesResponse.instancesSet.item.tagSet.item.find { it.key == 'sample-name' }.value",
|
||||
equalTo("sample-local"))
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
equalTo("sample-local"));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeInstances")
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.ec2.model.InternetGateway;
|
||||
import io.floci.aws.services.ec2.model.IpPermission;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroup;
|
||||
import io.floci.aws.services.ec2.model.Subnet;
|
||||
import io.floci.aws.services.ec2.model.UserIdGroupPair;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class Ec2SecurityGroupDeletionIntegrationTest {
|
||||
private static final String REGION = "us-west-2";
|
||||
private static final String ACCOUNT = "555566667788";
|
||||
|
||||
@Inject
|
||||
Ec2Service service;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"yes", "1", "invalid", "", " "})
|
||||
void invalidDryRunCannotDeleteGroupOrRules(String dryRun) {
|
||||
RequestScopes.runAs(ACCOUNT, () -> {
|
||||
String vpc = service.createVpc(REGION, "10.232.0.0/24", false).getVpcId();
|
||||
cleanup.register(() -> RequestScopes.runAs(ACCOUNT, () -> service.deleteVpc(REGION, vpc)));
|
||||
SecurityGroup group = service.createSecurityGroup(
|
||||
REGION, "invalid-dry-run-" + UUID.randomUUID(), "owned test group", vpc);
|
||||
cleanup.register(() -> RequestScopes.runAs(ACCOUNT, () -> {
|
||||
if (!service.describeSecurityGroups(
|
||||
REGION, List.of(group.getGroupId()), List.of(), Map.of()).isEmpty()) {
|
||||
service.deleteSecurityGroup(REGION, group.getGroupId());
|
||||
}
|
||||
}));
|
||||
int rules = service.describeSecurityGroupRules(
|
||||
REGION, List.of(group.getGroupId()), List.of()).size();
|
||||
assertTrue(rules > 0);
|
||||
given().contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
|
||||
+ "/20261110/" + REGION + "/ec2/aws4_request, SignedHeaders=host, Signature=test")
|
||||
.formParam("Action", "DeleteSecurityGroup")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.formParam("GroupId", group.getGroupId()).formParam("DryRun", dryRun)
|
||||
.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
|
||||
assertEquals(group.getGroupId(), service.describeSecurityGroups(
|
||||
REGION, List.of(group.getGroupId()), List.of(), Map.of()).getFirst().getGroupId());
|
||||
assertEquals(rules, service.describeSecurityGroupRules(
|
||||
REGION, List.of(group.getGroupId()), List.of()).size());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultGroupCannotBeDeleted() {
|
||||
RequestScopes.runAs(ACCOUNT, () -> {
|
||||
String vpc = service.createDefaultVpc(REGION).getVpcId();
|
||||
String group = service.describeSecurityGroups(
|
||||
REGION, List.of(), List.of("default"),
|
||||
Map.of("vpc-id", List.of(vpc))).getFirst().getGroupId();
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.deleteSecurityGroup(REGION, group, null, false));
|
||||
assertEquals("CannotDelete", error.getErrorCode());
|
||||
assertEquals(group, service.describeSecurityGroups(
|
||||
REGION, List.of(group), List.of(), Map.of()).getFirst().getGroupId());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameWithoutDefaultVpcCannotSelectACustomVpcGroup() {
|
||||
RequestScopes.runAs(ACCOUNT, () -> {
|
||||
String defaultVpc = service.createDefaultVpc(REGION).getVpcId();
|
||||
for (Subnet subnet : service.describeSubnets(
|
||||
REGION, List.of(), Map.of("vpc-id", List.of(defaultVpc)))) {
|
||||
service.deleteSubnet(REGION, subnet.getSubnetId());
|
||||
}
|
||||
for (InternetGateway gateway : service.describeInternetGateways(
|
||||
REGION, List.of(), Map.of("attachment.vpc-id", List.of(defaultVpc)))) {
|
||||
service.detachInternetGateway(REGION, gateway.getInternetGatewayId(), defaultVpc);
|
||||
service.deleteInternetGateway(REGION, gateway.getInternetGatewayId());
|
||||
}
|
||||
service.deleteVpc(REGION, defaultVpc);
|
||||
cleanup.register(() -> RequestScopes.runAs(ACCOUNT, () -> service.createDefaultVpc(REGION)));
|
||||
String customVpc = service.createVpc(REGION, "10.229.0.0/24", false).getVpcId();
|
||||
cleanup.register(() -> RequestScopes.runAs(ACCOUNT, () -> service.deleteVpc(REGION, customVpc)));
|
||||
SecurityGroup group = service.createSecurityGroup(
|
||||
REGION, "without-default-" + UUID.randomUUID(), "owned test group", customVpc);
|
||||
cleanup.register(() -> RequestScopes.runAs(ACCOUNT,
|
||||
() -> service.deleteSecurityGroup(REGION, group.getGroupId())));
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.deleteSecurityGroup(REGION, null, group.getGroupName(), false));
|
||||
assertEquals("VPCIdNotSpecified", error.getErrorCode());
|
||||
assertEquals(group.getGroupId(), service.describeSecurityGroups(
|
||||
REGION, List.of(group.getGroupId()), List.of(), Map.of()).getFirst().getGroupId());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void selfReferenceAllowsDeletionAndOwnRulesAreRemoved() {
|
||||
RequestScopes.runAs(ACCOUNT, () -> {
|
||||
String vpc = service.createVpc(REGION, "10.230.0.0/24", false).getVpcId();
|
||||
cleanup.register(() -> RequestScopes.runAs(ACCOUNT, () -> service.deleteVpc(REGION, vpc)));
|
||||
SecurityGroup group = service.createSecurityGroup(
|
||||
REGION, "self-reference-" + UUID.randomUUID(), "owned test group", vpc);
|
||||
cleanup.register(() -> RequestScopes.runAs(ACCOUNT, () -> {
|
||||
if (!service.describeSecurityGroups(
|
||||
REGION, List.of(group.getGroupId()), List.of(), Map.of()).isEmpty()) {
|
||||
service.deleteSecurityGroup(REGION, group.getGroupId());
|
||||
}
|
||||
}));
|
||||
UserIdGroupPair pair = new UserIdGroupPair();
|
||||
pair.setGroupId(group.getGroupId());
|
||||
IpPermission permission = new IpPermission();
|
||||
permission.setIpProtocol("-1");
|
||||
permission.getUserIdGroupPairs().add(pair);
|
||||
service.authorizeSecurityGroupIngress(REGION, group.getGroupId(), List.of(permission));
|
||||
assertFalse(service.describeSecurityGroupRules(
|
||||
REGION, List.of(group.getGroupId()), List.of()).isEmpty());
|
||||
service.deleteSecurityGroup(REGION, group.getGroupId());
|
||||
assertTrue(service.describeSecurityGroupRules(
|
||||
REGION, List.of(group.getGroupId()), List.of()).isEmpty());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.services.ec2.model.Vpc;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class Ec2SecurityGroupFixtureCleanupTest {
|
||||
private static final String REGION = "us-west-2";
|
||||
|
||||
@Test
|
||||
void selfReferenceSetupFailureStillDeletesItsVpc() {
|
||||
Ec2SecurityGroupDeletionIntegrationTest fixture = fixture();
|
||||
IllegalStateException failure = new IllegalStateException("group creation failed");
|
||||
when(fixture.service.createVpc(REGION, "10.230.0.0/24", false)).thenReturn(vpc("vpc-owned"));
|
||||
when(fixture.service.createSecurityGroup(anyString(), anyString(), anyString(), anyString()))
|
||||
.thenThrow(failure);
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class, fixture::selfReferenceAllowsDeletionAndOwnRulesAreRemoved));
|
||||
fixture.cleanup.afterEach(mock(ExtensionContext.class));
|
||||
|
||||
verify(fixture.service).deleteVpc(REGION, "vpc-owned");
|
||||
verify(fixture.service, never()).deleteSecurityGroup(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingDefaultSetupFailureDeletesCustomVpcBeforeRestoringDefault() {
|
||||
Ec2SecurityGroupDeletionIntegrationTest fixture = fixture();
|
||||
IllegalStateException failure = new IllegalStateException("group creation failed");
|
||||
when(fixture.service.createDefaultVpc(REGION)).thenReturn(vpc("vpc-default"));
|
||||
when(fixture.service.createVpc(REGION, "10.229.0.0/24", false)).thenReturn(vpc("vpc-custom"));
|
||||
when(fixture.service.createSecurityGroup(anyString(), anyString(), anyString(), anyString()))
|
||||
.thenThrow(failure);
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class, fixture::nameWithoutDefaultVpcCannotSelectACustomVpcGroup));
|
||||
fixture.cleanup.afterEach(mock(ExtensionContext.class));
|
||||
|
||||
InOrder order = inOrder(fixture.service);
|
||||
order.verify(fixture.service).createDefaultVpc(REGION);
|
||||
order.verify(fixture.service).deleteVpc(REGION, "vpc-default");
|
||||
order.verify(fixture.service).deleteVpc(REGION, "vpc-custom");
|
||||
order.verify(fixture.service).createDefaultVpc(REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedFirstAllocationDoesNotDeleteUnownedResources() {
|
||||
Ec2SecurityGroupDeletionIntegrationTest fixture = fixture();
|
||||
IllegalStateException failure = new IllegalStateException("VPC creation failed");
|
||||
when(fixture.service.createVpc(anyString(), anyString(), anyBoolean())).thenThrow(failure);
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class, fixture::selfReferenceAllowsDeletionAndOwnRulesAreRemoved));
|
||||
fixture.cleanup.afterEach(mock(ExtensionContext.class));
|
||||
|
||||
verify(fixture.service, never()).deleteVpc(anyString(), anyString());
|
||||
verify(fixture.service, never()).deleteSecurityGroup(anyString(), anyString());
|
||||
}
|
||||
|
||||
private static Ec2SecurityGroupDeletionIntegrationTest fixture() {
|
||||
Ec2SecurityGroupDeletionIntegrationTest fixture = new Ec2SecurityGroupDeletionIntegrationTest();
|
||||
fixture.service = mock(Ec2Service.class);
|
||||
return fixture;
|
||||
}
|
||||
|
||||
private static Vpc vpc(String id) {
|
||||
Vpc vpc = new Vpc();
|
||||
vpc.setVpcId(id);
|
||||
return vpc;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,912 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.IpPermission;
|
||||
import io.floci.aws.services.ec2.model.NetworkInterface;
|
||||
import io.floci.aws.services.ec2.model.Reservation;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroup;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroupRule;
|
||||
import io.floci.aws.services.ec2.model.Tag;
|
||||
import io.floci.aws.services.ec2.model.UserIdGroupPair;
|
||||
import io.floci.aws.services.ec2.model.VpcEndpoint;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import io.floci.aws.testing.ParkingStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
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 java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.floci.aws.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class Ec2SecurityGroupPublicationRaceTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void rulePublicationProtectsReferencedGroupFromDeletion(boolean egress) throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String source = service.createSecurityGroup(region, "source", "source", vpc).getGroupId();
|
||||
String target = service.createSecurityGroup(region, "target", "target", vpc).getGroupId();
|
||||
IpPermission permission = groupPermission(target);
|
||||
factory.rules.parkNextWrite();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<List<SecurityGroupRule>> authorized = executor.submit(() -> egress
|
||||
? service.authorizeSecurityGroupEgress(region, source, List.of(permission))
|
||||
: service.authorizeSecurityGroupIngress(region, source, List.of(permission)));
|
||||
assertTrue(factory.rules.awaitParked(), "Authorization must reach rule publication");
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<AwsException> deleted = deleteGroup(executor, deletingThread, service, region, target);
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
factory.rules.release();
|
||||
List<SecurityGroupRule> published = authorized.get(5, TimeUnit.SECONDS);
|
||||
AwsException failure = deleted.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(failure, "Deletion must observe the published cross-group reference");
|
||||
assertEquals("DependencyViolation", failure.getErrorCode());
|
||||
assertEquals(target, published.getFirst().getReferencedGroupInfo().getGroupId());
|
||||
assertEquals(1, service.describeSecurityGroups(region, List.of(target), List.of(), Map.of()).size());
|
||||
} finally {
|
||||
factory.rules.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void unknownGroupReferenceKeepsExistingCompatibility(boolean egress) {
|
||||
Ec2Service service = service(new TestStores());
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String source = service.createSecurityGroup(region, "source", "source", vpc).getGroupId();
|
||||
List<SecurityGroupRule> rules = egress
|
||||
? service.authorizeSecurityGroupEgress(region, source, List.of(groupPermission("sg-unknown")))
|
||||
: service.authorizeSecurityGroupIngress(region, source, List.of(groupPermission("sg-unknown")));
|
||||
assertEquals("sg-unknown", rules.getFirst().getReferencedGroupInfo().getGroupId());
|
||||
assertTrue(service.describeSecurityGroupRules(region, List.of(source), List.of()).stream()
|
||||
.anyMatch(rule -> rules.getFirst().getSecurityGroupRuleId().equals(rule.getSecurityGroupRuleId())));
|
||||
}
|
||||
|
||||
private static IpPermission groupPermission(String target) {
|
||||
UserIdGroupPair pair = new UserIdGroupPair();
|
||||
pair.setGroupId(target);
|
||||
IpPermission permission = new IpPermission();
|
||||
permission.setIpProtocol("tcp");
|
||||
permission.setFromPort(443);
|
||||
permission.setToPort(443);
|
||||
permission.setUserIdGroupPairs(List.of(pair));
|
||||
return permission;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"group,false", "group,true", "rule,false", "rule,true"})
|
||||
void failedCreationRemovesOnlyItsOwnGroupAndDefaultRule(String failingStore, boolean afterWrite) {
|
||||
TestStores factory = new TestStores();
|
||||
InMemoryStorage<String, SecurityGroup> groups = spy(new InMemoryStorage<>());
|
||||
InMemoryStorage<String, SecurityGroupRule> rules = spy(new InMemoryStorage<>());
|
||||
factory.storage.withStore("ec2-security-groups.json", groups)
|
||||
.withStore("ec2-security-group-rules.json", rules);
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
SecurityGroup existing = service.createSecurityGroup(region, "existing", "existing", vpc);
|
||||
List<String> beforeGroups = service.describeSecurityGroups(region, List.of(), List.of(), Map.of())
|
||||
.stream().map(SecurityGroup::getGroupId).sorted().toList();
|
||||
List<String> beforeRules = service.describeSecurityGroupRules(region, List.of(), List.of())
|
||||
.stream().map(SecurityGroupRule::getSecurityGroupRuleId).sorted().toList();
|
||||
IllegalStateException failure = new IllegalStateException("injected publication failure");
|
||||
if ("group".equals(failingStore)) {
|
||||
doAnswer(call -> {
|
||||
if (afterWrite) {
|
||||
call.callRealMethod();
|
||||
}
|
||||
throw failure;
|
||||
}).when(groups).put(anyString(), any(SecurityGroup.class));
|
||||
} else {
|
||||
doAnswer(call -> {
|
||||
if (afterWrite) {
|
||||
call.callRealMethod();
|
||||
}
|
||||
throw failure;
|
||||
}).when(rules).put(anyString(), any(SecurityGroupRule.class));
|
||||
}
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.createSecurityGroup(region, "failed", "failed", vpc)));
|
||||
assertEquals(beforeGroups, service.describeSecurityGroups(region, List.of(), List.of(), Map.of())
|
||||
.stream().map(SecurityGroup::getGroupId).sorted().toList());
|
||||
assertEquals(beforeRules, service.describeSecurityGroupRules(region, List.of(), List.of())
|
||||
.stream().map(SecurityGroupRule::getSecurityGroupRuleId).sorted().toList());
|
||||
reset(groups, rules);
|
||||
SecurityGroup retry = service.createSecurityGroup(region, "failed", "retry", vpc);
|
||||
assertNotEquals(existing.getGroupId(), retry.getGroupId());
|
||||
assertEquals(1, service.describeSecurityGroupRules(region, List.of(retry.getGroupId()), List.of()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedCreationRetainsOriginalFailureAndAttemptsBothCleanupWrites() {
|
||||
TestStores factory = new TestStores();
|
||||
InMemoryStorage<String, SecurityGroup> groups = spy(new InMemoryStorage<>());
|
||||
InMemoryStorage<String, SecurityGroupRule> rules = spy(new InMemoryStorage<>());
|
||||
factory.storage.withStore("ec2-security-groups.json", groups)
|
||||
.withStore("ec2-security-group-rules.json", rules);
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
IllegalStateException failure = new IllegalStateException("rule publication failed");
|
||||
IllegalStateException ruleCleanup = new IllegalStateException("rule cleanup failed");
|
||||
IllegalStateException groupCleanup = new IllegalStateException("group cleanup failed");
|
||||
doThrow(failure).when(rules).put(anyString(), any(SecurityGroupRule.class));
|
||||
doThrow(ruleCleanup).when(rules).delete(anyString());
|
||||
doThrow(groupCleanup).when(groups).delete(anyString());
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.createSecurityGroup(region, "failed", "failed", vpc)));
|
||||
assertArrayEquals(new Throwable[]{ruleCleanup, groupCleanup}, failure.getSuppressed());
|
||||
verify(rules).delete(anyString());
|
||||
verify(groups).delete(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentSameNameCreationRejectsTheSecondPublication() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
factory.groups.parkNextWrite();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<SecurityGroup> first = executor.submit(() ->
|
||||
service.createSecurityGroup(region, "same-name", "first", vpc));
|
||||
assertTrue(factory.groups.awaitParked(), "Creator must reach group publication");
|
||||
AtomicReference<Thread> secondThread = new AtomicReference<>();
|
||||
Future<AwsException> second = executor.submit(() -> {
|
||||
secondThread.set(Thread.currentThread());
|
||||
try {
|
||||
service.createSecurityGroup(region, "same-name", "second", vpc);
|
||||
return null;
|
||||
} catch (AwsException failure) {
|
||||
return failure;
|
||||
}
|
||||
});
|
||||
awaitBlockedOrDone(secondThread, second);
|
||||
assertFalse(second.isDone(), "Second creation must wait for the first publication");
|
||||
factory.groups.release();
|
||||
SecurityGroup created = first.get(5, TimeUnit.SECONDS);
|
||||
AwsException duplicate = second.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(duplicate, "Only one group with the same name and VPC may be published");
|
||||
assertEquals("InvalidGroup.Duplicate", duplicate.getErrorCode());
|
||||
List<SecurityGroup> groups = service.describeSecurityGroups(region, List.of(),
|
||||
List.of("same-name"), Map.of());
|
||||
assertEquals(List.of(created.getGroupId()), groups.stream().map(SecurityGroup::getGroupId).toList());
|
||||
assertEquals(1, service.describeSecurityGroupRules(region, List.of(created.getGroupId()), List.of()).size());
|
||||
} finally {
|
||||
factory.groups.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNameInDifferentVpcsRemainsAllowed() {
|
||||
Ec2Service service = service(new TestStores());
|
||||
String region = "us-east-1";
|
||||
String firstVpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String secondVpc = service.createVpc(region, "10.1.0.0/16", false).getVpcId();
|
||||
SecurityGroup first = service.createSecurityGroup(region, "same-name", "first", firstVpc);
|
||||
SecurityGroup second = service.createSecurityGroup(region, "same-name", "second", secondVpc);
|
||||
assertNotEquals(first.getGroupId(), second.getGroupId());
|
||||
assertEquals(2, service.describeSecurityGroups(region, List.of(), List.of("same-name"), Map.of()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingPublishedGroupWaitsForItsDefaultRule() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
service.describeSecurityGroups(region, List.of(), List.of(), Map.of());
|
||||
factory.rules.parkNextWrite();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<SecurityGroup> created = executor.submit(() ->
|
||||
service.createSecurityGroup(region, "default-rule-race", "race", null));
|
||||
assertTrue(factory.rules.awaitParked(), "Creator must reach default-rule publication");
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<String> deleted = executor.submit(() -> {
|
||||
deletingThread.set(Thread.currentThread());
|
||||
return service.deleteSecurityGroup(region, null, "default-rule-race", false);
|
||||
});
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
assertFalse(deleted.isDone(), "Deletion must wait until the default rule is persisted");
|
||||
factory.rules.release();
|
||||
SecurityGroup group = created.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(group.getGroupId(), deleted.get(5, TimeUnit.SECONDS));
|
||||
assertTrue(service.describeSecurityGroups(region, List.of(group.getGroupId()),
|
||||
List.of(), Map.of()).isEmpty());
|
||||
assertTrue(service.describeSecurityGroupRules(region, List.of(group.getGroupId()), List.of()).isEmpty(),
|
||||
"A deleted group must not leave an orphaned default rule");
|
||||
} finally {
|
||||
factory.rules.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishedInterfaceCannotReferenceSuccessfullyDeletedGroup() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "race", "race", vpc).getGroupId();
|
||||
factory.interfaces.parkNextWrite();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<NetworkInterface> created = executor.submit(() -> service.createNetworkInterface(
|
||||
region, subnet, "race", null, List.of(), List.of(group), List.of()));
|
||||
assertTrue(factory.interfaces.awaitParked(), "Creator must reach the ENI publication boundary");
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<AwsException> deleted = deleteGroup(executor, deletingThread, service, region, group);
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
factory.interfaces.release();
|
||||
NetworkInterface networkInterface = created.get(5, TimeUnit.SECONDS);
|
||||
AwsException error = deleted.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(error, "Deletion must observe the creator's published group reference");
|
||||
assertEquals("DependencyViolation", error.getErrorCode());
|
||||
assertTrue(networkInterface.getGroups().stream().anyMatch(value -> group.equals(value.getGroupId())));
|
||||
assertEquals(1, service.describeSecurityGroups(region, List.of(group), List.of(), Map.of()).size());
|
||||
} finally {
|
||||
factory.interfaces.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingInterfacePreventsDeletion() {
|
||||
Ec2Service service = service(new TestStores());
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "positive", "positive", vpc).getGroupId();
|
||||
service.createNetworkInterface(region, subnet, "positive", null, List.of(), List.of(group), List.of());
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.deleteSecurityGroup(region, group));
|
||||
assertEquals("DependencyViolation", error.getErrorCode());
|
||||
assertEquals(1, service.describeSecurityGroups(region, List.of(group), List.of(), Map.of()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void creationAfterDeletionRejectsMissingGroup() {
|
||||
Ec2Service service = service(new TestStores());
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "deleted", "deleted", vpc).getGroupId();
|
||||
service.deleteSecurityGroup(region, group);
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.createNetworkInterface(
|
||||
region, subnet, "rejected", null, List.of(), List.of(group), List.of()));
|
||||
assertEquals("InvalidSecurityGroupID.NotFound", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishedInstanceCannotReferenceSuccessfullyDeletedGroup() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "launch", "launch", vpc).getGroupId();
|
||||
factory.instances.parkNextWrite();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<Reservation> created = executor.submit(() -> service.runInstances(region, "ami-test", "t3.micro",
|
||||
1, 1, null, List.of(group), subnet, null, List.of(), null, null));
|
||||
assertTrue(factory.instances.awaitParked(), "Launch must reach instance publication");
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<AwsException> deleted = deleteGroup(executor, deletingThread, service, region, group);
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
factory.instances.release();
|
||||
Reservation reservation = created.get(5, TimeUnit.SECONDS);
|
||||
AwsException error = deleted.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(error, "Deletion must observe the published instance reference");
|
||||
assertEquals("DependencyViolation", error.getErrorCode());
|
||||
assertEquals(group, reservation.getInstances().getFirst().getSecurityGroups().getFirst().getGroupId());
|
||||
assertEquals(1, service.describeSecurityGroups(region, List.of(group), List.of(), Map.of()).size());
|
||||
} finally {
|
||||
factory.instances.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchRechecksGroupDeletedAfterInitialResolutionBeforeAllocating() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "deleted-launch", "launch", vpc).getGroupId();
|
||||
int available = service.describeSubnets(region, List.of(subnet), Map.of()).getFirst().getAvailableIpAddressCount();
|
||||
factory.groups.parkNextRead();
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<AwsException> created = executor.submit(() -> {
|
||||
try {
|
||||
service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(group), subnet, null, List.of(), null, null);
|
||||
return null;
|
||||
} catch (AwsException error) {
|
||||
return error;
|
||||
}
|
||||
});
|
||||
assertTrue(factory.groups.awaitParked(), "Launch must capture its original security group");
|
||||
service.deleteSecurityGroup(region, group);
|
||||
factory.groups.release();
|
||||
AwsException error = created.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(error, "Launch must reject the now-deleted captured group");
|
||||
assertEquals("InvalidGroup.NotFound", error.getErrorCode());
|
||||
assertTrue(service.describeInstances(region, List.of(), Map.of()).isEmpty());
|
||||
assertTrue(service.describeVolumes(region, List.of(), Map.of()).isEmpty());
|
||||
assertEquals(available,
|
||||
service.describeSubnets(region, List.of(subnet), Map.of()).getFirst().getAvailableIpAddressCount());
|
||||
} finally {
|
||||
factory.groups.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchRejectsSubnetDeletedAfterResolutionBeforeAllocating() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "deleted-subnet", "launch", vpc).getGroupId();
|
||||
factory.groups.parkNextRead();
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<AwsException> created = executor.submit(() -> {
|
||||
try {
|
||||
service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(group), subnet, null, List.of(), null, null);
|
||||
return null;
|
||||
} catch (AwsException error) {
|
||||
return error;
|
||||
}
|
||||
});
|
||||
assertTrue(factory.groups.awaitParked(), "Launch must resolve its subnet before reading the group");
|
||||
service.deleteSubnet(region, subnet);
|
||||
factory.groups.release();
|
||||
AwsException error = created.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(error, "Launch must reject the subnet deleted after its initial resolution");
|
||||
assertEquals("InvalidSubnetID.NotFound", error.getErrorCode());
|
||||
assertTrue(service.describeInstances(region, List.of(), Map.of()).isEmpty());
|
||||
assertTrue(service.describeVolumes(region, List.of(), Map.of()).isEmpty());
|
||||
assertTrue(service.describeNetworkInterfaces(region, List.of(), Map.of()).networkInterfaces().isEmpty());
|
||||
assertTrue(service.describeSubnets(region, List.of(subnet), Map.of()).isEmpty());
|
||||
} finally {
|
||||
factory.groups.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void subnetDeletionWaitsForLaunchPublicationAndRetainsResidentSubnet() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "resident-subnet", "launch", vpc).getGroupId();
|
||||
factory.instances.parkNextWrite();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<Reservation> created = executor.submit(() -> service.runInstances(region, "ami-test", "t3.micro",
|
||||
1, 1, null, List.of(group), subnet, null, List.of(), null, null));
|
||||
assertTrue(factory.instances.awaitParked(), "Launch must reach instance publication");
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<AwsException> deleted = executor.submit(() -> {
|
||||
deletingThread.set(Thread.currentThread());
|
||||
return assertThrows(AwsException.class, () -> service.deleteSubnet(region, subnet));
|
||||
});
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
assertFalse(deleted.isDone(), "Deletion must wait for launch publication");
|
||||
factory.instances.release();
|
||||
Reservation reservation = created.get(5, TimeUnit.SECONDS);
|
||||
AwsException failure = deleted.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(failure, "Stored endpoint membership must prevent group deletion");
|
||||
assertEquals("DependencyViolation", failure.getErrorCode());
|
||||
assertEquals(subnet, reservation.getInstances().getFirst().getSubnetId());
|
||||
assertEquals(1, service.describeSubnets(region, List.of(subnet), Map.of()).size());
|
||||
} finally {
|
||||
factory.instances.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingInstancePreventsDeletionUntilTerminated() {
|
||||
Ec2Service service = service(new TestStores());
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "existing-launch", "launch", vpc).getGroupId();
|
||||
String id = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(group), subnet, null, List.of(), null, null).getInstances().getFirst().getInstanceId();
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, group)).getErrorCode());
|
||||
service.terminateInstances(region, List.of(id));
|
||||
service.deleteSecurityGroup(region, group);
|
||||
assertTrue(service.describeSecurityGroups(region, List.of(), List.of(), Map.of()).stream()
|
||||
.noneMatch(value -> group.equals(value.getGroupId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyRejectsGroupDeletedAfterCapturedRead() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String original = service.createSecurityGroup(region, "original-modify", "original", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "replacement-modify", "replacement", vpc).getGroupId();
|
||||
String instance = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(original), subnet, null, List.of(), null, null).getInstances().getFirst().getInstanceId();
|
||||
factory.groups.parkNextRead();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<AwsException> modified = executor.submit(() -> {
|
||||
try {
|
||||
service.modifyInstanceGroups(region, instance, List.of(replacement));
|
||||
return null;
|
||||
} catch (AwsException error) {
|
||||
return error;
|
||||
}
|
||||
});
|
||||
assertTrue(factory.groups.awaitParked(), "Modifier must capture the replacement group before deletion");
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<AwsException> deleted = deleteGroup(executor, deletingThread, service, region, replacement);
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
factory.groups.release();
|
||||
AwsException modifyError = modified.get(5, TimeUnit.SECONDS);
|
||||
AwsException deleteError = deleted.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(modifyError != null || deleteError != null,
|
||||
"Deletion and a new assignment cannot both succeed for the captured group");
|
||||
if (deleteError == null) {
|
||||
assertEquals("InvalidGroup.NotFound", modifyError.getErrorCode());
|
||||
assertEquals(original, service.describeInstances(region, List.of(instance), Map.of()).getFirst()
|
||||
.getInstances().getFirst().getSecurityGroups().getFirst().getGroupId());
|
||||
} else {
|
||||
assertEquals("DependencyViolation", deleteError.getErrorCode());
|
||||
assertNull(modifyError);
|
||||
assertEquals(replacement, service.describeInstances(region, List.of(instance), Map.of()).getFirst()
|
||||
.getInstances().getFirst().getSecurityGroups().getFirst().getGroupId());
|
||||
}
|
||||
} finally {
|
||||
factory.groups.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyExistingGroupMovesDependencyToReplacement() {
|
||||
Ec2Service service = service(new TestStores());
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String original = service.createSecurityGroup(region, "original-positive", "original", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "replacement-positive", "replacement", vpc).getGroupId();
|
||||
String instance = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(original), subnet, null, List.of(), null, null).getInstances().getFirst().getInstanceId();
|
||||
service.modifyInstanceGroups(region, instance, List.of(replacement));
|
||||
service.deleteSecurityGroup(region, original);
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, replacement)).getErrorCode());
|
||||
assertEquals(replacement, service.describeInstances(region, List.of(instance), Map.of()).getFirst()
|
||||
.getInstances().getFirst().getSecurityGroups().getFirst().getGroupId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyMissingGroupPreservesOriginalDependency() {
|
||||
Ec2Service service = service(new TestStores());
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String original = service.createSecurityGroup(region, "original-missing", "original", vpc).getGroupId();
|
||||
String instance = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(original), subnet, null, List.of(), null, null).getInstances().getFirst().getInstanceId();
|
||||
assertEquals("InvalidGroup.NotFound", assertThrows(AwsException.class,
|
||||
() -> service.modifyInstanceGroups(region, instance, List.of("sg-missing"))).getErrorCode());
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, original)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulSameInstanceUpdatesPublishInFirewallOrder() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
EmulatorConfig config = mockConfig();
|
||||
Ec2ContainerManager manager = mock(Ec2ContainerManager.class);
|
||||
Ec2Service service = new Ec2Service(config, manager, mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), factory.storage);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String original = service.createSecurityGroup(region, "ordered-original", "original", vpc).getGroupId();
|
||||
String firstGroup = service.createSecurityGroup(region, "ordered-first", "first", vpc).getGroupId();
|
||||
String secondGroup = service.createSecurityGroup(region, "ordered-second", "second", vpc).getGroupId();
|
||||
Instance instance = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(original), subnet, null, List.of(), null, null).getInstances().getFirst();
|
||||
instance.setState(InstanceState.running());
|
||||
EmulatorConfig.NetworkConfig network = mock(EmulatorConfig.NetworkConfig.class);
|
||||
EmulatorConfig.SecurityGroupEnforcementConfig enforcement = mock(EmulatorConfig.SecurityGroupEnforcementConfig.class);
|
||||
when(config.network()).thenReturn(network);
|
||||
when(network.securityGroupEnforcement()).thenReturn(enforcement);
|
||||
when(enforcement.enabled()).thenReturn(true);
|
||||
when(config.services().ec2().mock()).thenReturn(false);
|
||||
CountDownLatch applied = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<Set<String>> firewall = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
Set<String> groups = invocation.getArgument(1);
|
||||
firewall.set(Set.copyOf(groups));
|
||||
if (groups.contains(firstGroup)) {
|
||||
applied.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
return null;
|
||||
}).when(manager).updateSecurityGroups(anyString(), anySet(), anyMap(), anyMap());
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> first = executor.submit(() ->
|
||||
service.modifyInstanceGroups(region, instance.getInstanceId(), List.of(firstGroup)));
|
||||
assertTrue(applied.await(5, TimeUnit.SECONDS), "First firewall update must precede its publication");
|
||||
AtomicReference<Thread> secondThread = new AtomicReference<>();
|
||||
Future<?> second = executor.submit(() -> {
|
||||
secondThread.set(Thread.currentThread());
|
||||
service.modifyInstanceGroups(region, instance.getInstanceId(), List.of(secondGroup));
|
||||
});
|
||||
awaitBlockedOrDone(secondThread, second);
|
||||
boolean secondOvertook = second.isDone();
|
||||
release.countDown();
|
||||
first.get(5, TimeUnit.SECONDS);
|
||||
second.get(5, TimeUnit.SECONDS);
|
||||
Instance stored = service.describeInstances(region, List.of(instance.getInstanceId()), Map.of())
|
||||
.getFirst().getInstances().getFirst();
|
||||
assertAll(
|
||||
() -> assertFalse(secondOvertook, "Same-instance update must wait through firewall publication"),
|
||||
() -> assertEquals(Set.of(secondGroup), firewall.get()),
|
||||
() -> assertEquals(secondGroup, stored.getSecurityGroups().getFirst().getGroupId()),
|
||||
() -> assertEquals(secondGroup, stored.getNetworkInterfaces().getFirst().getGroups().getFirst().getGroupId()),
|
||||
() -> assertEquals(secondGroup, service.describeNetworkInterfaces(region,
|
||||
List.of(stored.getNetworkInterfaces().getFirst().getNetworkInterfaceId()), Map.of())
|
||||
.networkInterfaces().getFirst().getGroups().getFirst().getGroupId()));
|
||||
service.deleteSecurityGroup(region, firstGroup);
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, secondGroup)).getErrorCode());
|
||||
} finally {
|
||||
release.countDown();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingFirewallAssignmentBlocksOnlyItsGroupAndReleasesOnFailure() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
EmulatorConfig config = mockConfig();
|
||||
Ec2ContainerManager manager = mock(Ec2ContainerManager.class);
|
||||
Ec2Service service = new Ec2Service(config, manager, mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), factory.storage);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String original = service.createSecurityGroup(region, "firewall-original", "original", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "firewall-replacement", "replacement", vpc).getGroupId();
|
||||
String unrelated = service.createSecurityGroup(region, "firewall-unrelated", "unrelated", vpc).getGroupId();
|
||||
Instance instance = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(original), subnet, null, List.of(), null, null).getInstances().getFirst();
|
||||
instance.setState(InstanceState.running());
|
||||
EmulatorConfig.NetworkConfig network = mock(EmulatorConfig.NetworkConfig.class);
|
||||
EmulatorConfig.SecurityGroupEnforcementConfig enforcement = mock(EmulatorConfig.SecurityGroupEnforcementConfig.class);
|
||||
when(config.network()).thenReturn(network);
|
||||
when(network.securityGroupEnforcement()).thenReturn(enforcement);
|
||||
when(enforcement.enabled()).thenReturn(true);
|
||||
when(config.services().ec2().mock()).thenReturn(false);
|
||||
CountDownLatch updating = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
IllegalStateException failure = new IllegalStateException("Owned firewall failure");
|
||||
doAnswer(invocation -> {
|
||||
updating.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
throw failure;
|
||||
}).when(manager).updateSecurityGroups(anyString(), anySet(), anyMap(), anyMap());
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<Throwable> modified = executor.submit(() -> assertThrows(IllegalStateException.class,
|
||||
() -> service.modifyInstanceGroups(region, instance.getInstanceId(), List.of(replacement))));
|
||||
assertTrue(updating.await(5, TimeUnit.SECONDS), "Must reach actual firewall update call");
|
||||
Future<?> independent = executor.submit(() -> service.deleteSecurityGroup(region, unrelated));
|
||||
independent.get(5, TimeUnit.SECONDS);
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, replacement)).getErrorCode());
|
||||
release.countDown();
|
||||
assertSame(failure, modified.get(5, TimeUnit.SECONDS));
|
||||
service.deleteSecurityGroup(region, replacement);
|
||||
assertEquals(original, service.describeInstances(region, List.of(instance.getInstanceId()), Map.of()).getFirst()
|
||||
.getInstances().getFirst().getSecurityGroups().getFirst().getGroupId());
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, original)).getErrorCode());
|
||||
} finally {
|
||||
release.countDown();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentFailedAssignmentsReleaseOnlyTheirOwnPendingReference() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
EmulatorConfig config = mockConfig();
|
||||
Ec2ContainerManager manager = mock(Ec2ContainerManager.class);
|
||||
Ec2Service service = new Ec2Service(config, manager, mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), factory.storage);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String original = service.createSecurityGroup(region, "parallel-original", "original", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "parallel-replacement", "replacement", vpc).getGroupId();
|
||||
List<Instance> instances = service.runInstances(region, "ami-test", "t3.micro", 2, 2, null,
|
||||
List.of(original), subnet, null, List.of(), null, null).getInstances();
|
||||
instances.forEach(instance -> instance.setState(InstanceState.running()));
|
||||
EmulatorConfig.NetworkConfig network = mock(EmulatorConfig.NetworkConfig.class);
|
||||
EmulatorConfig.SecurityGroupEnforcementConfig enforcement = mock(EmulatorConfig.SecurityGroupEnforcementConfig.class);
|
||||
when(config.network()).thenReturn(network);
|
||||
when(network.securityGroupEnforcement()).thenReturn(enforcement);
|
||||
when(enforcement.enabled()).thenReturn(true);
|
||||
when(config.services().ec2().mock()).thenReturn(false);
|
||||
CountDownLatch firstEntered = new CountDownLatch(1);
|
||||
CountDownLatch secondEntered = new CountDownLatch(1);
|
||||
CountDownLatch firstRelease = new CountDownLatch(1);
|
||||
CountDownLatch secondRelease = new CountDownLatch(1);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
doAnswer(invocation -> {
|
||||
boolean first = calls.incrementAndGet() == 1;
|
||||
(first ? firstEntered : secondEntered).countDown();
|
||||
assertTrue((first ? firstRelease : secondRelease).await(5, TimeUnit.SECONDS));
|
||||
throw new IllegalStateException("Owned parallel firewall failure");
|
||||
}).when(manager).updateSecurityGroups(anyString(), anySet(), anyMap(), anyMap());
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> first = executor.submit(() -> assertThrows(IllegalStateException.class,
|
||||
() -> service.modifyInstanceGroups(region, instances.getFirst().getInstanceId(), List.of(replacement))));
|
||||
assertTrue(firstEntered.await(5, TimeUnit.SECONDS));
|
||||
Future<?> second = executor.submit(() -> assertThrows(IllegalStateException.class,
|
||||
() -> service.modifyInstanceGroups(region, instances.getLast().getInstanceId(), List.of(replacement))));
|
||||
assertTrue(secondEntered.await(5, TimeUnit.SECONDS));
|
||||
firstRelease.countDown();
|
||||
first.get(5, TimeUnit.SECONDS);
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, replacement)).getErrorCode());
|
||||
secondRelease.countDown();
|
||||
second.get(5, TimeUnit.SECONDS);
|
||||
service.deleteSecurityGroup(region, replacement);
|
||||
assertEquals(2, calls.get());
|
||||
} finally {
|
||||
firstRelease.countDown();
|
||||
secondRelease.countDown();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointCreationRechecksAGroupDeletedAfterItsFirstRead() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String group = service.createSecurityGroup(region, "endpoint-race", "endpoint", vpc).getGroupId();
|
||||
factory.groups.parkNextRead();
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<AwsException> created = executor.submit(() -> {
|
||||
try {
|
||||
service.createVpcEndpoint(region, vpc, "test-service", "Interface",
|
||||
List.of(), List.of(), List.of(group), false, null,
|
||||
List.of(new Tag("EndpointRace", "rejected")));
|
||||
return null;
|
||||
} catch (AwsException failure) {
|
||||
return failure;
|
||||
}
|
||||
});
|
||||
assertTrue(factory.groups.awaitParked());
|
||||
service.deleteSecurityGroup(region, group);
|
||||
factory.groups.release();
|
||||
AwsException failure = created.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(failure, "Creation must reject the deleted group");
|
||||
assertEquals("InvalidGroup.NotFound", failure.getErrorCode());
|
||||
assertTrue(service.describeVpcEndpoints(region, List.of(), Map.of()).isEmpty());
|
||||
assertTrue(service.describeTags(region, Map.of("key", List.of("EndpointRace"))).isEmpty());
|
||||
} finally {
|
||||
factory.groups.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointPublicationProtectsItsGroupUntilEndpointDeletion() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String group = service.createSecurityGroup(region, "endpoint-reference", "endpoint", vpc).getGroupId();
|
||||
factory.endpoints.parkNextWrite();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<VpcEndpoint> created = executor.submit(() -> createEndpoint(service, region, vpc, group));
|
||||
assertTrue(factory.endpoints.awaitParked());
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<AwsException> deleted = deleteGroup(executor, deletingThread, service, region, group);
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
assertFalse(deleted.isDone());
|
||||
factory.endpoints.release();
|
||||
VpcEndpoint endpoint = created.get(5, TimeUnit.SECONDS);
|
||||
AwsException failure = deleted.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(failure, "Stored endpoint membership must prevent group deletion");
|
||||
assertEquals("DependencyViolation", failure.getErrorCode());
|
||||
service.deleteVpcEndpoints(region, List.of(endpoint.getVpcEndpointId()));
|
||||
service.deleteSecurityGroup(region, group);
|
||||
} finally {
|
||||
factory.endpoints.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointGroupModificationProtectsValidatedReferenceFromDeletion() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String original = service.createSecurityGroup(region, "endpoint-original", "endpoint", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "endpoint-replacement", "endpoint", vpc).getGroupId();
|
||||
VpcEndpoint endpoint = createEndpoint(service, region, vpc, original);
|
||||
factory.groups.parkNextRead();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<VpcEndpoint> modified = executor.submit(() -> service.modifyVpcEndpoint(region,
|
||||
endpoint.getVpcEndpointId(), List.of(), List.of(), List.of(), List.of(),
|
||||
List.of(replacement), List.of(original), null, null, null));
|
||||
assertTrue(factory.groups.awaitParked());
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<AwsException> deleted = deleteGroup(executor, deletingThread, service, region, replacement);
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
assertFalse(deleted.isDone());
|
||||
factory.groups.release();
|
||||
assertEquals(List.of(replacement), modified.get(5, TimeUnit.SECONDS).getSecurityGroupIds());
|
||||
AwsException failure = deleted.get(5, TimeUnit.SECONDS);
|
||||
assertNotNull(failure, "Stored endpoint membership must prevent group deletion");
|
||||
assertEquals("DependencyViolation", failure.getErrorCode());
|
||||
service.deleteSecurityGroup(region, original);
|
||||
service.deleteVpcEndpoints(region, List.of(endpoint.getVpcEndpointId()));
|
||||
service.deleteSecurityGroup(region, replacement);
|
||||
} finally {
|
||||
factory.groups.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointDeletionWaitsForModificationWithoutResurrection() throws Exception {
|
||||
TestStores factory = new TestStores();
|
||||
Ec2Service service = service(factory);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String group = service.createSecurityGroup(region, "endpoint-delete", "endpoint", vpc).getGroupId();
|
||||
VpcEndpoint endpoint = createEndpoint(service, region, vpc, group);
|
||||
factory.endpoints.parkNextRead();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<VpcEndpoint> modified = executor.submit(() -> service.modifyVpcEndpoint(region,
|
||||
endpoint.getVpcEndpointId(), List.of(), List.of(), List.of(), List.of(),
|
||||
List.of(), List.of(), "replacement-policy", null, null));
|
||||
assertTrue(factory.endpoints.awaitParked());
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Future<List<VpcEndpoint>> deleted = executor.submit(() -> {
|
||||
deletingThread.set(Thread.currentThread());
|
||||
return service.deleteVpcEndpoints(region, List.of(endpoint.getVpcEndpointId()));
|
||||
});
|
||||
awaitBlockedOrDone(deletingThread, deleted);
|
||||
assertFalse(deleted.isDone());
|
||||
factory.endpoints.release();
|
||||
modified.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, deleted.get(5, TimeUnit.SECONDS).size());
|
||||
assertTrue(service.describeVpcEndpoints(region, List.of(), Map.of()).isEmpty());
|
||||
service.deleteSecurityGroup(region, group);
|
||||
assertEquals("InvalidVpcEndpointId.NotFound", assertThrows(AwsException.class,
|
||||
() -> service.modifyVpcEndpoint(region, endpoint.getVpcEndpointId(), List.of(), List.of(),
|
||||
List.of(), List.of(), List.of(group), List.of(), null, null, null)).getErrorCode());
|
||||
} finally {
|
||||
factory.endpoints.release();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
private static Future<AwsException> deleteGroup(ExecutorService executor, AtomicReference<Thread> deletingThread,
|
||||
Ec2Service service, String region, String group) {
|
||||
return executor.submit(() -> {
|
||||
deletingThread.set(Thread.currentThread());
|
||||
try {
|
||||
service.deleteSecurityGroup(region, group);
|
||||
return null;
|
||||
} catch (AwsException failure) {
|
||||
return failure;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static VpcEndpoint createEndpoint(Ec2Service service, String region, String vpc, String group) {
|
||||
return service.createVpcEndpoint(region, vpc, "test-service", "Interface", List.of(), List.of(),
|
||||
List.of(group), false, null, List.of());
|
||||
}
|
||||
|
||||
private static Ec2Service service(TestStores factory) {
|
||||
return new Ec2Service(mockConfig(), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), factory.storage);
|
||||
}
|
||||
|
||||
private static EmulatorConfig mockConfig() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.ec2()).thenReturn(ec2);
|
||||
when(ec2.mock()).thenReturn(true);
|
||||
when(ec2.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
|
||||
return config;
|
||||
}
|
||||
|
||||
private static final class TestStores {
|
||||
private final ParkingStore<VpcEndpoint> endpoints = new ParkingStore<>();
|
||||
private final ParkingStore<NetworkInterface> interfaces = new ParkingStore<>();
|
||||
private final ParkingStore<Instance> instances = new ParkingStore<>();
|
||||
private final ParkingStore<SecurityGroupRule> rules = new ParkingStore<>();
|
||||
private final ParkingStore<SecurityGroup> groups = new ParkingStore<>();
|
||||
private final InMemoryStorageFactory storage = new InMemoryStorageFactory("000000000000")
|
||||
.withStore("ec2-vpc-endpoints.json", endpoints)
|
||||
.withStore("ec2-network-interfaces.json", interfaces)
|
||||
.withStore("ec2-instances.json", instances)
|
||||
.withStore("ec2-security-groups.json", groups)
|
||||
.withStore("ec2-security-group-rules.json", rules);
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
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.ec2.model.Filter;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class Ec2SecurityGroupTagDeletionIntegrationTest {
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void deletionRemovesGroupAndRuleTagsButPreservesOtherResources(boolean checkRuleFirst) {
|
||||
Ec2Client client = client();
|
||||
String vpc = vpc(client);
|
||||
String group = group(client, vpc);
|
||||
String retainedGroup = group(client, vpc);
|
||||
String rule = rule(client, group);
|
||||
String retainedRule = rule(client, retainedGroup);
|
||||
tag(client, List.of(group, rule, retainedGroup, retainedRule, vpc));
|
||||
assertEquals(2, tagCount(client, List.of(group, rule)));
|
||||
|
||||
client.deleteSecurityGroup(request -> request.groupId(group));
|
||||
|
||||
String first = checkRuleFirst ? rule : group;
|
||||
String second = checkRuleFirst ? group : rule;
|
||||
assertEquals(0, tagCount(client, List.of(first)), "Deleted resource tags must be removed: " + first);
|
||||
assertEquals(0, tagCount(client, List.of(second)), "Deleted resource tags must be removed: " + second);
|
||||
assertEquals(3, tagCount(client, List.of(retainedGroup, retainedRule, vpc)));
|
||||
assertTrue(client.describeSecurityGroupRules(request -> request.filters(
|
||||
Filter.builder().name("group-id").values(group).build())).securityGroupRules().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dryRunPreservesGroupAndRuleTags() {
|
||||
Ec2Client client = client();
|
||||
String group = group(client, vpc(client));
|
||||
String rule = rule(client, group);
|
||||
tag(client, List.of(group, rule));
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class,
|
||||
() -> client.deleteSecurityGroup(request -> request.groupId(group).dryRun(true)));
|
||||
|
||||
assertEquals("DryRunOperation", error.awsErrorDetails().errorCode());
|
||||
assertEquals(2, tagCount(client, List.of(group, rule)));
|
||||
assertEquals(1, client.describeSecurityGroups(request -> request.groupIds(group)).securityGroups().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dependencyRejectionPreservesGroupAndRuleTags() {
|
||||
Ec2Client client = client();
|
||||
String vpc = vpc(client);
|
||||
String group = group(client, vpc);
|
||||
String rule = rule(client, group);
|
||||
tag(client, List.of(group, rule));
|
||||
String subnet = client.createSubnet(request -> request.vpcId(vpc).cidrBlock("10.231.0.0/24"))
|
||||
.subnet().subnetId();
|
||||
cleanup.register(() -> client.deleteSubnet(request -> request.subnetId(subnet)));
|
||||
String networkInterface = client.createNetworkInterface(request -> request.subnetId(subnet).groups(group))
|
||||
.networkInterface().networkInterfaceId();
|
||||
cleanup.register(() -> client.deleteNetworkInterface(request -> request.networkInterfaceId(networkInterface)));
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class,
|
||||
() -> client.deleteSecurityGroup(request -> request.groupId(group)));
|
||||
|
||||
assertEquals("DependencyViolation", error.awsErrorDetails().errorCode());
|
||||
assertEquals(2, tagCount(client, List.of(group, rule)));
|
||||
assertEquals(1, client.describeSecurityGroups(request -> request.groupIds(group)).securityGroups().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointGroupReplacementRetainsReferencesUntilRemovalOrDeletion() {
|
||||
Ec2Client client = client();
|
||||
String vpc = vpc(client);
|
||||
String original = group(client, vpc);
|
||||
String replacement = group(client, vpc);
|
||||
String subnet = client.createSubnet(request -> request.vpcId(vpc).cidrBlock("10.231.1.0/24"))
|
||||
.subnet().subnetId();
|
||||
cleanup.register(() -> client.deleteSubnet(request -> request.subnetId(subnet)));
|
||||
String endpoint = client.createVpcEndpoint(request -> request.vpcId(vpc)
|
||||
.vpcEndpointType("Interface").serviceName("com.amazonaws.us-west-2.ssm")
|
||||
.subnetIds(subnet).securityGroupIds(original)).vpcEndpoint().vpcEndpointId();
|
||||
cleanup.register(() -> client.describeVpcEndpoints(request -> request.filters(
|
||||
Filter.builder().name("vpc-id").values(vpc).build())).vpcEndpoints().stream()
|
||||
.filter(value -> endpoint.equals(value.vpcEndpointId()))
|
||||
.forEach(value -> client.deleteVpcEndpoints(request -> request.vpcEndpointIds(endpoint))));
|
||||
tag(client, List.of(original, replacement, endpoint));
|
||||
|
||||
assertEquals("DependencyViolation", assertThrows(Ec2Exception.class,
|
||||
() -> client.deleteSecurityGroup(request -> request.groupId(original))).awsErrorDetails().errorCode());
|
||||
assertEquals(3, tagCount(client, List.of(original, replacement, endpoint)));
|
||||
assertEquals("InvalidGroup.NotFound", assertThrows(Ec2Exception.class,
|
||||
() -> client.modifyVpcEndpoint(request -> request.vpcEndpointId(endpoint)
|
||||
.addSecurityGroupIds("sg-00000000000000000").removeSecurityGroupIds(original)
|
||||
.privateDnsEnabled(false))).awsErrorDetails().errorCode());
|
||||
assertEquals(List.of(original), client.describeVpcEndpoints(request -> request.vpcEndpointIds(endpoint))
|
||||
.vpcEndpoints().getFirst().groups().stream().map(value -> value.groupId()).toList());
|
||||
|
||||
client.modifyVpcEndpoint(request -> request.vpcEndpointId(endpoint)
|
||||
.addSecurityGroupIds(replacement).removeSecurityGroupIds(original));
|
||||
client.deleteSecurityGroup(request -> request.groupId(original));
|
||||
assertEquals("DependencyViolation", assertThrows(Ec2Exception.class,
|
||||
() -> client.deleteSecurityGroup(request -> request.groupId(replacement))).awsErrorDetails().errorCode());
|
||||
client.deleteVpcEndpoints(request -> request.vpcEndpointIds(endpoint));
|
||||
client.deleteSecurityGroup(request -> request.groupId(replacement));
|
||||
assertEquals(0, tagCount(client, List.of(original, replacement, endpoint)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void endpointReferencesCannotResolveGroupsInAnotherAccountOrRegion(boolean foreignAccount) {
|
||||
Ec2Client owner = client();
|
||||
String group = group(owner, vpc(owner));
|
||||
Ec2Client other = client(foreignAccount ? Region.US_WEST_2 : Region.US_EAST_1,
|
||||
foreignAccount ? "555566667790" : "555566667789");
|
||||
String otherVpc = vpc(other);
|
||||
assertEquals("InvalidGroup.NotFound", assertThrows(Ec2Exception.class,
|
||||
() -> other.createVpcEndpoint(request -> request.vpcId(otherVpc).vpcEndpointType("Interface")
|
||||
.serviceName("test-service").securityGroupIds(group))).awsErrorDetails().errorCode());
|
||||
assertTrue(other.describeVpcEndpoints(request -> request.filters(
|
||||
Filter.builder().name("vpc-id").values(otherVpc).build())).vpcEndpoints().isEmpty());
|
||||
assertEquals(1, owner.describeSecurityGroups(request -> request.groupIds(group)).securityGroups().size());
|
||||
}
|
||||
|
||||
private Ec2Client client() {
|
||||
return client(Region.US_WEST_2, "555566667789");
|
||||
}
|
||||
|
||||
private Ec2Client client(Region region, String account) {
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), account, region);
|
||||
cleanup.register(client::close);
|
||||
return client;
|
||||
}
|
||||
|
||||
private String vpc(Ec2Client client) {
|
||||
String vpc = client.createVpc(request -> request.cidrBlock("10.231.0.0/16")).vpc().vpcId();
|
||||
cleanup.register(() -> client.deleteVpc(request -> request.vpcId(vpc)));
|
||||
return vpc;
|
||||
}
|
||||
|
||||
private String group(Ec2Client client, String vpc) {
|
||||
String name = "tag-deletion-" + UUID.randomUUID();
|
||||
cleanup.register(() -> client.describeSecurityGroups(request -> request.filters(
|
||||
Filter.builder().name("vpc-id").values(vpc).build(),
|
||||
Filter.builder().name("group-name").values(name).build())).securityGroups()
|
||||
.forEach(group -> client.deleteSecurityGroup(request -> request.groupId(group.groupId()))));
|
||||
return client.createSecurityGroup(request -> request.vpcId(vpc).groupName(name)
|
||||
.description("owned tag cleanup fixture")).groupId();
|
||||
}
|
||||
|
||||
private static String rule(Ec2Client client, String group) {
|
||||
return client.describeSecurityGroupRules(request -> request.filters(
|
||||
Filter.builder().name("group-id").values(group).build()))
|
||||
.securityGroupRules().getFirst().securityGroupRuleId();
|
||||
}
|
||||
|
||||
private static void tag(Ec2Client client, List<String> resources) {
|
||||
client.createTags(request -> request.resources(resources)
|
||||
.tags(Tag.builder().key("Owner").value("tag-deletion-fixture").build()));
|
||||
}
|
||||
|
||||
private static int tagCount(Ec2Client client, List<String> resources) {
|
||||
return client.describeTags(request -> request.filters(
|
||||
Filter.builder().name("resource-id").values(resources).build())).tags().size();
|
||||
}
|
||||
}
|
||||
@@ -288,11 +288,15 @@ class Ec2ServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultSecurityGroupOfIsEmptyOnceTheDefaultGroupIsGone() {
|
||||
Ec2Service service = mockModeService();
|
||||
void defaultSecurityGroupOfIsEmptyWhenTheStoredDefaultGroupIsMissing() {
|
||||
AccountAwareStorageBackend<SecurityGroup> groups = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(Map.of("ec2-security-groups.json", groups)));
|
||||
String region = "us-east-1";
|
||||
String vpcId = service.createVpc(region, "10.94.0.0/16", false).getVpcId();
|
||||
service.deleteSecurityGroup(region, service.defaultSecurityGroupOf(region, vpcId).orElseThrow().getGroupId());
|
||||
// Model a missing persisted record; the public API cannot delete a default group.
|
||||
groups.delete(region + "::" + service.defaultSecurityGroupOf(region, vpcId).orElseThrow().getGroupId());
|
||||
|
||||
assertTrue(service.defaultSecurityGroupOf(region, vpcId).isEmpty());
|
||||
}
|
||||
@@ -9580,6 +9584,92 @@ class Ec2ServiceTest {
|
||||
assertEquals("InvalidInstanceID.NotFound", error.getErrorCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"instance-state", "instance-groups", "interface-groups", "endpoint-groups",
|
||||
"ingress", "egress", "group-pairs"})
|
||||
void deleteSecurityGroupToleratesUnrelatedNullAttachmentFields(String field) {
|
||||
AccountAwareStorageBackend<Instance> instanceStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
AccountAwareStorageBackend<NetworkInterface> interfaceStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
AccountAwareStorageBackend<VpcEndpoint> endpointStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(Map.of(
|
||||
"ec2-instances.json", instanceStore, "ec2-network-interfaces.json", interfaceStore,
|
||||
"ec2-vpc-endpoints.json", endpointStore)));
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.79.0.0/16", false).getVpcId();
|
||||
SecurityGroup selected = service.createSecurityGroup(region, "selected", "selected", vpc);
|
||||
SecurityGroup unrelated = service.createSecurityGroup(region, "unrelated", "unrelated", vpc);
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-null-fields");
|
||||
instance.setRegion(region);
|
||||
instance.setState("instance-state".equals(field) ? null : InstanceState.running());
|
||||
instance.setSecurityGroups("instance-groups".equals(field) ? null : List.of());
|
||||
instanceStore.put(region + "::i-null-fields", instance);
|
||||
NetworkInterface networkInterface = new NetworkInterface();
|
||||
networkInterface.setNetworkInterfaceId("eni-null-fields");
|
||||
networkInterface.setGroups("interface-groups".equals(field) ? null : List.of());
|
||||
interfaceStore.put(region + "::eni-null-fields", networkInterface);
|
||||
VpcEndpoint endpoint = new VpcEndpoint();
|
||||
endpoint.setVpcEndpointId("vpce-null-fields");
|
||||
endpoint.setSecurityGroupIds("endpoint-groups".equals(field) ? null : List.of());
|
||||
endpointStore.put(region + "::vpce-null-fields", endpoint);
|
||||
if ("ingress".equals(field)) {
|
||||
unrelated.setIpPermissions(null);
|
||||
}
|
||||
if ("egress".equals(field)) {
|
||||
unrelated.setIpPermissionsEgress(null);
|
||||
}
|
||||
if ("group-pairs".equals(field)) {
|
||||
IpPermission permission = new IpPermission();
|
||||
permission.setUserIdGroupPairs(null);
|
||||
unrelated.setIpPermissions(List.of(permission));
|
||||
}
|
||||
|
||||
service.deleteSecurityGroup(region, selected.getGroupId());
|
||||
|
||||
assertTrue(service.describeSecurityGroups(region, List.of(selected.getGroupId()), List.of(), Map.of()).isEmpty());
|
||||
assertEquals(unrelated.getGroupId(), service.describeSecurityGroups(
|
||||
region, List.of(unrelated.getGroupId()), List.of(), Map.of()).getFirst().getGroupId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSecurityGroupRetainsAttachmentWithUnknownInstanceState() {
|
||||
AccountAwareStorageBackend<Instance> instances = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(Map.of("ec2-instances.json", instances)));
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.79.0.0/16", false).getVpcId();
|
||||
SecurityGroup selected = service.createSecurityGroup(region, "selected", "selected", vpc);
|
||||
Instance instance = new Instance();
|
||||
instance.setState(null);
|
||||
instance.setSecurityGroups(List.of(new GroupIdentifier(selected.getGroupId(), selected.getGroupName())));
|
||||
instances.put(region + "::i-unknown-state", instance);
|
||||
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, selected.getGroupId())).getErrorCode());
|
||||
assertEquals(selected.getGroupId(), service.describeSecurityGroups(
|
||||
region, List.of(selected.getGroupId()), List.of(), Map.of()).getFirst().getGroupId());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " "})
|
||||
void deleteSecurityGroupRequiresAnIdentifierWithoutMutation(String blank) {
|
||||
Ec2Service service = mockModeService();
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.79.0.0/16", false).getVpcId();
|
||||
SecurityGroup selected = service.createSecurityGroup(region, "selected", "selected", vpc);
|
||||
assertEquals("MissingParameter", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, null, blank, false)).getErrorCode());
|
||||
assertEquals("MissingParameter", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, blank, null, false)).getErrorCode());
|
||||
assertEquals("MissingParameter", assertThrows(AwsException.class,
|
||||
() -> service.deleteSecurityGroup(region, null, null, false)).getErrorCode());
|
||||
assertEquals(selected.getGroupId(), service.describeSecurityGroups(
|
||||
region, List.of(selected.getGroupId()), List.of(), Map.of()).getFirst().getGroupId());
|
||||
}
|
||||
|
||||
private static Ec2Service mockModeService() {
|
||||
return mockModeService(mockConfig(true));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user