mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(ec2): support ModifyNetworkInterfaceAttribute (#8532)
ModifyNetworkInterfaceAttribute was not implemented, so a call to change
an interface's security groups, description, source/destination check
or DeleteOnTermination was refused, and with security-group enforcement
on an interface's groups could only change through ModifyInstanceAttribute.
The action now changes a standalone interface or one an instance was
launched with. The group list is read as SecurityGroupId.N, the name the
SDKs and the CLI send. On an instance's primary interface the groups and
the source/destination check are the instance's too. With enforcement
on, a group change reaches the interface's firewall before it is stored,
under the instance's lock, as ModifyInstanceAttribute does, so a policy
that cannot be applied leaves the groups as they were, and the ports the
instance's groups publish are reconciled after a primary-interface change.
The change re-checks the interface and its attachment in the critical
section that stores it, and AttachNetworkInterface and
DetachNetworkInterface now update the standalone record and the instance's
copy under the same topology lock.
ModifyInstanceAttribute no longer overwrites every interface's groups: on
an instance with more than one interface, a group or SourceDestCheck change
answers InvalidInstanceID ("There are multiple interfaces attached to
instance ... Please specify an interface ID for the operation instead."),
the code and message AWS returns, as the Terraform AWS provider quotes them.
The members Floci does not apply (EnablePrimaryIpv6, EnaSrdSpecification,
ConnectionTrackingSpecification, AssociatePublicIpAddress,
AssociatedSubnetIds and the attachment's ENA queue counts) answer
UnsupportedOperation, as ReplaceRoute refuses a target it cannot store,
rather than true with nothing changed.
Part of #2564.
This commit is contained in:
1 parent
a015fd9fb8
commit
82b7547f0a
6 files changed
+586
-60
No files matched your search
@@ -382,7 +382,7 @@ naming different VPCs find nothing.
|
||||
| GetConsoleOutput | Returns a console log carrying the guest's SSH host keys between the `-----BEGIN SSH HOST KEY KEYS-----` and `-----END SSH HOST KEY KEYS-----` markers cloud-init prints, read from the running instance container. An instance that is not running, or whose container cannot be read, returns an empty log, as a just-launched one does on AWS. An instance in another region is `InvalidInstanceID.NotFound`. `DryRun=true` returns `DryRunOperation` before the instance is looked up, as on AWS. |
|
||||
| DescribeInstanceCreditSpecifications | Returns the CPU credit option of burstable performance instances. A named instance id reports the option the instance acquired at launch, either the explicit `CreditSpecification.CpuCredits` or the family default, `standard` for t2 and `unlimited` for t3, t3a and t4g. An id that is not a burstable performance instance reports `standard`, and only an unknown id is an error. Naming no id returns the instances on the unlimited option, including one that kept `unlimited` after a resize onto a non-burstable type. `Filter.N` supports the modeled `instance-id` and narrows whichever set the request selected. `MaxResults` accepts 5 through 1000 and cannot be combined with instance ids. `DryRun=true` returns `DryRunOperation`. |
|
||||
| DescribeInstanceAttribute | Returns a supported attribute for an instance. `ebsOptimized` reports what `RunInstances` (or its launch template) set; instances launched by CloudFormation, Auto Scaling or Fleet report `false`. |
|
||||
| ModifyInstanceAttribute | Updates supported mutable attributes for an instance. `UserData.Value` (base64) needs the instance stopped, as on AWS, and answers `IncorrectInstanceState` otherwise. |
|
||||
| ModifyInstanceAttribute | Updates supported mutable attributes for an instance. `UserData.Value` (base64) needs the instance stopped, as on AWS, and answers `IncorrectInstanceState` otherwise. A group or `SourceDestCheck` change on an instance with more than one network interface answers `InvalidInstanceID` ("There are multiple interfaces attached to instance..."), as on AWS; change each interface with `ModifyNetworkInterfaceAttribute` instead. |
|
||||
| ModifyInstanceMetadataOptions | Updates an instance's IMDS options, changing only the fields the request names. An EKS cluster node is refused with `OperationNotPermitted`. |
|
||||
|
||||
### VPCs
|
||||
@@ -1258,11 +1258,12 @@ profile.
|
||||
| DescribeNetworkInterfaces | Lists network interfaces known to the local EC2 service, both an instance's implicit primary interface and standalone ENIs created via `CreateNetworkInterface`. |
|
||||
| AttachNetworkInterface | Attaches an available standalone ENI to a running or stopped instance at a device index. |
|
||||
| DetachNetworkInterface | Detaches a standalone ENI by attachment ID, returning it to `available`. |
|
||||
| ModifyNetworkInterfaceAttribute | Changes a standalone ENI or an instance's launch-created interface: its security groups (`SecurityGroupId.N`), `Description`, `SourceDestCheck`, or its attachment's `DeleteOnTermination`. On an instance's primary interface the groups and the check are the instance's too. With security-group enforcement on, a group change reaches the interface's firewall before it is stored. The members Floci does not apply (`EnablePrimaryIpv6`, `EnaSrdSpecification`, `ConnectionTrackingSpecification`, `AssociatePublicIpAddress`, `AssociatedSubnetIds`, and the attachment's `DefaultEnaQueueCount` and `EnaQueueCount`) answer `UnsupportedOperation` rather than `true` with nothing changed. |
|
||||
| DeleteNetworkInterface | Deletes a standalone ENI. Fails while the ENI is still attached, matching AWS. |
|
||||
|
||||
A standalone ENI created via `CreateNetworkInterface` can also be handed to `RunInstances` as an instance's primary interface (`NetworkInterface.1.NetworkInterfaceId` / `NetworkInterface.1.DeviceIndex`) instead of letting the instance create its own implicit one, the pattern Terraform's `aws_instance` resource uses for `network_interface { network_interface_id = ... }`. AWS only allows this for a single instance per launch call; `RunInstances` rejects it otherwise with `InvalidParameterCombination`.
|
||||
|
||||
`ModifyNetworkInterfaceAttribute` is not implemented: no example in the corpus that needed `CreateNetworkInterface` was found to need it. A route table's `CreateRoute` with a `NetworkInterfaceId` target is accepted but not recorded, since `Route` does not yet model an ENI target; a subsequent `plan` against such a route may show drift.
|
||||
AWS takes one attribute per `ModifyNetworkInterfaceAttribute` call; Floci applies every attribute a call names. A route table's `CreateRoute` with a `NetworkInterfaceId` target is accepted but not recorded, since `Route` does not yet model an ENI target; a subsequent `plan` against such a route may show drift.
|
||||
|
||||
### Volumes
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 |
|
||||
| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 59 |
|
||||
| [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 26 |
|
||||
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 228 |
|
||||
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 229 |
|
||||
| [EC2 Instance Connect](ec2-instance-connect.md) | `POST /` + `X-Amz-Target: AWSEC2InstanceConnectService.*` | JSON 1.1 | 2 |
|
||||
| [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions |
|
||||
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 |
|
||||
|
||||
@@ -43,6 +43,13 @@ public class Ec2QueryHandler {
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
/** ReplaceRoute targets AWS accepts that a stored {@code Route} cannot represent here. */
|
||||
/**
|
||||
* ModifyNetworkInterfaceAttribute members Floci does not apply, as their query names prefix them. Each is refused,
|
||||
* as ReplaceRoute refuses a target it cannot store, rather than answering true with nothing changed.
|
||||
*/
|
||||
private static final List<String> UNAPPLIED_INTERFACE_ATTRIBUTES = List.of("EnablePrimaryIpv6",
|
||||
"EnaSrdSpecification", "ConnectionTrackingSpecification", "AssociatePublicIpAddress", "AssociatedSubnetId",
|
||||
"Attachment.DefaultEnaQueueCount", "Attachment.EnaQueueCount");
|
||||
private static final List<String> UNSUPPORTED_ROUTE_TARGETS = List.of(
|
||||
"CarrierGatewayId", "CoreNetworkArn", "EgressOnlyInternetGatewayId",
|
||||
"LocalGatewayId", "OdbNetworkArn",
|
||||
@@ -350,6 +357,7 @@ public class Ec2QueryHandler {
|
||||
case "DeleteNetworkInterface" -> handleDeleteNetworkInterface(params, region);
|
||||
case "AttachNetworkInterface" -> handleAttachNetworkInterface(params, region);
|
||||
case "DetachNetworkInterface" -> handleDetachNetworkInterface(params, region);
|
||||
case "ModifyNetworkInterfaceAttribute" -> handleModifyNetworkInterfaceAttribute(params, region);
|
||||
// Volumes
|
||||
case "CreateVolume" -> handleCreateVolume(params, region);
|
||||
case "DescribeVolumes" -> handleDescribeVolumes(params, region);
|
||||
@@ -1721,8 +1729,7 @@ public class Ec2QueryHandler {
|
||||
groupIds.add(groupId);
|
||||
}
|
||||
if (dryRun(p)) {
|
||||
service.checkInstanceAttributeChange(region, instanceId, userDataEncoded != null, attrName != null,
|
||||
groupIds);
|
||||
service.checkInstanceAttributeChange(region, instanceId, userDataEncoded != null, attrName, groupIds);
|
||||
throw Ec2Service.dryRunOperation();
|
||||
}
|
||||
if (userDataEncoded != null) {
|
||||
@@ -5573,6 +5580,30 @@ public class Ec2QueryHandler {
|
||||
return booleanResponse("DetachNetworkInterface");
|
||||
}
|
||||
|
||||
private Response handleModifyNetworkInterfaceAttribute(MultivaluedMap<String, String> p, String region) {
|
||||
String networkInterfaceId = p.getFirst("NetworkInterfaceId");
|
||||
if (networkInterfaceId == null || networkInterfaceId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter NetworkInterfaceId",
|
||||
400);
|
||||
}
|
||||
for (String member : UNAPPLIED_INTERFACE_ATTRIBUTES) {
|
||||
if (p.keySet().stream().anyMatch(name -> name.equals(member) || name.startsWith(member + "."))) {
|
||||
throw new AwsException("UnsupportedOperation",
|
||||
"ModifyNetworkInterfaceAttribute with " + member + " is not supported.", 400);
|
||||
}
|
||||
}
|
||||
// The SDKs and the CLI send the group list as SecurityGroupId.N: botocore's Groups member carries that
|
||||
// locationName, and the EC2 protocol serializes a list by it.
|
||||
Ec2Service.NetworkInterfaceAttributeChange change = new Ec2Service.NetworkInterfaceAttributeChange(
|
||||
getList(p, "SecurityGroupId"),
|
||||
p.getFirst("Description.Value"),
|
||||
parseOptionalBoolean(p.getFirst("SourceDestCheck.Value"), "SourceDestCheck"),
|
||||
p.getFirst("Attachment.AttachmentId"),
|
||||
parseOptionalBoolean(p.getFirst("Attachment.DeleteOnTermination"), "Attachment.DeleteOnTermination"));
|
||||
service.modifyNetworkInterfaceAttribute(region, networkInterfaceId, change, dryRun(p));
|
||||
return booleanResponse("ModifyNetworkInterfaceAttribute");
|
||||
}
|
||||
|
||||
// ─── XML fragment builders ────────────────────────────────────────────────
|
||||
|
||||
private String instanceXml(Instance inst, Map<String, String> capacityAssociations,
|
||||
|
||||
@@ -5903,22 +5903,38 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
* is nothing to check.
|
||||
*/
|
||||
public void checkInstanceAttributeChange(String region, String instanceId, boolean userData,
|
||||
boolean attribute, List<String> groupIds) {
|
||||
String attribute, List<String> groupIds) {
|
||||
ensureDefaultResources(region);
|
||||
if (!userData && !attribute && groupIds.isEmpty()) {
|
||||
if (!userData && attribute == null && groupIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Instance inst = getRequiredInstance(region, instanceId);
|
||||
if (userData) {
|
||||
requireStoppedForUserData(inst);
|
||||
}
|
||||
if ("sourceDestCheck".equals(attribute)) {
|
||||
requireSingleInterface(inst);
|
||||
}
|
||||
if (!groupIds.isEmpty()) {
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
requireSingleInterface(inst);
|
||||
instanceVpcGroups(region, inst, groupIds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS refuses an instance-level group or source/destination check change on an instance with more than one
|
||||
* network interface, since those belong to each interface; ModifyNetworkInterfaceAttribute changes them there.
|
||||
* The code and message are AWS's own, as the Terraform AWS provider quotes them.
|
||||
*/
|
||||
private static void requireSingleInterface(Instance inst) {
|
||||
if (inst.getNetworkInterfaces() != null && inst.getNetworkInterfaces().size() > 1) {
|
||||
throw new AwsException("InvalidInstanceID", "There are multiple interfaces attached to instance '"
|
||||
+ inst.getInstanceId() + "'. Please specify an interface ID for the operation instead.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** New user data needs the instance stopped, as on AWS. */
|
||||
private static void requireStoppedForUserData(Instance inst) {
|
||||
String state = inst.getState() != null ? inst.getState().getName() : null;
|
||||
@@ -5956,7 +5972,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
inst.setCreditSpecificationCpuCredits(acquiredCpuCredits(value, null));
|
||||
}
|
||||
}
|
||||
case "sourceDestCheck" -> inst.setSourceDestCheck(Boolean.parseBoolean(value));
|
||||
case "sourceDestCheck" -> {
|
||||
requireSingleInterface(inst);
|
||||
inst.setSourceDestCheck(Boolean.parseBoolean(value));
|
||||
}
|
||||
case "ebsOptimized" -> inst.setEbsOptimized(Boolean.parseBoolean(value));
|
||||
}
|
||||
instances.put(key(region, instanceId), inst);
|
||||
@@ -5983,6 +6002,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
List<GroupIdentifier> identifiers = new ArrayList<>();
|
||||
List<String> protectedGroups = new ArrayList<>();
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
requireSingleInterface(inst);
|
||||
for (SecurityGroup sg : instanceVpcGroups(region, inst, groupIds)) {
|
||||
identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
|
||||
protectedGroups.add(callerAccountId() + "::" + key(region, sg.getGroupId()));
|
||||
@@ -16192,30 +16212,217 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
Instance inst = instances.get(key(region, instanceId)).orElse(null);
|
||||
if (inst == null) return;
|
||||
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
|
||||
NetworkInterface ni = networkInterfaces.get(key(region, eni.getNetworkInterfaceId())).orElse(null);
|
||||
if (ni == null) {
|
||||
// Implicit (auto-created) interface: honor the flag. When false, create a standalone
|
||||
// record so the interface is returned to "available" on termination instead of deleted.
|
||||
eni.setDeleteOnTermination(value);
|
||||
if (!value) {
|
||||
NetworkInterface standalone = synthesizeImplicitNetworkInterface(inst, eni, region, callerAccountId());
|
||||
NetworkInterfaceAttachment att = standalone.getAttachment();
|
||||
att.setDeleteOnTermination(false);
|
||||
standalone.setStatus("in-use");
|
||||
networkInterfaces.put(key(region, eni.getNetworkInterfaceId()), standalone);
|
||||
}
|
||||
} else {
|
||||
// Supplied (caller-created) interface: honor the flag on both copies.
|
||||
eni.setDeleteOnTermination(value);
|
||||
if (ni.getAttachment() != null) {
|
||||
ni.getAttachment().setDeleteOnTermination(value);
|
||||
networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni);
|
||||
}
|
||||
}
|
||||
setDeleteOnTermination(region, inst, eni, value);
|
||||
}
|
||||
instances.put(key(region, instanceId), inst);
|
||||
}
|
||||
|
||||
/** Sets one interface's DeleteOnTermination; the caller persists {@code inst}. */
|
||||
private void setDeleteOnTermination(String region, Instance inst, InstanceNetworkInterface eni, boolean value) {
|
||||
NetworkInterface ni = networkInterfaces.get(key(region, eni.getNetworkInterfaceId())).orElse(null);
|
||||
eni.setDeleteOnTermination(value);
|
||||
if (ni == null) {
|
||||
// Implicit (auto-created) interface: when false, create a standalone record so the
|
||||
// interface is returned to "available" on termination instead of deleted.
|
||||
if (!value) {
|
||||
NetworkInterface standalone = synthesizeImplicitNetworkInterface(inst, eni, region, callerAccountId());
|
||||
standalone.getAttachment().setDeleteOnTermination(false);
|
||||
standalone.setStatus("in-use");
|
||||
networkInterfaces.put(key(region, eni.getNetworkInterfaceId()), standalone);
|
||||
}
|
||||
} else if (ni.getAttachment() != null) {
|
||||
// Supplied (caller-created) interface: honor the flag on both copies.
|
||||
ni.getAttachment().setDeleteOnTermination(value);
|
||||
networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni);
|
||||
}
|
||||
}
|
||||
|
||||
/** The attributes one ModifyNetworkInterfaceAttribute call names: empty or null where it names none. */
|
||||
public record NetworkInterfaceAttributeChange(List<String> groupIds, String description, Boolean sourceDestCheck,
|
||||
String attachmentId, Boolean deleteOnTermination) {
|
||||
}
|
||||
|
||||
/**
|
||||
* ModifyNetworkInterfaceAttribute, for a standalone interface or one an instance was launched with. A group
|
||||
* change reaches the interface's security-group firewall before it is stored, so a policy that cannot be
|
||||
* applied leaves the groups as they were, as {@link #modifyInstanceGroups} does. On an instance's primary
|
||||
* interface the groups and the source/destination check are the instance's too.
|
||||
*/
|
||||
public void modifyNetworkInterfaceAttribute(String region, String networkInterfaceId,
|
||||
NetworkInterfaceAttributeChange change, boolean dryRun) {
|
||||
ensureDefaultResources(region);
|
||||
// The instance's lock when the interface has one, so a ModifyInstanceAttribute group change on the same
|
||||
// instance cannot reach the firewall in between. An attach or detach can move the interface before that
|
||||
// lock is held, which the locked step reports so the change starts again under the right lock.
|
||||
while (true) {
|
||||
String host;
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
host = interfaceHostId(region, networkInterfaceId);
|
||||
}
|
||||
String lockKey = callerAccountId() + "::" + key(region, host != null ? host : networkInterfaceId);
|
||||
boolean applied = withResourceLock(instanceGroupLocks, lockKey,
|
||||
() -> modifyNetworkInterfaceAttributeLocked(region, networkInterfaceId, change, dryRun, host));
|
||||
if (applied) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** False when the interface's host changed from {@code expectedHost}, so the caller starts again. */
|
||||
private boolean modifyNetworkInterfaceAttributeLocked(String region, String networkInterfaceId,
|
||||
NetworkInterfaceAttributeChange change, boolean dryRun,
|
||||
String expectedHost) {
|
||||
List<String> protectedGroups;
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
if (!Objects.equals(expectedHost, interfaceHostId(region, networkInterfaceId))) {
|
||||
return false;
|
||||
}
|
||||
protectedGroups = validateNetworkInterfaceAttributeChange(region, networkInterfaceId, change).stream()
|
||||
.map(group -> callerAccountId() + "::" + key(region, group.getGroupId())).toList();
|
||||
if (dryRun) {
|
||||
throw dryRunOperation();
|
||||
}
|
||||
protectedGroups.forEach(group -> pendingSecurityGroupAssignments.merge(group, 1, Integer::sum));
|
||||
}
|
||||
|
||||
try {
|
||||
if (!change.groupIds().isEmpty() && securityGroupEnforcementEnabled() && !config.services().ec2().mock()) {
|
||||
List<SecurityGroup> current = securityGroups.scan(k -> k.startsWith(region + "::"));
|
||||
Map<String, SecurityGroup> byId = current.stream().collect(Collectors.toMap(
|
||||
SecurityGroup::getGroupId, Function.identity()));
|
||||
containerManager.updateSecurityGroups(networkInterfaceId, new HashSet<>(change.groupIds()), byId,
|
||||
policyPrefixLists(region, current));
|
||||
}
|
||||
Instance primaryHost;
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
if (!Objects.equals(expectedHost, interfaceHostId(region, networkInterfaceId))) {
|
||||
return false;
|
||||
}
|
||||
List<GroupIdentifier> identifiers =
|
||||
validateNetworkInterfaceAttributeChange(region, networkInterfaceId, change);
|
||||
primaryHost = applyNetworkInterfaceAttributeChange(region, networkInterfaceId, change, identifiers);
|
||||
}
|
||||
// The instance's groups changed, so the ports they publish change too, as after ModifyInstanceAttribute.
|
||||
if (primaryHost != null && config.services().ec2().publishSecurityGroupPorts()
|
||||
&& !config.services().ec2().mock() && primaryHost.getDockerContainerId() != null
|
||||
&& primaryHost.getState() != null && "running".equals(primaryHost.getState().getName())) {
|
||||
portForwardManager.reconcile(primaryHost, desiredPublishedPorts(region, primaryHost));
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
protectedGroups.forEach(group -> pendingSecurityGroupAssignments.computeIfPresent(
|
||||
group, (ignored, count) -> count == 1 ? null : count - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the interface exists and the change fits it, and returns the groups it names. Run in the critical
|
||||
* section that validates the change and again in the one that stores it, so nothing it checked can have moved.
|
||||
*/
|
||||
private List<GroupIdentifier> validateNetworkInterfaceAttributeChange(String region, String networkInterfaceId,
|
||||
NetworkInterfaceAttributeChange change) {
|
||||
NetworkInterface stored = networkInterfaces.get(key(region, networkInterfaceId))
|
||||
.map(ni -> releaseIfHostIsGone(region, ni)).orElse(null);
|
||||
Instance host = interfaceHost(region, networkInterfaceId).orElse(null);
|
||||
InstanceNetworkInterface copy = host == null ? null : instanceCopy(host, networkInterfaceId);
|
||||
if (stored == null && copy == null) {
|
||||
throw new AwsException("InvalidNetworkInterfaceID.NotFound",
|
||||
"The network interface ID '" + networkInterfaceId + "' does not exist", 400);
|
||||
}
|
||||
String vpcId = stored != null ? stored.getVpcId() : copy.getVpcId();
|
||||
List<GroupIdentifier> identifiers = new ArrayList<>();
|
||||
for (String groupId : change.groupIds()) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
if (!Objects.equals(vpcId, sg.getVpcId())) {
|
||||
throw new AwsException("InvalidGroup.NotFound",
|
||||
"Security group " + groupId + " does not belong to the network interface VPC", 400);
|
||||
}
|
||||
identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
|
||||
}
|
||||
if (change.deleteOnTermination() != null) {
|
||||
String attachmentId = copy != null ? copy.getAttachmentId()
|
||||
: stored.getAttachment() != null ? stored.getAttachment().getAttachmentId() : null;
|
||||
if (attachmentId == null || !attachmentId.equals(change.attachmentId())) {
|
||||
throw new AwsException("InvalidAttachmentID.NotFound",
|
||||
"The attachment ID '" + change.attachmentId() + "' does not exist", 400);
|
||||
}
|
||||
}
|
||||
return identifiers;
|
||||
}
|
||||
|
||||
/** Stores the change; returns the instance whose own groups it changed, or null. */
|
||||
private Instance applyNetworkInterfaceAttributeChange(String region, String networkInterfaceId,
|
||||
NetworkInterfaceAttributeChange change,
|
||||
List<GroupIdentifier> identifiers) {
|
||||
NetworkInterface stored = networkInterfaces.get(key(region, networkInterfaceId)).orElse(null);
|
||||
if (stored != null) {
|
||||
if (!identifiers.isEmpty()) {
|
||||
stored.setGroups(new ArrayList<>(identifiers));
|
||||
}
|
||||
if (change.description() != null) {
|
||||
stored.setDescription(change.description());
|
||||
}
|
||||
if (change.sourceDestCheck() != null) {
|
||||
stored.setSourceDestCheck(change.sourceDestCheck());
|
||||
}
|
||||
networkInterfaces.put(key(region, networkInterfaceId), stored);
|
||||
}
|
||||
Instance host = interfaceHost(region, networkInterfaceId).orElse(null);
|
||||
InstanceNetworkInterface copy = host == null ? null : instanceCopy(host, networkInterfaceId);
|
||||
if (copy == null) {
|
||||
return null;
|
||||
}
|
||||
boolean primary = copy.getDeviceIndex() == 0;
|
||||
if (!identifiers.isEmpty()) {
|
||||
copy.setGroups(new ArrayList<>(identifiers));
|
||||
if (primary) {
|
||||
host.setSecurityGroups(new ArrayList<>(identifiers));
|
||||
}
|
||||
}
|
||||
if (change.description() != null) {
|
||||
copy.setDescription(change.description());
|
||||
}
|
||||
if (change.sourceDestCheck() != null) {
|
||||
copy.setSourceDestCheck(change.sourceDestCheck());
|
||||
if (primary) {
|
||||
host.setSourceDestCheck(change.sourceDestCheck());
|
||||
}
|
||||
}
|
||||
if (change.deleteOnTermination() != null) {
|
||||
setDeleteOnTermination(region, host, copy, change.deleteOnTermination());
|
||||
}
|
||||
instances.put(key(region, host.getInstanceId()), host);
|
||||
return primary && !identifiers.isEmpty() ? host : null;
|
||||
}
|
||||
|
||||
private String interfaceHostId(String region, String networkInterfaceId) {
|
||||
return interfaceHost(region, networkInterfaceId).map(Instance::getInstanceId).orElse(null);
|
||||
}
|
||||
|
||||
/** The instance an interface is attached to: the one its standalone record names, or the one launched with it. */
|
||||
private Optional<Instance> interfaceHost(String region, String networkInterfaceId) {
|
||||
String attached = instanceAttachedTo(region, networkInterfaceId);
|
||||
if (attached != null) {
|
||||
return instances.get(key(region, attached));
|
||||
}
|
||||
// A terminated instance's launch interfaces are gone with it, as describeNetworkInterfaces reports them.
|
||||
return instances.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(inst -> inst.getState() == null || !"terminated".equals(inst.getState().getName()))
|
||||
.filter(inst -> instanceCopy(inst, networkInterfaceId) != null)
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private static InstanceNetworkInterface instanceCopy(Instance inst, String networkInterfaceId) {
|
||||
if (inst.getNetworkInterfaces() == null) {
|
||||
return null;
|
||||
}
|
||||
return inst.getNetworkInterfaces().stream()
|
||||
.filter(eni -> networkInterfaceId.equals(eni.getNetworkInterfaceId()))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a standalone ENI and gives the lease its primary address took back to the VPC
|
||||
* network. A requested primary took no lease, so any it carries is a failed launch's, given
|
||||
@@ -16281,6 +16488,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
*/
|
||||
public NetworkInterfaceAttachment attachNetworkInterface(String region, String networkInterfaceId,
|
||||
String instanceId, int deviceIndex) {
|
||||
// Under the topology lock, so the standalone record and the instance's copy change together for anything
|
||||
// that reads both, ModifyNetworkInterfaceAttribute among them.
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
return attachNetworkInterfaceLocked(region, networkInterfaceId, instanceId, deviceIndex);
|
||||
}
|
||||
}
|
||||
|
||||
private NetworkInterfaceAttachment attachNetworkInterfaceLocked(String region, String networkInterfaceId,
|
||||
String instanceId, int deviceIndex) {
|
||||
NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId);
|
||||
if (ni.getAttachment() != null) {
|
||||
throw new AwsException("InvalidNetworkInterface.InUse",
|
||||
@@ -16338,6 +16554,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (attachmentId == null || attachmentId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter AttachmentId", 400);
|
||||
}
|
||||
// As attaching does: the standalone record and the instance's copy change together.
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
return detachNetworkInterfaceLocked(region, attachmentId);
|
||||
}
|
||||
}
|
||||
|
||||
private NetworkInterfaceAttachment detachNetworkInterfaceLocked(String region, String attachmentId) {
|
||||
NetworkInterface ni = networkInterfaces.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(n -> n.getAttachment() != null && attachmentId.equals(n.getAttachment().getAttachmentId()))
|
||||
.findFirst()
|
||||
|
||||
+181
-7
@@ -9,18 +9,27 @@ 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.AttributeBooleanValue;
|
||||
import software.amazon.awssdk.services.ec2.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.ec2.model.ConnectionTrackingSpecificationRequest;
|
||||
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
|
||||
import software.amazon.awssdk.services.ec2.model.EnaSrdSpecification;
|
||||
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.ModifyNetworkInterfaceAttributeRequest;
|
||||
import software.amazon.awssdk.services.ec2.model.NetworkInterface;
|
||||
import software.amazon.awssdk.services.ec2.model.NetworkInterfaceAttachmentChanges;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
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 Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
@@ -37,7 +46,8 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(networkInterface(fixture).groups()));
|
||||
Instance instance = instance(fixture);
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(instance.securityGroups()));
|
||||
assertEquals(List.of(primaryAtLaunch ? fixture.replacement() : fixture.original()),
|
||||
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);
|
||||
@@ -51,8 +61,10 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
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());
|
||||
// Leave no instance reference to the replacement: only the standalone ENI protects it. The instance now
|
||||
// has at most one interface, so the instance-level change is one AWS accepts.
|
||||
fixture.client().modifyInstanceAttribute(request -> request.instanceId(fixture.instance())
|
||||
.groups(fixture.original()));
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client()
|
||||
.deleteSecurityGroup(request -> request.groupId(fixture.replacement())));
|
||||
@@ -66,6 +78,12 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
void replacementReleasesThePreviousGroupForDeletion(boolean primaryAtLaunch) {
|
||||
Fixture fixture = fixture(primaryAtLaunch);
|
||||
replace(fixture, fixture.replacement());
|
||||
if (!primaryAtLaunch) {
|
||||
// The launch-created primary holds the old group too; on an instance with two interfaces each is
|
||||
// changed on its own.
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request
|
||||
.networkInterfaceId(primaryInterfaceId(fixture)).groups(fixture.replacement()));
|
||||
}
|
||||
|
||||
fixture.client().deleteSecurityGroup(request -> request.groupId(fixture.original()));
|
||||
|
||||
@@ -74,7 +92,7 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
|
||||
@Test
|
||||
void invalidReplacementLeavesBothRepresentationsUnchanged() {
|
||||
Fixture fixture = fixture(false);
|
||||
Fixture fixture = fixture(true);
|
||||
NetworkInterface before = networkInterface(fixture);
|
||||
List<GroupIdentifier> beforeGroups = instance(fixture).securityGroups();
|
||||
|
||||
@@ -102,6 +120,148 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
assertEquals(before, networkInterface(fixture));
|
||||
}
|
||||
|
||||
// Catches: ModifyNetworkInterfaceAttribute reading the group list under a name the SDKs do not send (they
|
||||
// send SecurityGroupId.N), so the call reports success and changes nothing.
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void modifyNetworkInterfaceAttributeReplacesTheInterfaceGroups(boolean primaryAtLaunch) {
|
||||
Fixture fixture = fixture(primaryAtLaunch);
|
||||
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(fixture.eni())
|
||||
.groups(fixture.replacement()));
|
||||
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(networkInterface(fixture).groups()));
|
||||
// Only the primary interface's groups are the instance's.
|
||||
assertEquals(List.of(primaryAtLaunch ? fixture.replacement() : fixture.original()),
|
||||
groupIds(instance(fixture).securityGroups()));
|
||||
}
|
||||
|
||||
// Catches: an instance's launch-created primary interface, which has no standalone record, answering
|
||||
// InvalidNetworkInterfaceID.NotFound, or taking the groups on only one of its two copies.
|
||||
@Test
|
||||
void theLaunchCreatedPrimaryInterfaceTakesTheGroups() {
|
||||
Fixture fixture = fixture(false);
|
||||
String primary = primaryInterfaceId(fixture);
|
||||
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(primary)
|
||||
.groups(fixture.replacement()));
|
||||
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(fixture.client().describeNetworkInterfaces(
|
||||
request -> request.networkInterfaceIds(primary)).networkInterfaces().getFirst().groups()));
|
||||
assertEquals(List.of(fixture.replacement()), groupIds(instance(fixture).securityGroups()));
|
||||
}
|
||||
|
||||
// Catches: the attributes other than groups, which Terraform sends through the same action one per call,
|
||||
// being accepted and dropped.
|
||||
@Test
|
||||
void modifyNetworkInterfaceAttributeAppliesTheOtherAttributes() {
|
||||
Fixture fixture = fixture(false);
|
||||
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(fixture.eni())
|
||||
.description(AttributeValue.builder().value("changed description").build()));
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(fixture.eni())
|
||||
.sourceDestCheck(AttributeBooleanValue.builder().value(false).build()));
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(fixture.eni())
|
||||
.attachment(NetworkInterfaceAttachmentChanges.builder().attachmentId(fixture.attachment())
|
||||
.deleteOnTermination(true).build()));
|
||||
|
||||
NetworkInterface changed = networkInterface(fixture);
|
||||
assertEquals("changed description", changed.description());
|
||||
assertFalse(changed.sourceDestCheck());
|
||||
assertTrue(changed.attachment().deleteOnTermination());
|
||||
// Back to false, so terminating the instance during cleanup leaves the interface to be deleted.
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(fixture.eni())
|
||||
.attachment(NetworkInterfaceAttachmentChanges.builder().attachmentId(fixture.attachment())
|
||||
.deleteOnTermination(false).build()));
|
||||
assertFalse(networkInterface(fixture).attachment().deleteOnTermination());
|
||||
}
|
||||
|
||||
// Catches: an instance-level group or source/destination check change on an instance with several
|
||||
// interfaces overwriting every interface, groups a secondary interface was given on its own included, where
|
||||
// AWS refuses the call and asks for the interface instead.
|
||||
@Test
|
||||
void anInstanceWithSeveralInterfacesRefusesInstanceLevelChanges() {
|
||||
Fixture fixture = fixture(false);
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(fixture.eni())
|
||||
.groups(fixture.replacement()));
|
||||
NetworkInterface before = networkInterface(fixture);
|
||||
|
||||
Ec2Exception groups = assertThrows(Ec2Exception.class, () -> fixture.client().modifyInstanceAttribute(
|
||||
request -> request.instanceId(fixture.instance()).groups(fixture.original())));
|
||||
Ec2Exception sourceDestCheck = assertThrows(Ec2Exception.class, () -> fixture.client()
|
||||
.modifyInstanceAttribute(request -> request.instanceId(fixture.instance())
|
||||
.sourceDestCheck(AttributeBooleanValue.builder().value(false).build())));
|
||||
|
||||
for (Ec2Exception error : List.of(groups, sourceDestCheck)) {
|
||||
assertEquals("InvalidInstanceID", error.awsErrorDetails().errorCode());
|
||||
assertEquals("There are multiple interfaces attached to instance '" + fixture.instance()
|
||||
+ "'. Please specify an interface ID for the operation instead.", error.awsErrorDetails().errorMessage());
|
||||
}
|
||||
assertEquals(before, networkInterface(fixture));
|
||||
assertEquals(List.of(fixture.original()), groupIds(instance(fixture).securityGroups()));
|
||||
}
|
||||
|
||||
// Catches: a member the action does not apply answering true with nothing changed; Terraform sends
|
||||
// EnablePrimaryIpv6 through this action for aws_instance.
|
||||
@Test
|
||||
void membersTheActionDoesNotApplyAreRefused() {
|
||||
Fixture fixture = fixture(false);
|
||||
List<Consumer<ModifyNetworkInterfaceAttributeRequest.Builder>> unapplied = List.of(
|
||||
request -> request.enablePrimaryIpv6(true),
|
||||
request -> request.associatePublicIpAddress(true),
|
||||
request -> request.associatedSubnetIds("subnet-00000000000000000"),
|
||||
request -> request.enaSrdSpecification(EnaSrdSpecification.builder().enaSrdEnabled(true).build()),
|
||||
request -> request.connectionTrackingSpecification(ConnectionTrackingSpecificationRequest.builder()
|
||||
.tcpEstablishedTimeout(120).build()),
|
||||
request -> request.attachment(NetworkInterfaceAttachmentChanges.builder()
|
||||
.attachmentId(fixture.attachment()).enaQueueCount(2).build()),
|
||||
request -> request.attachment(NetworkInterfaceAttachmentChanges.builder()
|
||||
.attachmentId(fixture.attachment()).defaultEnaQueueCount(true).build()));
|
||||
NetworkInterface before = networkInterface(fixture);
|
||||
|
||||
for (Consumer<ModifyNetworkInterfaceAttributeRequest.Builder> member : unapplied) {
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client()
|
||||
.modifyNetworkInterfaceAttribute(request -> member.accept(request.networkInterfaceId(fixture.eni()))));
|
||||
assertEquals("UnsupportedOperation", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
assertEquals(before, networkInterface(fixture));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownGroupLeavesTheInterfaceUnchanged() {
|
||||
Fixture fixture = fixture(false);
|
||||
NetworkInterface before = networkInterface(fixture);
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client().modifyNetworkInterfaceAttribute(
|
||||
request -> request.networkInterfaceId(fixture.eni()).groups(fixture.replacement(),
|
||||
"sg-00000000000000000")));
|
||||
|
||||
assertEquals("InvalidGroup.NotFound", error.awsErrorDetails().errorCode());
|
||||
assertEquals(before, networkInterface(fixture));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAttachmentTheInterfaceDoesNotHaveIsRefused() {
|
||||
Fixture fixture = fixture(false);
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client().modifyNetworkInterfaceAttribute(
|
||||
request -> request.networkInterfaceId(fixture.eni()).attachment(NetworkInterfaceAttachmentChanges
|
||||
.builder().attachmentId("eni-attach-00000000000000000").deleteOnTermination(true).build())));
|
||||
|
||||
assertEquals("InvalidAttachmentID.NotFound", error.awsErrorDetails().errorCode());
|
||||
assertFalse(networkInterface(fixture).attachment().deleteOnTermination());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownInterfaceIsNotFound() {
|
||||
Fixture fixture = fixture(false);
|
||||
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client().modifyNetworkInterfaceAttribute(
|
||||
request -> request.networkInterfaceId("eni-00000000000000000").groups(fixture.replacement())));
|
||||
|
||||
assertEquals("InvalidNetworkInterfaceID.NotFound", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -145,7 +305,7 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
client.detachNetworkInterface(request -> request.attachmentId(current.attachment().attachmentId()));
|
||||
}
|
||||
});
|
||||
return new Fixture(client, instance, eni, attachment, original, replacement);
|
||||
return new Fixture(client, instance, eni, attachment, original, replacement, primaryAtLaunch);
|
||||
}
|
||||
|
||||
private Ec2Client client(String account, Region region) {
|
||||
@@ -164,8 +324,17 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
.description("owned instance group synchronization fixture")).groupId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the fixture interface {@code group} the way AWS allows: through the instance while it is the instance's
|
||||
* only interface, through the interface itself once the instance has another.
|
||||
*/
|
||||
private static void replace(Fixture fixture, String group) {
|
||||
fixture.client().modifyInstanceAttribute(request -> request.instanceId(fixture.instance()).groups(group));
|
||||
if (fixture.primaryAtLaunch()) {
|
||||
fixture.client().modifyInstanceAttribute(request -> request.instanceId(fixture.instance()).groups(group));
|
||||
} else {
|
||||
fixture.client().modifyNetworkInterfaceAttribute(request -> request.networkInterfaceId(fixture.eni())
|
||||
.groups(group));
|
||||
}
|
||||
}
|
||||
|
||||
private static NetworkInterface networkInterface(Fixture fixture) {
|
||||
@@ -178,10 +347,15 @@ class Ec2InstanceGroupSynchronizationIntegrationTest {
|
||||
.reservations().getFirst().instances().getFirst();
|
||||
}
|
||||
|
||||
private static String primaryInterfaceId(Fixture fixture) {
|
||||
return instance(fixture).networkInterfaces().stream()
|
||||
.filter(eni -> eni.attachment().deviceIndex() == 0).findFirst().orElseThrow().networkInterfaceId();
|
||||
}
|
||||
|
||||
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) { }
|
||||
String original, String replacement, boolean primaryAtLaunch) { }
|
||||
}
|
||||
@@ -551,8 +551,7 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
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);
|
||||
Ec2Service service = service(factory, config, manager);
|
||||
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();
|
||||
@@ -562,12 +561,7 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
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);
|
||||
enableEnforcement(config);
|
||||
CountDownLatch applied = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<Set<String>> firewall = new AtomicReference<>();
|
||||
@@ -620,8 +614,7 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
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);
|
||||
Ec2Service service = service(factory, config, manager);
|
||||
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();
|
||||
@@ -631,12 +624,7 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
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);
|
||||
enableEnforcement(config);
|
||||
CountDownLatch updating = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
IllegalStateException failure = new IllegalStateException("Owned firewall failure");
|
||||
@@ -668,13 +656,109 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
}
|
||||
}
|
||||
|
||||
// Catches: ModifyNetworkInterfaceAttribute storing new groups without telling the interface's firewall, or
|
||||
// telling it only after they are stored, so the enforced policy and the reported groups disagree.
|
||||
@Test
|
||||
void interfaceGroupChangeReachesTheFirewallBeforeItIsStored() {
|
||||
TestStores factory = new TestStores();
|
||||
EmulatorConfig config = mockConfig();
|
||||
Ec2ContainerManager manager = mock(Ec2ContainerManager.class);
|
||||
Ec2Service service = service(factory, config, manager);
|
||||
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, "eni-original", "original", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "eni-replacement", "replacement", 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();
|
||||
String eni = instance.getNetworkInterfaces().getFirst().getNetworkInterfaceId();
|
||||
enableEnforcement(config);
|
||||
AtomicReference<String> groupsWhenApplied = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
groupsWhenApplied.set(interfaceGroup(service, region, eni));
|
||||
return null;
|
||||
}).when(manager).updateSecurityGroups(eq(eni), eq(Set.of(replacement)), anyMap(), anyMap());
|
||||
|
||||
service.modifyNetworkInterfaceAttribute(region, eni,
|
||||
new Ec2Service.NetworkInterfaceAttributeChange(List.of(replacement), null, null, null, null), false);
|
||||
|
||||
assertEquals(original, groupsWhenApplied.get(), "the firewall must hear of the change before it is stored");
|
||||
assertEquals(replacement, interfaceGroup(service, region, eni));
|
||||
}
|
||||
|
||||
// Catches: a firewall that refuses the change leaving the new groups stored, or their pending reference held,
|
||||
// so the replacement group can never be deleted.
|
||||
@Test
|
||||
void aFirewallFailureLeavesTheInterfaceGroupsAsTheyWere() {
|
||||
TestStores factory = new TestStores();
|
||||
EmulatorConfig config = mockConfig();
|
||||
Ec2ContainerManager manager = mock(Ec2ContainerManager.class);
|
||||
Ec2Service service = service(factory, config, manager);
|
||||
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, "eni-kept", "kept", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "eni-refused", "refused", 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();
|
||||
String eni = instance.getNetworkInterfaces().getFirst().getNetworkInterfaceId();
|
||||
enableEnforcement(config);
|
||||
IllegalStateException failure = new IllegalStateException("Owned firewall failure");
|
||||
doThrow(failure).when(manager).updateSecurityGroups(anyString(), anySet(), anyMap(), anyMap());
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class, () -> service.modifyNetworkInterfaceAttribute(
|
||||
region, eni, new Ec2Service.NetworkInterfaceAttributeChange(List.of(replacement), null, null, null,
|
||||
null), false)));
|
||||
|
||||
assertEquals(original, interfaceGroup(service, region, eni));
|
||||
service.deleteSecurityGroup(region, replacement);
|
||||
}
|
||||
|
||||
// Catches: a group change on an instance's primary interface leaving the ports those groups publish as they
|
||||
// were, where ModifyInstanceAttribute reconciles them; a secondary interface's groups publish nothing.
|
||||
@Test
|
||||
void onlyAPrimaryInterfaceGroupChangeReconcilesThePublishedPorts() {
|
||||
TestStores factory = new TestStores();
|
||||
EmulatorConfig config = mockConfig();
|
||||
Ec2PortForwardManager ports = mock(Ec2PortForwardManager.class);
|
||||
Ec2Service service = service(factory, config, mock(Ec2ContainerManager.class), ports);
|
||||
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, "ports-original", "original", vpc).getGroupId();
|
||||
String replacement = service.createSecurityGroup(region, "ports-replacement", "replacement", 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());
|
||||
instance.setDockerContainerId("container-ports");
|
||||
String primary = instance.getNetworkInterfaces().getFirst().getNetworkInterfaceId();
|
||||
String secondary = service.createNetworkInterface(region, subnet, null, null, List.of(), List.of(original),
|
||||
List.of()).getNetworkInterfaceId();
|
||||
service.attachNetworkInterface(region, secondary, instance.getInstanceId(), 1);
|
||||
when(config.services().ec2().mock()).thenReturn(false);
|
||||
when(config.services().ec2().publishSecurityGroupPorts()).thenReturn(true);
|
||||
|
||||
service.modifyNetworkInterfaceAttribute(region, secondary,
|
||||
new Ec2Service.NetworkInterfaceAttributeChange(List.of(replacement), null, null, null, null), false);
|
||||
verify(ports, never()).reconcile(any(), anySet());
|
||||
|
||||
service.modifyNetworkInterfaceAttribute(region, primary,
|
||||
new Ec2Service.NetworkInterfaceAttributeChange(List.of(replacement), null, null, null, null), false);
|
||||
verify(ports).reconcile(argThat(reconciled -> instance.getInstanceId().equals(reconciled.getInstanceId())),
|
||||
anySet());
|
||||
}
|
||||
|
||||
private static String interfaceGroup(Ec2Service service, String region, String eni) {
|
||||
return service.describeNetworkInterfaces(region, List.of(eni), Map.of()).networkInterfaces().getFirst()
|
||||
.getGroups().getFirst().getGroupId();
|
||||
}
|
||||
|
||||
@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);
|
||||
Ec2Service service = service(factory, config, manager);
|
||||
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();
|
||||
@@ -683,12 +767,7 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
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);
|
||||
enableEnforcement(config);
|
||||
CountDownLatch firstEntered = new CountDownLatch(1);
|
||||
CountDownLatch secondEntered = new CountDownLatch(1);
|
||||
CountDownLatch firstRelease = new CountDownLatch(1);
|
||||
@@ -880,10 +959,28 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
}
|
||||
|
||||
private static Ec2Service service(TestStores factory) {
|
||||
return new Ec2Service(mockConfig(), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
|
||||
return service(factory, mockConfig(), mock(Ec2ContainerManager.class));
|
||||
}
|
||||
|
||||
private static Ec2Service service(TestStores factory, EmulatorConfig config, Ec2ContainerManager manager) {
|
||||
return service(factory, config, manager, mock(Ec2PortForwardManager.class));
|
||||
}
|
||||
|
||||
private static Ec2Service service(TestStores factory, EmulatorConfig config, Ec2ContainerManager manager,
|
||||
Ec2PortForwardManager ports) {
|
||||
return new Ec2Service(config, manager, ports,
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), factory.storage);
|
||||
}
|
||||
|
||||
private static void enableEnforcement(EmulatorConfig config) {
|
||||
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);
|
||||
}
|
||||
|
||||
private static EmulatorConfig mockConfig() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
|
||||
Reference in new issue
Block a user