mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): select EC2 interface and endpoint authorization resources (#8892)
* fix(iam): select EC2 interface and endpoint authorization resources
This commit is contained in:
1 parent
c91740de85
commit
875794c538
11 files changed
+714
-18
No files matched your search
@@ -51,6 +51,22 @@ class RequestResourcesTest {
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void detachFindsBothAttachmentEndpointsAndKeepsTypedMissingFallbacks() {
|
||||
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
|
||||
StoredResourceArns stored = mock(StoredResourceArns.class);
|
||||
when(stored.findByMembers("instance", List.of("eni-attach-one"), "us-east-1"))
|
||||
.thenReturn(Optional.of(prefix + "instance/i-one"));
|
||||
when(stored.findByMembers("network-interface", List.of("eni-attach-one"), "us-east-1"))
|
||||
.thenReturn(Optional.of(prefix + "network-interface/eni-one"));
|
||||
assertEquals(List.of(prefix + "instance/i-one", prefix + "network-interface/eni-one"),
|
||||
of("ec2:DetachNetworkInterface", form("AttachmentId=eni-attach-one"), stored));
|
||||
List<String> missing = List.of(prefix + "instance/*", prefix + "network-interface/*");
|
||||
assertEquals(missing, of("ec2:DetachNetworkInterface", form("AttachmentId=eni-attach-missing"), stored));
|
||||
assertEquals(missing, of("ec2:DetachNetworkInterface", form("AttachmentId=eni-attach-one")));
|
||||
assertEquals(missing, of("ec2:DetachNetworkInterface", json("{\"AttachmentId\":\"eni-attach-missing\"}"), stored));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2ListsUseSdkWireNamesAndIgnoreForgedQuerySpellings() {
|
||||
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
|
||||
@@ -64,6 +80,39 @@ class RequestResourcesTest {
|
||||
""")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcEndpointModificationChecksAddedAndRemovedResources() {
|
||||
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
|
||||
List<String> expected = List.of(prefix + "route-table/rtb-add", prefix + "security-group/sg-add",
|
||||
prefix + "subnet/subnet-add", prefix + "vpc-endpoint/vpce-one",
|
||||
prefix + "route-table/rtb-remove", prefix + "security-group/sg-remove",
|
||||
prefix + "subnet/subnet-remove");
|
||||
assertEquals(expected, of("ec2:ModifyVpcEndpoint", form("VpcEndpointId=vpce-one"
|
||||
+ "&AddRouteTableId.1=rtb-add&RemoveRouteTableId.1=rtb-remove"
|
||||
+ "&AddSecurityGroupId.1=sg-add&RemoveSecurityGroupId.1=sg-remove"
|
||||
+ "&AddSubnetId.1=subnet-add&RemoveSubnetId.1=subnet-remove")));
|
||||
assertEquals(expected, of("ec2:ModifyVpcEndpoint", json("""
|
||||
{"VpcEndpointId":"vpce-one","AddRouteTableIds":["rtb-add"],
|
||||
"RemoveRouteTableIds":["rtb-remove"],"AddSecurityGroupIds":["sg-add"],
|
||||
"RemoveSecurityGroupIds":["sg-remove"],"AddSubnetIds":["subnet-add"],
|
||||
"RemoveSubnetIds":["subnet-remove"]}
|
||||
""")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void transitGatewayModificationChecksRemovedSubnetsWithItsDistinctWireSpelling() {
|
||||
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
|
||||
List<String> expected = List.of(prefix + "subnet/subnet-add",
|
||||
prefix + "transit-gateway-attachment/tgw-attach-one", prefix + "subnet/subnet-remove");
|
||||
assertEquals(expected, of("ec2:ModifyTransitGatewayVpcAttachment", form(
|
||||
"TransitGatewayAttachmentId=tgw-attach-one&AddSubnetIds.1=subnet-add"
|
||||
+ "&RemoveSubnetIds.1=subnet-remove&RemoveSubnetId.1=subnet-forged")));
|
||||
assertEquals(expected, of("ec2:ModifyTransitGatewayVpcAttachment", json("""
|
||||
{"TransitGatewayAttachmentId":"tgw-attach-one","AddSubnetIds":["subnet-add"],
|
||||
"RemoveSubnetIds":["subnet-remove"]}
|
||||
""")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createVpcChecksItsNewArnAndOnlyThePoolsPresentInTheRequest() {
|
||||
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
|
||||
@@ -162,6 +211,35 @@ class RequestResourcesTest {
|
||||
assertEquals(List.of(arn), of("signer:TagResource", request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointTagTargetsRetainTheCallerPartitionAndEachResource() throws Exception {
|
||||
for (String operation : List.of("ec2:CreateTags", "ec2:DeleteTags")) {
|
||||
List<String> expected = List.of(
|
||||
"arn:aws-us-gov:ec2:us-gov-west-1:111111111111:network-interface/eni-11111111",
|
||||
"*");
|
||||
assertEquals(expected, RequestResources.ofBody(operation,
|
||||
new ObjectMapper().readTree("{\"Resources\":[\"eni-11111111\",\"vpce-22222222\"]}"),
|
||||
"aws-us-gov", "us-gov-west-1", "111111111111", null));
|
||||
assertEquals(expected, RequestResources.of(operation,
|
||||
form("ResourceId.1=eni-11111111&ResourceId.2=vpce-22222222"),
|
||||
"aws-us-gov", "us-gov-west-1", "111111111111", null));
|
||||
assertEquals(List.of("*", "*"), of(operation,
|
||||
form("ResourceId.1=vpce-svc-22222222&ResourceId.2=eni-attach-11111111")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointDeletionReadsDistinctEndpointsUsingItsActualQueryListName() throws Exception {
|
||||
List<String> expected = List.of(
|
||||
"arn:aws:ec2:us-east-1:000000000000:vpc-endpoint/vpce-11111111",
|
||||
"arn:aws:ec2:us-east-1:000000000000:vpc-endpoint/vpce-22222222");
|
||||
assertEquals(expected, of("ec2:DeleteVpcEndpoints", form("VpcEndpointId.1=vpce-11111111"
|
||||
+ "&VpcEndpointId.2=vpce-22222222&VpcEndpointId.3=vpce-11111111&ResourceId.1=vpce-33333333")));
|
||||
assertEquals(expected, RequestResources.ofBody("ec2:DeleteVpcEndpoints", new ObjectMapper().readTree(
|
||||
"{\"VpcEndpointIds\":[\"vpce-11111111\",\"vpce-22222222\",\"vpce-11111111\"]}"),
|
||||
"aws", "us-east-1", "000000000000", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedIdTargetsReadModelListsAndSerializedQueryNamesInOrder() throws Exception {
|
||||
String instance = "arn:aws:ec2:us-east-1:000000000000:instance/i-one";
|
||||
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.iam.model.AccessKey;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.SignedIamEnforcementProfile;
|
||||
import io.floci.aws.testing.SignedIamUsers;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.Instance;
|
||||
import software.amazon.awssdk.services.ec2.model.InstanceType;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
class Ec2DetachNetworkInterfaceIamIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"us-east-1", "us-gov-west-1", "cn-north-1"})
|
||||
void bothEndpointGrantsPermitDetach(String regionName) throws Exception {
|
||||
Region region = Region.of(regionName);
|
||||
try (Ec2Client admin = admin(region); Attachment fixture = attach(admin)) {
|
||||
String policy = policy("Allow", List.of(arn(region, "instance/" + fixture.instanceId()),
|
||||
arn(region, "network-interface/" + fixture.interfaceId())));
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "detach-", "detach", policy);
|
||||
Ec2Client caller = caller(user, region)) {
|
||||
assertTrue(caller.detachNetworkInterface(r -> r.attachmentId(fixture.attachmentId()))
|
||||
.sdkHttpResponse().isSuccessful());
|
||||
assertNull(admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(fixture.interfaceId()))
|
||||
.networkInterfaces().getFirst().attachment());
|
||||
assertTrue(instance(admin, fixture.instanceId()).networkInterfaces().stream()
|
||||
.noneMatch(eni -> fixture.interfaceId().equals(eni.networkInterfaceId())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"instance", "network-interface", "explicit-deny"})
|
||||
void missingEndpointGrantOrExplicitDenyPreservesAttachment(String grant) throws Exception {
|
||||
Region region = Region.US_EAST_1;
|
||||
try (Ec2Client admin = admin(region); Attachment fixture = attach(admin)) {
|
||||
String instanceArn = arn(region, "instance/" + fixture.instanceId());
|
||||
String interfaceArn = arn(region, "network-interface/" + fixture.interfaceId());
|
||||
String policy = "explicit-deny".equals(grant)
|
||||
? "{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ statement("Allow", List.of("*")) + ","
|
||||
+ statement("Deny", List.of(interfaceArn)) + "]}"
|
||||
: policy("Allow", List.of("instance".equals(grant) ? instanceArn : interfaceArn));
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "detach-deny-", "detach", policy);
|
||||
Ec2Client caller = caller(user, region)) {
|
||||
error(caller, fixture.attachmentId(), "UnauthorizedOperation", 403);
|
||||
fixture.assertAttached();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void typedWildcardFallbackPreservesMissingAttachmentError() throws Exception {
|
||||
Region region = Region.US_EAST_1;
|
||||
String policy = policy("Allow", List.of(arn(region, "instance/*"), arn(region, "network-interface/*")));
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "detach-missing-", "detach", policy);
|
||||
Ec2Client caller = caller(user, region)) {
|
||||
error(caller, "eni-attach-0123456789abcdef0", "InvalidAttachmentID.NotFound", 400);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignRegionAttachmentCannotSupplyLocalAuthorizationResources() throws Exception {
|
||||
try (Ec2Client remote = admin(Region.US_WEST_2); Attachment fixture = attach(remote)) {
|
||||
String remotePolicy = policy("Allow", List.of(arn(Region.US_WEST_2, "instance/" + fixture.instanceId()),
|
||||
arn(Region.US_WEST_2, "network-interface/" + fixture.interfaceId())));
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "detach-region-", "detach", remotePolicy);
|
||||
Ec2Client caller = caller(user, Region.US_EAST_1)) {
|
||||
error(caller, fixture.attachmentId(), "UnauthorizedOperation", 403);
|
||||
String local = policy("Allow", List.of(arn(Region.US_EAST_1, "instance/*"),
|
||||
arn(Region.US_EAST_1, "network-interface/*")));
|
||||
SignedIamUsers.iam(endpoint, "PutUserPolicy", Map.of("UserName", user.name(),
|
||||
"PolicyName", "detach", "PolicyDocument", local)).then().statusCode(200);
|
||||
error(caller, fixture.attachmentId(), "InvalidAttachmentID.NotFound", 400);
|
||||
fixture.assertAttached();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
IamService iam;
|
||||
|
||||
@Test
|
||||
void foreignAccountCannotResolveOrDetachTheOwnersAttachment() throws Exception {
|
||||
String foreign = "111122223333";
|
||||
String name = "detach-foreign-" + UUID.randomUUID();
|
||||
try (Ec2Client admin = admin(Region.US_EAST_1); Attachment fixture = attach(admin)) {
|
||||
RequestScopes.runAs(foreign, "us-east-1", () -> iam.createUser(name, "/"));
|
||||
try {
|
||||
String ownerPolicy = policy("Allow", List.of(arn(Region.US_EAST_1, "instance/" + fixture.instanceId()),
|
||||
arn(Region.US_EAST_1, "network-interface/" + fixture.interfaceId())));
|
||||
RequestScopes.runAs(foreign, "us-east-1", () -> iam.putUserPolicy(name, "detach", ownerPolicy));
|
||||
AccessKey key = RequestScopes.callAs(foreign, "us-east-1", () -> iam.createAccessKey(name));
|
||||
try (Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), key.getAccessKeyId(),
|
||||
key.getSecretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
error(caller, fixture.attachmentId(), "UnauthorizedOperation", 403);
|
||||
fixture.assertAttached();
|
||||
String localPolicy = policy("Allow", List.of(
|
||||
AwsArnUtils.Arn.of("ec2", "us-east-1", foreign, "instance/*").toString(),
|
||||
AwsArnUtils.Arn.of("ec2", "us-east-1", foreign, "network-interface/*").toString()));
|
||||
RequestScopes.runAs(foreign, "us-east-1", () -> iam.putUserPolicy(name, "detach", localPolicy));
|
||||
error(caller, fixture.attachmentId(), "InvalidAttachmentID.NotFound", 400);
|
||||
fixture.assertAttached();
|
||||
}
|
||||
} finally {
|
||||
RequestScopes.runAs(foreign, "us-east-1", () -> {
|
||||
for (AccessKey key : iam.listAccessKeys(name)) {
|
||||
iam.deleteAccessKey(name, key.getAccessKeyId());
|
||||
}
|
||||
for (String policyName : iam.listUserPolicies(name)) {
|
||||
iam.deleteUserPolicy(name, policyName);
|
||||
}
|
||||
iam.deleteUser(name);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Attachment attach(Ec2Client admin) {
|
||||
String instanceId = admin.runInstances(r -> r.imageId("ami-1234567890abcdef0")
|
||||
.instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1)).instances().getFirst().instanceId();
|
||||
String interfaceId = null;
|
||||
try {
|
||||
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
|
||||
assertEquals("running", instance(admin, instanceId).state().nameAsString()));
|
||||
String subnet = instance(admin, instanceId).subnetId();
|
||||
interfaceId = admin.createNetworkInterface(r -> r.subnetId(subnet)).networkInterface().networkInterfaceId();
|
||||
String id = interfaceId;
|
||||
String attachmentId = admin.attachNetworkInterface(r -> r.networkInterfaceId(id)
|
||||
.instanceId(instanceId).deviceIndex(1)).attachmentId();
|
||||
return new Attachment(admin, instanceId, interfaceId, attachmentId);
|
||||
} catch (RuntimeException | AssertionError failure) {
|
||||
try {
|
||||
new Attachment(admin, instanceId, interfaceId, null).close();
|
||||
} catch (RuntimeException | AssertionError cleanup) {
|
||||
failure.addSuppressed(cleanup);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private record Attachment(Ec2Client admin, String instanceId, String interfaceId, String attachmentId)
|
||||
implements AutoCloseable {
|
||||
void assertAttached() {
|
||||
assertEquals(attachmentId, admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(interfaceId))
|
||||
.networkInterfaces().getFirst().attachment().attachmentId());
|
||||
assertTrue(instance(admin, instanceId).networkInterfaces().stream()
|
||||
.anyMatch(eni -> interfaceId.equals(eni.networkInterfaceId())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
admin.terminateInstances(r -> r.instanceIds(instanceId));
|
||||
if (interfaceId != null) {
|
||||
admin.deleteNetworkInterface(r -> r.networkInterfaceId(interfaceId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Ec2Client admin(Region region) {
|
||||
return AwsTestClients.create(Ec2Client.builder(), "test", region, endpoint);
|
||||
}
|
||||
|
||||
private Ec2Client caller(SignedIamUsers.User user, Region region) {
|
||||
return AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), user.secretAccessKey(), region, endpoint);
|
||||
}
|
||||
|
||||
private static Instance instance(Ec2Client client, String id) {
|
||||
return client.describeInstances(r -> r.instanceIds(id)).reservations().getFirst().instances().getFirst();
|
||||
}
|
||||
|
||||
private static void error(Ec2Client caller, String id, String code, int status) {
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> caller.detachNetworkInterface(r -> r.attachmentId(id)));
|
||||
assertEquals(status, error.statusCode());
|
||||
assertEquals(code, error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
private static String arn(Region region, String resource) {
|
||||
return AwsArnUtils.Arn.of("ec2", region.id(), "000000000000", resource).toString();
|
||||
}
|
||||
|
||||
private static String policy(String effect, List<String> resources) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[" + statement(effect, resources) + "]}";
|
||||
}
|
||||
|
||||
private static String statement(String effect, List<String> resources) {
|
||||
return "{\"Effect\":\"" + effect + "\",\"Action\":\"ec2:DetachNetworkInterface\",\"Resource\":[\""
|
||||
+ String.join("\",\"", resources) + "\"]}";
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.ListNetworksCmd;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsPartitions;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
@@ -135,6 +136,7 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -665,6 +667,59 @@ class Ec2ServiceTest {
|
||||
List.of(data), false, null, null);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"us-east-1", "us-gov-west-1", "cn-north-1"})
|
||||
void attachmentArnLookupStaysInTheCallerAccountAndRegion(String region) {
|
||||
String owner = "000000000000";
|
||||
String other = "111111111111";
|
||||
AccountAwareStorageBackend<NetworkInterface> interfaces = AccountAwareStorageBackend.inMemory(owner);
|
||||
Ec2Service service = spy(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", interfaces))));
|
||||
NetworkInterface eni = new NetworkInterface();
|
||||
eni.setNetworkInterfaceId("eni-11111111");
|
||||
eni.setOwnerId(owner);
|
||||
NetworkInterfaceAttachment attachment = new NetworkInterfaceAttachment();
|
||||
attachment.setAttachmentId("eni-attach-11111111");
|
||||
attachment.setInstanceId("i-11111111");
|
||||
eni.setAttachment(attachment);
|
||||
interfaces.putForAccount(owner, region + "::" + eni.getNetworkInterfaceId(), eni);
|
||||
Ec2StoredResourceArns stored = new Ec2StoredResourceArns(service);
|
||||
|
||||
assertEquals(attachmentArns(region, owner, "i-11111111", "eni-11111111"),
|
||||
service.networkInterfaceAttachmentArns(region, attachment.getAttachmentId()));
|
||||
assertEquals(Optional.of(attachmentArns(region, owner, "i-11111111", "eni-11111111").getFirst()),
|
||||
stored.findByMembers("instance", List.of(attachment.getAttachmentId()), region));
|
||||
assertEquals(Optional.of(attachmentArns(region, owner, "i-11111111", "eni-11111111").getLast()),
|
||||
stored.findByMembers("network-interface", List.of(attachment.getAttachmentId()), region));
|
||||
assertTrue(stored.findByMembers("instance", List.of("eni-attach-missing"), region).isEmpty());
|
||||
assertTrue(stored.findByMembers("instance", List.of(), region).isEmpty());
|
||||
assertSame(attachment, eni.getAttachment(), "authorization lookup must not detach the interface");
|
||||
assertEquals(List.of(),
|
||||
service.networkInterfaceAttachmentArns("eu-west-1", attachment.getAttachmentId()));
|
||||
assertEquals(List.of(),
|
||||
service.networkInterfaceAttachmentArns(region, "eni-attach-missing"));
|
||||
doReturn(other).when(service).callerAccountId();
|
||||
assertEquals(List.of(),
|
||||
service.networkInterfaceAttachmentArns(region, attachment.getAttachmentId()));
|
||||
assertTrue(stored.findByMembers("instance", List.of(attachment.getAttachmentId()), region).isEmpty());
|
||||
assertTrue(stored.findByMembers("network-interface", List.of(attachment.getAttachmentId()), region).isEmpty());
|
||||
assertTrue(stored.through("UnrelatedId", attachment.getAttachmentId(), region).isEmpty());
|
||||
assertTrue(service.networkInterfaceAttachmentArns(region, null).isEmpty());
|
||||
assertTrue(service.networkInterfaceAttachmentArns(region, " ").isEmpty());
|
||||
doReturn(owner).when(service).callerAccountId();
|
||||
eni.setAttachment(null);
|
||||
interfaces.putForAccount(owner, region + "::" + eni.getNetworkInterfaceId(), eni);
|
||||
assertEquals(List.of(),
|
||||
service.networkInterfaceAttachmentArns(region, attachment.getAttachmentId()));
|
||||
}
|
||||
|
||||
private static List<String> attachmentArns(String region, String account, String instance, String eni) {
|
||||
return List.of(AwsArnUtils.Arn.of("ec2", region, account, "instance/" + instance).toString(),
|
||||
AwsArnUtils.Arn.of("ec2", region, account, "network-interface/" + eni).toString());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"grant-before-detach", "detach-before-grant", "grant-before-describe"})
|
||||
void interfacePermissionOperationsShareAttachmentSynchronization(String order) throws Exception {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The resources network interface and VPC endpoint requests are checked on: the types AWS's Service
|
||||
* Authorization Reference gives each action, for the resources the request names. And what that
|
||||
* buys: Amazon OpenSearch Service's service-linked role policy, which scopes its EC2 grants to
|
||||
* resource ARNs, authorizes the calls the service makes in the customer's account with it, and still
|
||||
* refuses what lies outside its patterns.
|
||||
*/
|
||||
class Ec2NetworkInterfaceResourceArnTest {
|
||||
|
||||
private static final String CUSTOMER = "111111111111";
|
||||
private static final String PREFIX = "arn:aws:ec2:eu-west-1:" + CUSTOMER + ":";
|
||||
|
||||
private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
|
||||
|
||||
@Test
|
||||
void createNetworkInterfaceNamesTheInterfaceItsSubnetAndEachGroup() {
|
||||
assertResources(List.of(PREFIX + "network-interface/*", PREFIX + "subnet/subnet-11111111",
|
||||
PREFIX + "security-group/sg-11111111", PREFIX + "security-group/sg-22222222"),
|
||||
resources("CreateNetworkInterface", "SubnetId=subnet-11111111&SecurityGroupId.1=sg-11111111"
|
||||
+ "&SecurityGroupId.2=sg-22222222&Description=web"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void interfaceActionsNameTheInterface() {
|
||||
for (String operation : List.of("DeleteNetworkInterface", "CreateNetworkInterfacePermission")) {
|
||||
assertResources(List.of(PREFIX + "network-interface/eni-11111111"),
|
||||
resources(operation, "NetworkInterfaceId=eni-11111111&AwsAccountId=222222222222"
|
||||
+ "&Permission=INSTANCE-ATTACH"), operation);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachNamesTheInstanceAndTheInterface() {
|
||||
assertResources(List.of(PREFIX + "instance/i-11111111", PREFIX + "network-interface/eni-11111111"),
|
||||
resources("AttachNetworkInterface", "NetworkInterfaceId=eni-11111111&InstanceId=i-11111111"
|
||||
+ "&DeviceIndex=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAttachmentNoServiceResolvesIsCheckedOnTheAccountsInstancesAndInterfaces() {
|
||||
assertResources(List.of(PREFIX + "instance/*", PREFIX + "network-interface/*"),
|
||||
resources("DetachNetworkInterface", "AttachmentId=eni-attach-11111111&Force=true"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcEndpointActionsNameTheEndpointAndWhatItIsPlacedIn() {
|
||||
assertResources(List.of(PREFIX + "vpc-endpoint/*", PREFIX + "vpc/vpc-11111111", PREFIX + "subnet/subnet-11111111",
|
||||
PREFIX + "security-group/sg-11111111", PREFIX + "route-table/rtb-11111111"),
|
||||
resources("CreateVpcEndpoint", "VpcId=vpc-11111111&ServiceName=com.amazonaws.vpce.x"
|
||||
+ "&SubnetId.1=subnet-11111111&SecurityGroupId.1=sg-11111111&RouteTableId.1=rtb-11111111"));
|
||||
assertResources(List.of(PREFIX + "vpc-endpoint/vpce-11111111", PREFIX + "subnet/subnet-22222222",
|
||||
PREFIX + "security-group/sg-33333333"),
|
||||
resources("ModifyVpcEndpoint", "VpcEndpointId=vpce-11111111&AddSubnetId.1=subnet-22222222"
|
||||
+ "&RemoveSecurityGroupId.1=sg-33333333"));
|
||||
assertResources(List.of(PREFIX + "vpc-endpoint/vpce-11111111", PREFIX + "vpc-endpoint/vpce-22222222"),
|
||||
resources("DeleteVpcEndpoints", "VpcEndpointId.1=vpce-11111111&VpcEndpointId.2=vpce-22222222"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagRequestsNameKnownInterfacesAndLeaveUncoveredEndpointIdsOnTheWildcard() {
|
||||
assertResources(List.of(PREFIX + "network-interface/eni-11111111", "*"),
|
||||
resources("CreateTags", "ResourceId.1=eni-11111111&ResourceId.2=vpce-11111111"
|
||||
+ "&Tag.1.Key=Name&Tag.1.Value=web"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void actionsAwsChecksOnNoResourceTypeStayOnTheWildcard() {
|
||||
for (String operation : List.of("DescribeNetworkInterfaces", "DescribeNetworkInterfacePermissions")) {
|
||||
assertResources(List.of("*"), resources(operation, "NetworkInterfaceId.1=eni-11111111"
|
||||
+ "&NetworkInterfaceId=eni-11111111"), operation);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOpenSearchServiceLinkedRolePolicyAuthorizesTheServicesInterfaceCalls() {
|
||||
List<String> policy = List.of(openSearchRolePolicy());
|
||||
List<String> create = resources("CreateNetworkInterface",
|
||||
"SubnetId=subnet-11111111&SecurityGroupId.1=sg-11111111");
|
||||
for (String resource : create) {
|
||||
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
|
||||
evaluator.evaluate(policy, "ec2:CreateNetworkInterface", resource), resource);
|
||||
}
|
||||
for (String operation : List.of("DeleteNetworkInterface", "CreateTags")) {
|
||||
for (String resource : resources(operation, "NetworkInterfaceId=eni-11111111&ResourceId.1=eni-11111111")) {
|
||||
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
|
||||
evaluator.evaluate(policy, "ec2:" + operation, resource), operation + " " + resource);
|
||||
}
|
||||
}
|
||||
// Checked on the wildcard, as before, the same grant matches none of its patterns.
|
||||
assertEquals(IamPolicyEvaluator.Decision.DENY, evaluator.evaluate(policy, "ec2:CreateNetworkInterface", "*"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSamePolicyStillRefusesWhatLiesOutsideItsPatterns() {
|
||||
List<String> policy = List.of(openSearchRolePolicy());
|
||||
// CreateNetworkInterface is granted on interfaces, subnets and groups only.
|
||||
assertEquals(IamPolicyEvaluator.Decision.DENY,
|
||||
evaluator.evaluate(policy, "ec2:CreateNetworkInterface", PREFIX + "route-table/rtb-11111111"));
|
||||
// The policy grants no AttachNetworkInterface.
|
||||
for (String resource : resources("AttachNetworkInterface", "NetworkInterfaceId=eni-11111111&InstanceId=i-1")) {
|
||||
assertEquals(IamPolicyEvaluator.Decision.DENY,
|
||||
evaluator.evaluate(policy, "ec2:AttachNetworkInterface", resource), resource);
|
||||
}
|
||||
// Its CreateTags grant covers interfaces, and endpoints only while they are created.
|
||||
assertEquals(IamPolicyEvaluator.Decision.DENY,
|
||||
evaluator.evaluate(policy, "ec2:CreateTags", PREFIX + "instance/i-11111111"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEndpointItselfNeedsTheRequestTagThePolicyNames() {
|
||||
List<String> policy = List.of(openSearchRolePolicy());
|
||||
String endpoint = PREFIX + "vpc-endpoint/*";
|
||||
assertEquals(IamPolicyEvaluator.Decision.DENY,
|
||||
evaluator.simulateCustomPolicy(policy, "ec2:CreateVpcEndpoint", endpoint, Map.of()));
|
||||
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
|
||||
evaluator.simulateCustomPolicy(policy, "ec2:CreateVpcEndpoint", endpoint,
|
||||
Map.of("aws:RequestTag/OpenSearchManaged", List.of("true"))));
|
||||
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
|
||||
evaluator.evaluate(policy, "ec2:CreateVpcEndpoint", PREFIX + "subnet/subnet-11111111"));
|
||||
}
|
||||
|
||||
private static String openSearchRolePolicy() {
|
||||
return AwsManagedPolicies.POLICIES.stream()
|
||||
.filter(policy -> "AmazonOpenSearchServiceRolePolicy".equals(policy.name()))
|
||||
.findFirst()
|
||||
.orElseThrow()
|
||||
.document();
|
||||
}
|
||||
|
||||
private static void assertResources(List<String> expected, List<String> actual) {
|
||||
assertEquals(expected.stream().sorted().toList(), actual.stream().sorted().toList());
|
||||
}
|
||||
|
||||
private static void assertResources(List<String> expected, List<String> actual, String message) {
|
||||
assertEquals(expected.stream().sorted().toList(), actual.stream().sorted().toList(), message);
|
||||
}
|
||||
|
||||
private List<String> resources(String operation, String body) {
|
||||
ContainerRequestContext context = mock(ContainerRequestContext.class);
|
||||
UriInfo uri = mock(UriInfo.class);
|
||||
Map<String, Object> properties = new HashMap<>();
|
||||
when(context.getUriInfo()).thenReturn(uri);
|
||||
when(uri.getPath()).thenReturn("/");
|
||||
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(context.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
when(context.getEntityStream()).thenReturn(
|
||||
new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
|
||||
doAnswer(invocation -> {
|
||||
when(context.getEntityStream()).thenReturn(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(context).setEntityStream(any());
|
||||
when(context.getProperty(any())).thenAnswer(invocation -> properties.get(invocation.getArgument(0)));
|
||||
doAnswer(invocation -> {
|
||||
properties.put(invocation.getArgument(0), invocation.getArgument(1));
|
||||
return null;
|
||||
}).when(context).setProperty(any(), any());
|
||||
return new ResourceArnBuilder().buildResources("ec2", "ec2:" + operation, context,
|
||||
"eu-west-1", CUSTOMER, "aws");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user