diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 28c2b385c6..e750712d86 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1306,11 +1306,28 @@ profile. | UnassignIpv6Addresses | Removes the named IPv6 addresses (`Ipv6Addresses.N`) from an interface; `unassignedIpv6Addresses` lists only the ones it held. `Ipv6Prefix` answers `UnsupportedOperation`. | | 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. | +| CreateNetworkInterfacePermission | The interface's owner grants another account `INSTANCE-ATTACH` over it. `EIP-ASSOCIATE` and `AwsService` are `UnsupportedOperation`. | +| DescribeNetworkInterfacePermissions | The permissions granted over the caller's interfaces, by `NetworkInterfacePermissionId.N` and the five `network-interface-permission.*` filters; `MaxResults` 5-255, default 50. | 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`. 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. +#### Network interface permissions + +`CreateNetworkInterfacePermission` lets the account that owns an interface grant another account +`INSTANCE-ATTACH` over it, which `DescribeNetworkInterfacePermissions` lists to the owner. Only the +owner can grant: another account's interface is `InvalidNetworkInterfaceID.NotFound`, as it is to +every other action of that account. + +Floci accepts any ordinary 12-digit AWS account ID as an `INSTANCE-ATTACH` grantee. +This is a Floci compatibility choice: AWS requires an AWS-authorized grantee account, +so an ordinary account accepted here can be rejected by AWS with `OperationNotPermitted`. + +A repeated grant of the same permission to the same account answers the grant already in place. +AWS documents no duplicate error for it; this is Floci's choice. Grants are kept on the interface, +so they go when it is deleted. `DeleteNetworkInterfacePermission` is not served. + ### Volumes | Action | Description | diff --git a/docs/services/index.md b/docs/services/index.md index 2b194d5b55..50f455603b 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -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 | 231 | +| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 233 | | [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 (of 161 recognized; the rest answer `UnsupportedOperation`) | | [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 | diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index eeb5b0c687..0d567fb9ce 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -29,9 +29,11 @@ import java.util.function.Consumer; import static io.floci.aws.services.ec2.Ec2QueryProtocol.boolParam; import static io.floci.aws.services.ec2.Ec2QueryProtocol.booleanResponse; +import static io.floci.aws.services.ec2.Ec2QueryProtocol.endResponse; import static io.floci.aws.services.ec2.Ec2QueryProtocol.getFiltersList; import static io.floci.aws.services.ec2.Ec2QueryProtocol.getList; import static io.floci.aws.services.ec2.Ec2QueryProtocol.intParam; +import static io.floci.aws.services.ec2.Ec2QueryProtocol.startResponse; import static io.floci.aws.services.ec2.Ec2QueryProtocol.tagSetXml; import static io.floci.aws.services.ec2.Ec2QueryProtocol.xmlResponse; @@ -357,6 +359,9 @@ public class Ec2QueryHandler { case "ModifyNetworkInterfaceAttribute" -> handleModifyNetworkInterfaceAttribute(params, region); case "AssignIpv6Addresses" -> handleAssignIpv6Addresses(params, region); case "UnassignIpv6Addresses" -> handleUnassignIpv6Addresses(params, region); + case "CreateNetworkInterfacePermission" -> handleCreateNetworkInterfacePermission(params, region); + case "DescribeNetworkInterfacePermissions" -> + handleDescribeNetworkInterfacePermissions(params, region); // Volumes case "CreateVolume" -> handleCreateVolume(params, region); case "DescribeVolumes" -> handleDescribeVolumes(params, region); @@ -5669,6 +5674,41 @@ public class Ec2QueryHandler { return booleanResponse("ModifyNetworkInterfaceAttribute"); } + private Response handleCreateNetworkInterfacePermission(MultivaluedMap p, String region) { + checkDryRun(p); + NetworkInterfacePermission permission = service.createNetworkInterfacePermission(region, + p.getFirst("NetworkInterfaceId"), p.getFirst("AwsAccountId"), p.getFirst("AwsService"), + p.getFirst("Permission")); + XmlBuilder xml = startResponse("CreateNetworkInterfacePermission") + .start("interfacePermission").raw(networkInterfacePermissionXml(permission)).end("interfacePermission"); + return endResponse(xml, "CreateNetworkInterfacePermission"); + } + + private Response handleDescribeNetworkInterfacePermissions(MultivaluedMap p, String region) { + Ec2Service.NetworkInterfacePermissionPage page = service.describeNetworkInterfacePermissions(region, + getList(p, "NetworkInterfacePermissionId"), getFiltersList(p), + parseOptionalInt(p.getFirst("MaxResults"), "MaxResults"), p.getFirst("NextToken")); + XmlBuilder xml = startResponse("DescribeNetworkInterfacePermissions").start("networkInterfacePermissions"); + for (NetworkInterfacePermission permission : page.permissions()) { + xml.start("item").raw(networkInterfacePermissionXml(permission)).end("item"); + } + xml.end("networkInterfacePermissions"); + if (page.nextToken() != null) { + xml.elem("nextToken", page.nextToken()); + } + return endResponse(xml, "DescribeNetworkInterfacePermissions"); + } + + private static String networkInterfacePermissionXml(NetworkInterfacePermission permission) { + return new XmlBuilder() + .elem("networkInterfacePermissionId", permission.getNetworkInterfacePermissionId()) + .elem("networkInterfaceId", permission.getNetworkInterfaceId()) + .elem("awsAccountId", permission.getAwsAccountId()) + .elem("permission", permission.getPermission()) + .start("permissionState").elem("state", permission.getState()).end("permissionState") + .build(); + } + // ─── XML fragment builders ──────────────────────────────────────────────── private String instanceXml(Instance inst, Map capacityAssociations, diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index abb5ef2818..14f75f1408 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -66,6 +66,7 @@ import io.floci.aws.services.ec2.model.NetworkInterface; import io.floci.aws.services.ec2.model.NetworkInterfaceAssociation; import io.floci.aws.services.ec2.model.NetworkInterfaceAttachment; import io.floci.aws.services.ec2.model.NetworkInterfaceListResult; +import io.floci.aws.services.ec2.model.NetworkInterfacePermission; import io.floci.aws.services.ec2.model.NetworkInterfacePrivateIpAddress; import io.floci.aws.services.ec2.model.Placement; import io.floci.aws.services.ec2.model.PrefixList; @@ -17351,6 +17352,172 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return detached; } + // ─── Network interface permissions ─────────────────────────────────────────────── + + /** The permission that lets another account attach an interface to an instance of its own. */ + public static final String INSTANCE_ATTACH = "INSTANCE-ATTACH"; + private static final String EIP_ASSOCIATE = "EIP-ASSOCIATE"; + /** {@code NetworkInterfacePermissionState.State} once a permission applies. */ + private static final String PERMISSION_GRANTED = "granted"; + private static final String NETWORK_INTERFACE_PERMISSION_ID_PREFIX = "eni-perm-"; + private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}"); + private static final Set NETWORK_INTERFACE_PERMISSION_FILTERS = Set.of( + "network-interface-permission.network-interface-permission-id", + "network-interface-permission.network-interface-id", + "network-interface-permission.aws-account-id", + "network-interface-permission.aws-service", + "network-interface-permission.permission"); + + /** One page of DescribeNetworkInterfacePermissions. */ + public record NetworkInterfacePermissionPage(List permissions, String nextToken) {} + + /** + * CreateNetworkInterfacePermission: the interface's owner records an {@code INSTANCE-ATTACH} + * grant for another account. Attachment execution does not yet consume these grants. + * Only the owner can grant: the interface is looked up in the caller's account, and + * one another account owns is {@code InvalidNetworkInterfaceID.NotFound}, as it is to every + * other action of that account. + * + *

A second grant of the same permission to the same account answers the grant already in + * place rather than minting another: AWS documents no duplicate error for this action, and the + * permission either holds or it does not. {@code EIP-ASSOCIATE} is refused as unsupported, since + * nothing here would honour it, and so is {@code AwsService}, which AWS documents as "Currently + * not supported". + */ + public NetworkInterfacePermission createNetworkInterfacePermission(String region, String networkInterfaceId, + String awsAccountId, String awsService, + String permission) { + if (!isSet(networkInterfaceId)) { + throw new AwsException("MissingParameter", + "The request must contain the parameter NetworkInterfaceId", 400); + } + if (!isSet(permission)) { + throw new AwsException("MissingParameter", "The request must contain the parameter Permission", 400); + } + requireParameterValue("Permission", permission, INSTANCE_ATTACH, EIP_ASSOCIATE); + if (EIP_ASSOCIATE.equals(permission)) { + throw new AwsException("UnsupportedOperation", + "The EIP-ASSOCIATE network interface permission is not supported.", 400); + } + if (isSet(awsService)) { + throw new AwsException("UnsupportedOperation", + "Network interface permissions for an AwsService are not supported.", 400); + } + if (!isSet(awsAccountId)) { + throw new AwsException("MissingParameter", "The request must contain the parameter AwsAccountId", 400); + } + requireAccountId("AwsAccountId", awsAccountId); + ensureDefaultResources(region); + synchronized (attachmentTopologyLock(region)) { + synchronized (privateIpAllocationLock) { + NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId); + return grantInstanceAttach(callerAccountId(), region, ni, awsAccountId); + } + } + } + + /** + * DescribeNetworkInterfacePermissions: the permissions the caller has granted over the + * interfaces it owns in {@code region}, by id and by the five documented filters. MaxResults + * runs 5 to 255 and defaults to 50, as AWS documents. + */ + public NetworkInterfacePermissionPage describeNetworkInterfacePermissions( + String region, List permissionIds, List>> filters, + Integer maxResults, String nextToken) { + requireSupportedFilters(filterNames(filters), NETWORK_INTERFACE_PERMISSION_FILTERS); + if (maxResults != null && (maxResults < 5 || maxResults > 255)) { + throw new AwsException("InvalidParameterValue", + "Value (" + maxResults + ") for parameter MaxResults is invalid. " + + "Expecting a value between 5 and 255.", 400); + } + for (String id : permissionIds) { + if (!id.startsWith(NETWORK_INTERFACE_PERMISSION_ID_PREFIX)) { + throw new AwsException("InvalidNetworkInterfacePermissionID.Malformed", + "Invalid id: \"" + id + "\" (expecting \"" + NETWORK_INTERFACE_PERMISSION_ID_PREFIX + "...\")", + 400); + } + } + ensureDefaultResources(region); + List held = new ArrayList<>(); + synchronized (attachmentTopologyLock(region)) { + for (NetworkInterface ni : networkInterfaces.scan(k -> k.startsWith(region + "::"))) { + held.addAll(ni.getPermissions()); + } + } + for (String id : permissionIds) { + if (held.stream().noneMatch(perm -> id.equals(perm.getNetworkInterfacePermissionId()))) { + throw new AwsException("InvalidNetworkInterfacePermissionID.NotFound", + "The NetworkInterfacePermission ID '" + id + "' does not exist", 400); + } + } + List matching = held.stream() + .filter(perm -> permissionIds.isEmpty() || permissionIds.contains(perm.getNetworkInterfacePermissionId())) + .filter(perm -> matchesPermissionFilters(perm, filters)) + .toList(); + int offset = decodeToken(nextToken); + int pageSize = maxResults != null ? maxResults : 50; + int end = Math.min(offset + pageSize, matching.size()); + List page = offset < matching.size() + ? new ArrayList<>(matching.subList(offset, end)) : new ArrayList<>(); + return new NetworkInterfacePermissionPage(page, end < matching.size() ? encodeToken(end) : null); + } + + private boolean matchesPermissionFilters(NetworkInterfacePermission perm, + List>> filters) { + for (Map.Entry> filter : filters == null ? List.>>of() : filters) { + List values = filter.getValue(); + boolean matches = switch (filter.getKey()) { + case "network-interface-permission.network-interface-permission-id" -> + matchesValue(values, perm.getNetworkInterfacePermissionId()); + case "network-interface-permission.network-interface-id" -> + matchesValue(values, perm.getNetworkInterfaceId()); + case "network-interface-permission.aws-account-id" -> matchesValue(values, perm.getAwsAccountId()); + // No permission here is granted to a service, so none carries one to match. + case "network-interface-permission.aws-service" -> false; + case "network-interface-permission.permission" -> matchesValue(values, perm.getPermission()); + default -> true; + }; + if (!matches) { + return false; + } + } + return true; + } + + /** The grant of {@code INSTANCE-ATTACH} to {@code grantee}, minted unless one is already in place. */ + private NetworkInterfacePermission grantInstanceAttach(String ownerAccountId, String region, NetworkInterface ni, + String grantee) { + Optional existing = ni.getPermissions().stream() + .filter(perm -> grantee.equals(perm.getAwsAccountId()) && INSTANCE_ATTACH.equals(perm.getPermission())) + .findFirst(); + if (existing.isPresent()) { + return existing.get(); + } + NetworkInterfacePermission granted = new NetworkInterfacePermission( + NETWORK_INTERFACE_PERMISSION_ID_PREFIX + randomHex(17), ni.getNetworkInterfaceId(), grantee, + INSTANCE_ATTACH, PERMISSION_GRANTED); + ni.getPermissions().add(granted); + putNetworkInterface(ownerAccountId, region, ni); + return granted; + } + + private static void requireAccountId(String parameter, String value) { + if (!ACCOUNT_ID.matcher(value).matches()) { + throw new AwsException("InvalidParameterValue", + "Value (" + value + ") for parameter " + parameter + " is invalid. " + + "Expecting a 12-digit AWS account ID.", 400); + } + } + + /** Stores an interface in its owner's partition, whichever account is calling. */ + private void putNetworkInterface(String accountId, String region, NetworkInterface ni) { + if (networkInterfaces instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(accountId, key(region, ni.getNetworkInterfaceId()), ni); + } else { + networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni); + } + } + /** Removes an interface from an instance's own list, the mirror of attaching it. */ private void detachFromInstance(String region, String instanceId, String networkInterfaceId) { detachFromInstance(callerAccountId(), region, instanceId, networkInterfaceId); diff --git a/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java b/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java index 483cf8f9ea..a7828ec6d9 100644 --- a/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java +++ b/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java @@ -40,6 +40,8 @@ public class NetworkInterface { private List tagSet = new ArrayList<>(); private List privateIpAddresses = new ArrayList<>(); private List ipv6Addresses = new ArrayList<>(); + /** The permissions this interface's owner has granted other accounts over it. */ + private List permissions = new ArrayList<>(); public NetworkInterface() {} @@ -98,4 +100,7 @@ public class NetworkInterface { public List getIpv6Addresses() { return ipv6Addresses; } public void setIpv6Addresses(List ipv6Addresses) { this.ipv6Addresses = ipv6Addresses; } public void setPrivateIpAddresses(List privateIpAddresses) { this.privateIpAddresses = privateIpAddresses; } + + public List getPermissions() { return permissions; } + public void setPermissions(List permissions) { this.permissions = permissions; } } diff --git a/src/main/java/io/floci/aws/services/ec2/model/NetworkInterfacePermission.java b/src/main/java/io/floci/aws/services/ec2/model/NetworkInterfacePermission.java new file mode 100644 index 0000000000..ecd21c1ef6 --- /dev/null +++ b/src/main/java/io/floci/aws/services/ec2/model/NetworkInterfacePermission.java @@ -0,0 +1,50 @@ +package io.floci.aws.services.ec2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A permission the account that owns a network interface has granted another account over it + * ({@code NetworkInterfacePermission}). CreateNetworkInterfacePermission records an + * {@code INSTANCE-ATTACH} grant on the interface it is over. Attachment execution does not yet + * consume these grants. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class NetworkInterfacePermission { + + private String networkInterfacePermissionId; + private String networkInterfaceId; + private String awsAccountId; + private String permission; + private String state; + + public NetworkInterfacePermission() {} + + public NetworkInterfacePermission(String networkInterfacePermissionId, String networkInterfaceId, + String awsAccountId, String permission, String state) { + this.networkInterfacePermissionId = networkInterfacePermissionId; + this.networkInterfaceId = networkInterfaceId; + this.awsAccountId = awsAccountId; + this.permission = permission; + this.state = state; + } + + public String getNetworkInterfacePermissionId() { return networkInterfacePermissionId; } + public void setNetworkInterfacePermissionId(String networkInterfacePermissionId) { + this.networkInterfacePermissionId = networkInterfacePermissionId; + } + + public String getNetworkInterfaceId() { return networkInterfaceId; } + public void setNetworkInterfaceId(String networkInterfaceId) { this.networkInterfaceId = networkInterfaceId; } + + public String getAwsAccountId() { return awsAccountId; } + public void setAwsAccountId(String awsAccountId) { this.awsAccountId = awsAccountId; } + + public String getPermission() { return permission; } + public void setPermission(String permission) { this.permission = permission; } + + /** {@code PermissionState.State}: {@code granted} once it applies. */ + public String getState() { return state; } + public void setState(String state) { this.state = state; } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2NetworkInterfacePermissionIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2NetworkInterfacePermissionIntegrationTest.java new file mode 100644 index 0000000000..49c93d8c77 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2NetworkInterfacePermissionIntegrationTest.java @@ -0,0 +1,151 @@ +package io.floci.aws.services.ec2; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.floci.aws.testing.Ec2Requests.ec2; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Network interface permissions: the public CreateNetworkInterfacePermission an interface's owner + * calls, and DescribeNetworkInterfacePermissions, which lists them to the owner. + * + *

Twelve-digit access key ids resolve to distinct accounts, as in the other cross-account tests. + */ +@QuarkusTest +class Ec2NetworkInterfacePermissionIntegrationTest { + + private static final String OWNER = "000000003511"; + private static final String GRANTEE = "000000003512"; + private static final String SERVICE = "000000003513"; + private static final String OTHER = "000000003514"; + + /** + * The owner's interface, created on first use: QuarkusTest points RestAssured at the application + * only for a test method, so a {@code @BeforeAll} could not reach it. + */ + private static String eniId; + + private static String eni() { + if (eniId == null) { + eniId = createTheOwnersInterface(); + } + return eniId; + } + + private static String createTheOwnersInterface() { + String vpcId = ec2("DescribeVpcs", OWNER, "us-east-1") + .formParam("Filter.1.Name", "is-default").formParam("Filter.1.Value.1", "true") + .when().post("/") + .then().statusCode(200) + .extract().path("DescribeVpcsResponse.vpcSet.item[0].vpcId"); + String subnetId = ec2("DescribeSubnets", OWNER, "us-east-1") + .formParam("Filter.1.Name", "vpc-id").formParam("Filter.1.Value.1", vpcId) + .when().post("/") + .then().statusCode(200) + .extract().path("DescribeSubnetsResponse.subnetSet.item[0].subnetId"); + return ec2("CreateNetworkInterface", OWNER, "us-east-1") + .formParam("SubnetId", subnetId) + .formParam("Description", "ES permissions-domain") + .when().post("/") + .then().statusCode(200) + .extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId"); + } + + @Test + void theOwnerGrantsAnotherAccountInstanceAttachAndSeesIt() { + ec2("CreateNetworkInterfacePermission", OWNER, "us-east-1") + .formParam("NetworkInterfaceId", eni()) + .formParam("AwsAccountId", GRANTEE) + .formParam("Permission", "INSTANCE-ATTACH") + .when().post("/") + .then().statusCode(200) + .body("CreateNetworkInterfacePermissionResponse.interfacePermission.awsAccountId", equalTo(GRANTEE)); + + ec2("DescribeNetworkInterfacePermissions", OWNER, "us-east-1") + .formParam("Filter.1.Name", "network-interface-permission.network-interface-id") + .formParam("Filter.1.Value.1", eni()) + .formParam("Filter.2.Name", "network-interface-permission.aws-account-id") + .formParam("Filter.2.Value.1", GRANTEE) + .when().post("/") + .then().statusCode(200) + .body("DescribeNetworkInterfacePermissionsResponse.networkInterfacePermissions.item.size()", equalTo(1)) + .body("DescribeNetworkInterfacePermissionsResponse.networkInterfacePermissions.item" + + ".networkInterfacePermissionId", startsWith("eni-perm-")) + .body("DescribeNetworkInterfacePermissionsResponse.networkInterfacePermissions.item.permission", + equalTo("INSTANCE-ATTACH")) + .body("DescribeNetworkInterfacePermissionsResponse.networkInterfacePermissions.item" + + ".permissionState.state", equalTo("granted")); + } + + @Test + void theOwnerGrantsAPermissionOnceAndOnlyTheOwnerCan() { + String first = ec2("CreateNetworkInterfacePermission", OWNER, "us-east-1") + .formParam("NetworkInterfaceId", eni()) + .formParam("AwsAccountId", SERVICE) + .formParam("Permission", "INSTANCE-ATTACH") + .when().post("/") + .then().statusCode(200) + .body("CreateNetworkInterfacePermissionResponse.interfacePermission.networkInterfaceId", + equalTo(eni())) + .body("CreateNetworkInterfacePermissionResponse.interfacePermission.awsAccountId", equalTo(SERVICE)) + .body("CreateNetworkInterfacePermissionResponse.interfacePermission.permissionState.state", + equalTo("granted")) + .extract().path("CreateNetworkInterfacePermissionResponse.interfacePermission" + + ".networkInterfacePermissionId"); + String again = ec2("CreateNetworkInterfacePermission", OWNER, "us-east-1") + .formParam("NetworkInterfaceId", eni()) + .formParam("AwsAccountId", SERVICE) + .formParam("Permission", "INSTANCE-ATTACH") + .when().post("/") + .then().statusCode(200) + .extract().path("CreateNetworkInterfacePermissionResponse.interfacePermission" + + ".networkInterfacePermissionId"); + assertEquals(first, again); + + ec2("DescribeNetworkInterfacePermissions", OWNER, "us-east-1") + .formParam("NetworkInterfacePermissionId.1", first) + .when().post("/") + .then().statusCode(200) + .body("DescribeNetworkInterfacePermissionsResponse.networkInterfacePermissions.item.awsAccountId", + equalTo(SERVICE)); + + ec2("CreateNetworkInterfacePermission", GRANTEE, "us-east-1") + .formParam("NetworkInterfaceId", eni()) + .formParam("AwsAccountId", OTHER) + .formParam("Permission", "INSTANCE-ATTACH") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound")); + } + + @Test + void aPermissionRequestOutsideTheModelIsRefused() { + ec2("CreateNetworkInterfacePermission", OWNER, "us-east-1") + .formParam("NetworkInterfaceId", eni()) + .formParam("AwsAccountId", GRANTEE) + .formParam("Permission", "INSTANCE-DETACH") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")); + ec2("CreateNetworkInterfacePermission", OWNER, "us-east-1") + .formParam("NetworkInterfaceId", eni()) + .formParam("AwsAccountId", GRANTEE) + .formParam("Permission", "EIP-ASSOCIATE") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("UnsupportedOperation")); + ec2("DescribeNetworkInterfacePermissions", OWNER, "us-east-1") + .formParam("NetworkInterfacePermissionId.1", "eni-perm-0123456789abcdef0") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfacePermissionID.NotFound")); + ec2("DescribeNetworkInterfacePermissions", OWNER, "us-east-1") + .formParam("NetworkInterfacePermissionId.1", "perm-0123") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfacePermissionID.Malformed")); + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java index 750d8c6fa3..c212c210f5 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java @@ -34,6 +34,7 @@ import io.floci.aws.services.ec2.model.NatGatewayAddress; import io.floci.aws.services.ec2.model.NetworkAcl; import io.floci.aws.services.ec2.model.NetworkInterface; import io.floci.aws.services.ec2.model.NetworkInterfaceAssociation; +import io.floci.aws.services.ec2.model.NetworkInterfaceAttachment; import io.floci.aws.services.ec2.model.NetworkInterfaceListResult; import io.floci.aws.services.ec2.model.NetworkInterfacePrivateIpAddress; import io.floci.aws.services.ec2.model.Placement; @@ -125,6 +126,7 @@ import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.ED25519_KEY; import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.RSA_FINGERPRINT; import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.RSA_KEY; import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.TRUNCATED_RSA_KEY; +import static io.floci.aws.testing.ParkingStoreAssertions.assertOperationWaitsForParkedStore; import static io.floci.aws.testing.ThreadStates.awaitBlockedOrDone; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -663,6 +665,48 @@ class Ec2ServiceTest { List.of(data), false, null, null); } + @ParameterizedTest + @ValueSource(strings = {"grant-before-detach", "detach-before-grant", "grant-before-describe"}) + void interfacePermissionOperationsShareAttachmentSynchronization(String order) throws Exception { + String region = "us-east-1"; + ParkingStore interfaces = new ParkingStore<>(); + AccountAwareStorageBackend interfaceStore = + new AccountAwareStorageBackend<>(interfaces, null, "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-network-interfaces.json", interfaceStore))); + String subnet = publicSubnet(service, region, "10.243.0.0/24"); + NetworkInterface eni = service.createNetworkInterface(region, subnet, null, "10.243.0.10", + List.of(), List.of(), List.of()); + Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro", + 1, 1, null, List.of(), subnet, null, List.of(), null, null, null).getInstances().getFirst(); + instance.setState(InstanceState.running()); + NetworkInterfaceAttachment attachment = service.attachNetworkInterface(region, + eni.getNetworkInterfaceId(), instance.getInstanceId(), 1); + Runnable grant = () -> service.createNetworkInterfacePermission(region, eni.getNetworkInterfaceId(), + "111111111111", null, Ec2Service.INSTANCE_ATTACH); + Runnable detach = () -> service.detachNetworkInterface(region, attachment.getAttachmentId(), false); + Runnable describe = () -> assertEquals(1, service.describeNetworkInterfacePermissions( + region, List.of(), List.of(), null, null).permissions().size()); + interfaces.parkNextWrite(); + + switch (order) { + case "grant-before-detach" -> assertOperationWaitsForParkedStore(interfaces, grant, detach); + case "detach-before-grant" -> assertOperationWaitsForParkedStore(interfaces, detach, grant); + case "grant-before-describe" -> assertOperationWaitsForParkedStore(interfaces, grant, describe); + default -> throw new IllegalArgumentException(order); + } + + assertEquals(1, service.describeNetworkInterfacePermissions( + region, List.of(), List.of(), null, null).permissions().size()); + if (!"grant-before-describe".equals(order)) { + assertNull(eni.getAttachment()); + assertTrue(instance.getNetworkInterfaces().stream() + .noneMatch(value -> eni.getNetworkInterfaceId().equals(value.getNetworkInterfaceId()))); + } + } + @Test void subnetAvailableAddressesTrackAllocationsAndRelease() { AccountAwareStorageBackend interfaceStore =