fix(iam): resolve EC2 network resources and ownership tags (#8288)

EC2 network operations with resource-scoped policies were checked against
`*`, and stored ownership conditions were missing. Every EC2 request is
now read by the generated request-resource rules, its EC2 Query list
names from botocore, so a resource-scoped policy applies to each EC2
operation whose request names a resource. A list a type's ARN variable
names is the request's targets only when the request names nothing
else, and the sg-, acl-, rtb- and eni- id prefixes come from botocore's
examples.

Each target is evaluated with its own stored tags, under every EC2
type's Service Reference resource-tag keys, and tags on creation are
authorized separately. A forged SDK spelling cannot replace an EC2 wire
value. ENI creation tags are kept in the regional tag index and stay in
sync with CreateTags and DeleteTags.

Closes #8286
Closes #8287
Closes #8291
Closes #8295
Closes #8300
Closes #8306
This commit is contained in:
luiseterc authored and GitHub committed 2026-11-14 13:38:41 -04:00
1 parent 4649d6c683
commit a138f88094
20 files changed
+2163 -587

No files matched your search

@@ -0,0 +1,150 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Address;
import software.amazon.awssdk.services.ec2.model.AssociateAddressRequest;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2AddressIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@ValueSource(strings = {"instance", "network-interface"})
void associationRequiresEveryRequestedTargetWithItsOwnStoredTags(String kind) {
String user = "address-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.211.0.0/16")).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.211.1.0/24")).subnet().subnetId();
String target;
if ("instance".equals(kind)) {
target = admin.runInstances(r -> r.imageId("ami-amazonlinux2023").instanceType("t3.micro")
.minCount(1).maxCount(1).subnetId(subnet).tagSpecifications(tags(kind, "foreign")))
.instances().getFirst().instanceId();
} else {
target = admin.createNetworkInterface(r -> r.subnetId(subnet).tagSpecifications(tags(kind, "foreign")))
.networkInterface().networkInterfaceId();
}
String allocation = admin.allocateAddress(r -> r.domain("vpc")
.tagSpecifications(tags("elastic-ip", "address"))).allocationId();
String addressGrant = grant("AssociateAddress", "elastic-ip/" + allocation, "address");
String targetGrant = grant("AssociateAddress", kind + "/" + target, "target");
AssociateAddressRequest.Builder builder = AssociateAddressRequest.builder().allocationId(allocation);
if ("instance".equals(kind)) {
builder.instanceId(target);
} else {
builder.networkInterfaceId(target);
}
AssociateAddressRequest request = builder.build();
try {
policy(user, addressGrant + "," + targetGrant);
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
assertNull(admin.describeAddresses(r -> r.allocationIds(allocation)).addresses().getFirst().associationId());
admin.createTags(r -> r.resources(target).tags(t -> t.key("Owner").value("target")));
policy(user, addressGrant);
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
policy(user, targetGrant);
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
policy(user, addressGrant + "," + targetGrant + "," + targetGrant.replace("Allow", "Deny"));
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
policy(user, addressGrant + "," + targetGrant + "," + addressGrant.replace("Allow", "Deny"));
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
policy(user, addressGrant + "," + targetGrant);
String association = client.associateAddress(request).associationId();
Address result = admin.describeAddresses(r -> r.allocationIds(allocation)).addresses().getFirst();
assertEquals(association, result.associationId());
assertEquals(target, "instance".equals(kind) ? result.instanceId() : result.networkInterfaceId());
} finally {
Address address = admin.describeAddresses(r -> r.allocationIds(allocation)).addresses().getFirst();
if (address.associationId() != null) {
admin.disassociateAddress(r -> r.associationId(address.associationId()));
}
admin.releaseAddress(r -> r.allocationId(allocation));
if ("instance".equals(kind)) {
admin.terminateInstances(r -> r.instanceIds(target));
}
admin.describeNetworkInterfaces().networkInterfaces().stream().filter(n -> vpc.equals(n.vpcId()))
.forEach(n -> admin.deleteNetworkInterface(r -> r.networkInterfaceId(n.networkInterfaceId())));
admin.deleteSubnet(r -> r.subnetId(subnet));
admin.deleteVpc(r -> r.vpcId(vpc));
}
}
}
@Test
void releaseRequiresTheNamedAllocationsStoredOwnershipAndHonorsExplicitDeny() {
String user = "release-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String allocation = admin.allocateAddress(r -> r.domain("vpc")
.tagSpecifications(tags("elastic-ip", "foreign"))).allocationId();
String grant = grant("ReleaseAddress", "elastic-ip/" + allocation, "address");
try {
policy(user, grant);
assertAwsError("UnauthorizedOperation", 403,
() -> client.releaseAddress(r -> r.allocationId(allocation)));
admin.createTags(r -> r.resources(allocation).tags(t -> t.key("Owner").value("address")));
policy(user, grant + "," + grant.replace("Allow", "Deny"));
assertAwsError("UnauthorizedOperation", 403,
() -> client.releaseAddress(r -> r.allocationId(allocation)));
policy(user, grant.replace(allocation, "eipalloc-other"));
assertAwsError("UnauthorizedOperation", 403,
() -> client.releaseAddress(r -> r.allocationId(allocation)));
policy(user, grant);
client.releaseAddress(r -> r.allocationId(allocation));
} finally {
if (admin.describeAddresses().addresses().stream().anyMatch(a -> allocation.equals(a.allocationId()))) {
admin.releaseAddress(r -> r.allocationId(allocation));
}
}
}
}
private void policy(String user, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
"address", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
private static String grant(String action, String resource, String owner) {
return """
{"Effect":"Allow","Action":"ec2:%s","Resource":"arn:aws:ec2:us-east-1:000000000000:%s",
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"%s"}}}
""".formatted(action, resource, owner);
}
private static TagSpecification tags(String type, String owner) {
return TagSpecification.builder().resourceType(type).tags(t -> t.key("Owner").value(owner)).build();
}
}
@@ -0,0 +1,132 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.CreateVpcRequest;
import software.amazon.awssdk.services.ec2.model.ResourceType;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2CreateVpcIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@ValueSource(strings = {"us-east-1", "us-gov-west-1", "cn-north-1"})
void scopedCreateRequiresRequestTagsAndTagPermissionAndHonorsExplicitDeny(String region) {
String name = "vpc-create-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), name);
String resource = AwsArnUtils.Arn.of("ec2", region, "000000000000", "vpc/*").toString();
String create = """
{"Effect":"Allow","Action":"ec2:CreateVpc","Resource":"%s",
"Condition":{"StringEquals":{"aws:RequestTag/ManagedBy":"integration-test"}}}
""".formatted(resource);
String tag = """
{"Effect":"Allow","Action":"ec2:CreateTags","Resource":"%s",
"Condition":{"StringEquals":{"ec2:CreateAction":"CreateVpc"}}}
""".formatted(resource);
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.of(region), endpoint);
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.of(region), endpoint)) {
CreateVpcRequest request = tagged("integration-test");
policy(name, create);
denied(client, request);
policy(name, create + "," + tag);
denied(client, CreateVpcRequest.builder().cidrBlock("10.200.0.0/16").build());
denied(client, tagged("other"));
String vpcId = client.createVpc(request).vpc().vpcId();
try {
assertTrue(vpcId.startsWith("vpc-"));
assertTrue(admin.describeVpcs(r -> r.vpcIds(vpcId)).vpcs().getFirst().tags().stream()
.anyMatch(t -> t.key().equals("ManagedBy") && t.value().equals("integration-test")));
} finally {
admin.deleteVpc(r -> r.vpcId(vpcId));
}
policy(name, create + "," + tag + "," + """
{"Effect":"Deny","Action":"ec2:CreateVpc","Resource":"%s"}
""".formatted(resource));
denied(client, request);
policy(name, create.replace(":000000000000:", ":111122223333:") + "," + tag);
denied(client, request);
policy(name, create + "," + tag + "," + """
{"Effect":"Deny","Action":"ec2:CreateTags","Resource":"%s"}
""".formatted(resource));
denied(client, request);
}
}
@ParameterizedTest
@ValueSource(strings = {"ipv4-ipam", "ipv6-ipam", "ipv6-pool"})
void optionalPoolsNeedTheirOwnGrantAndTagsAreCheckedOnlyOnTheVpc(String pool) {
String name = "vpc-pool-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), name);
String resource = pool.equals("ipv6-pool")
? "arn:aws:ec2:us-east-1:000000000000:ipv6pool-ec2/ipv6pool-one"
: "arn:aws:ec2::000000000000:ipam-pool/ipam-pool-one";
CreateVpcRequest.Builder request = tagged("integration-test").toBuilder();
switch (pool) {
case "ipv4-ipam" -> request.ipv4IpamPoolId("ipam-pool-one");
case "ipv6-ipam" -> request.ipv6IpamPoolId("ipam-pool-one");
default -> request.ipv6Pool("ipv6pool-one");
}
String vpc = """
{"Effect":"Allow","Action":["ec2:CreateVpc","ec2:CreateTags"],
"Resource":"arn:aws:ec2:us-east-1:000000000000:vpc/*"}
""";
String grant = """
{"Effect":"Allow","Action":"ec2:CreateVpc","Resource":"%s"}
""".formatted(resource);
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint);
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint)) {
policy(name, vpc);
denied(client, request.build());
policy(name, vpc + "," + grant);
String vpcId = client.createVpc(request.build()).vpc().vpcId();
admin.deleteVpc(r -> r.vpcId(vpcId));
policy(name, vpc + "," + grant + "," + grant.replace("Allow", "Deny"));
denied(client, request.build());
}
}
private CreateVpcRequest tagged(String owner) {
return CreateVpcRequest.builder().cidrBlock("10.200.0.0/16")
.tagSpecifications(TagSpecification.builder().resourceType(ResourceType.VPC)
.tags(Tag.builder().key("ManagedBy").value(owner).build()).build()).build();
}
private void denied(Ec2Client client, CreateVpcRequest request) {
assertAwsError("UnauthorizedOperation", 403, () -> client.createVpc(request));
}
private void policy(String name, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), name,
"create", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
}
@@ -0,0 +1,102 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2NatGatewayIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void natCreationRequiresBothOwnedParentsAndSeparatelyAuthorizedTags() {
String name = "nat-iam-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), name);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.205.0.0/16")).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.205.1.0/24")
.tagSpecifications(tags("subnet", "owner"))).subnet().subnetId();
String allocation = admin.allocateAddress(r -> r.domain("vpc")
.tagSpecifications(tags("elastic-ip", "foreign"))).allocationId();
String created = """
{"Effect":"Allow","Action":"ec2:CreateNatGateway",
"Resource":"arn:aws:ec2:us-east-1:000000000000:natgateway/*",
"Condition":{"StringEquals":{"aws:RequestTag/Owner":"owner"}}}
""";
String parents = """
{"Effect":"Allow","Action":"ec2:CreateNatGateway",
"Resource":["arn:aws:ec2:us-east-1:000000000000:subnet/%s",
"arn:aws:ec2:us-east-1:000000000000:elastic-ip/%s"],
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"owner"}}}
""".formatted(subnet, allocation);
String tag = """
{"Effect":"Allow","Action":"ec2:CreateTags",
"Resource":"arn:aws:ec2:us-east-1:000000000000:natgateway/*",
"Condition":{"StringEquals":{"ec2:CreateAction":"CreateNatGateway"}}}
""";
try {
policy(name, created + "," + parents + "," + tag);
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
admin.createTags(r -> r.resources(allocation).tags(Tag.builder().key("Owner").value("owner").build()));
policy(name, created + "," + tag);
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
policy(name, created + "," + parents);
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
policy(name, created + "," + parents + "," + tag + "," + """
{"Effect":"Deny","Action":"ec2:CreateNatGateway",
"Resource":"arn:aws:ec2:us-east-1:000000000000:elastic-ip/%s"}
""".formatted(allocation));
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
policy(name, created + "," + parents + "," + tag);
create(client, subnet, allocation);
} finally {
admin.describeNatGateways().natGateways().stream().filter(n -> vpc.equals(n.vpcId()))
.forEach(n -> admin.deleteNatGateway(r -> r.natGatewayId(n.natGatewayId())));
admin.releaseAddress(r -> r.allocationId(allocation));
admin.deleteSubnet(r -> r.subnetId(subnet));
admin.deleteVpc(r -> r.vpcId(vpc));
}
}
}
private void policy(String name, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), name, "nat",
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
private static void create(Ec2Client client, String subnet, String allocation) {
client.createNatGateway(r -> r.subnetId(subnet).allocationId(allocation)
.tagSpecifications(tags("natgateway", "owner")));
}
private static TagSpecification tags(String type, String owner) {
return TagSpecification.builder().resourceType(type)
.tags(Tag.builder().key("Owner").value(owner).build()).build();
}
}
@@ -0,0 +1,180 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2NetworkCreateIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void gatewayEndpointChecksEverySuppliedRouteTable() {
String user = "endpoint-routes-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.204.0.0/16")).vpc().vpcId();
String first = admin.createRouteTable(r -> r.vpcId(vpc)).routeTable().routeTableId();
String second = admin.createRouteTable(r -> r.vpcId(vpc)).routeTable().routeTableId();
String allow = """
{"Effect":"Allow","Action":"ec2:CreateVpcEndpoint",
"Resource":"arn:aws:ec2:us-east-1:000000000000:*"}
""";
String deny = """
{"Effect":"Deny","Action":"ec2:CreateVpcEndpoint",
"Resource":"arn:aws:ec2:us-east-1:000000000000:route-table/%s"}
""".formatted(second);
try {
policy(user, allow + "," + deny);
assertAwsError("UnauthorizedOperation", 403,
() -> client.createVpcEndpoint(r -> r.vpcId(vpc).vpcEndpointType("Gateway")
.serviceName("com.amazonaws.us-east-1.s3").routeTableIds(first, second)));
policy(user, allow);
String id = client.createVpcEndpoint(r -> r.vpcId(vpc).vpcEndpointType("Gateway")
.serviceName("com.amazonaws.us-east-1.s3").routeTableIds(first, second))
.vpcEndpoint().vpcEndpointId();
admin.deleteVpcEndpoints(r -> r.vpcEndpointIds(id));
} finally {
admin.describeVpcEndpoints().vpcEndpoints().stream().filter(e -> vpc.equals(e.vpcId()))
.forEach(e -> admin.deleteVpcEndpoints(r -> r.vpcEndpointIds(e.vpcEndpointId())));
admin.deleteRouteTable(r -> r.routeTableId(second));
admin.deleteRouteTable(r -> r.routeTableId(first));
admin.deleteVpc(r -> r.vpcId(vpc));
}
}
}
@ParameterizedTest
@CsvSource({"CreateSubnet,subnet", "CreateRouteTable,route-table", "CreateSecurityGroup,security-group",
"CreateInternetGateway,internet-gateway", "CreateVpcEndpoint,vpc-endpoint", "AllocateAddress,elastic-ip"})
void creationChecksNewResourceTagsAndParentOwnershipSeparately(String action, String type) {
String name = "network-create-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), name);
String resource = "arn:aws:ec2:us-east-1:000000000000:" + type + "/*";
String create = """
{"Effect":"Allow","Action":"ec2:%s","Resource":"%s",
"Condition":{"StringEquals":{"aws:RequestTag/ManagedBy":"integration-test"}}}
""".formatted(action, resource);
String tags = """
{"Effect":"Allow","Action":"ec2:CreateTags","Resource":"%s",
"Condition":{"StringEquals":{"ec2:CreateAction":"%s"}}}
""".formatted(resource, action);
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint);
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.201.0.0/16").tagSpecifications(
specification("vpc", "parent-owner"))).vpc().vpcId();
String parentArn = "arn:aws:ec2:us-east-1:000000000000:vpc/" + vpc;
String parent = """
{"Effect":"Allow","Action":"ec2:%s","Resource":"%s",
"Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"parent-owner"}}}
""".formatted(action, parentArn);
try {
policy(name, create + "," + parent);
assertAwsError("UnauthorizedOperation", 403,
() -> create(client, action, type, vpc, "integration-test"));
policy(name, create + "," + tags + "," + parent);
assertAwsError("UnauthorizedOperation", 403, () -> create(client, action, type, vpc, "wrong-owner"));
String id = create(client, action, type, vpc, "integration-test");
assertEquals("integration-test", admin.describeTags(r -> r.filters(f -> f.name("resource-id")
.values(id))).tags().stream().filter(t -> t.key().equals("ManagedBy")).findFirst()
.orElseThrow().value());
delete(admin, action, id);
policy(name, create + "," + tags + "," + parent + "," + create.replace("Allow", "Deny"));
assertAwsError("UnauthorizedOperation", 403,
() -> create(client, action, type, vpc, "integration-test"));
policy(name, create.replace(":000000000000:", ":111122223333:") + "," + tags + "," + parent);
assertAwsError("UnauthorizedOperation", 403,
() -> create(client, action, type, vpc, "integration-test"));
if (!action.equals("CreateInternetGateway") && !action.equals("AllocateAddress")) {
policy(name, create + "," + tags);
assertAwsError("UnauthorizedOperation", 403,
() -> create(client, action, type, vpc, "integration-test"));
policy(name, create + "," + tags + "," + parent.replace("parent-owner", "integration-test"));
assertAwsError("UnauthorizedOperation", 403,
() -> create(client, action, type, vpc, "integration-test"));
policy(name, create + "," + tags + "," + parent + "," + parent.replace("Allow", "Deny"));
assertAwsError("UnauthorizedOperation", 403,
() -> create(client, action, type, vpc, "integration-test"));
} else {
policy(name, create + "," + tags);
delete(admin, action, create(client, action, type, vpc, "integration-test"));
}
} finally {
admin.deleteVpc(r -> r.vpcId(vpc));
}
}
}
private String create(Ec2Client client, String action, String type, String vpc, String owner) {
TagSpecification tags = specification(type, owner);
return switch (action) {
case "CreateSubnet" -> client.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.201.1.0/24")
.tagSpecifications(tags)).subnet().subnetId();
case "CreateRouteTable" -> client.createRouteTable(r -> r.vpcId(vpc).tagSpecifications(tags))
.routeTable().routeTableId();
case "CreateSecurityGroup" -> client.createSecurityGroup(r -> r.vpcId(vpc)
.groupName("network-" + UUID.randomUUID()).description("IAM integration test")
.tagSpecifications(tags)).groupId();
case "CreateVpcEndpoint" -> client.createVpcEndpoint(r -> r.vpcId(vpc).vpcEndpointType("Gateway")
.serviceName("com.amazonaws.us-east-1.s3").tagSpecifications(tags)).vpcEndpoint().vpcEndpointId();
case "CreateInternetGateway" -> client.createInternetGateway(r -> r.tagSpecifications(tags))
.internetGateway().internetGatewayId();
case "AllocateAddress" -> client.allocateAddress(r -> r.domain("vpc").tagSpecifications(tags)).allocationId();
default -> throw new IllegalArgumentException(action);
};
}
private void delete(Ec2Client admin, String action, String id) {
switch (action) {
case "CreateSubnet" -> admin.deleteSubnet(r -> r.subnetId(id));
case "CreateRouteTable" -> admin.deleteRouteTable(r -> r.routeTableId(id));
case "CreateSecurityGroup" -> admin.deleteSecurityGroup(r -> r.groupId(id));
case "CreateVpcEndpoint" -> admin.deleteVpcEndpoints(r -> r.vpcEndpointIds(id));
case "CreateInternetGateway" -> admin.deleteInternetGateway(r -> r.internetGatewayId(id));
case "AllocateAddress" -> admin.releaseAddress(r -> r.allocationId(id));
default -> throw new IllegalArgumentException(action);
}
}
private TagSpecification specification(String type, String owner) {
return TagSpecification.builder().resourceType(type)
.tags(Tag.builder().key("ManagedBy").value(owner).build()).build();
}
private void policy(String name, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), name,
"network", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
}
@@ -0,0 +1,158 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.NetworkInterface;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2NetworkInterfaceIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void creationChecksSubnetAndEverySecurityGroupWithTheirOwnTags() {
String user = "eni-create-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.203.0.0/16")).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.203.1.0/24")
.tagSpecifications(tags("subnet", "subnet-owner"))).subnet().subnetId();
String group = admin.createSecurityGroup(r -> r.vpcId(vpc).groupName("eni-test")
.description("IAM fixture").tagSpecifications(tags("security-group", "group-owner"))).groupId();
String second = admin.createSecurityGroup(r -> r.vpcId(vpc).groupName("eni-test-second")
.description("IAM fixture").tagSpecifications(tags("security-group", "group-owner"))).groupId();
String create = """
{"Effect":"Allow","Action":"ec2:CreateNetworkInterface",
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/*",
"Condition":{"StringEquals":{"aws:RequestTag/ManagedBy":"integration-test"}}}
""";
String tag = """
{"Effect":"Allow","Action":"ec2:CreateTags",
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/*",
"Condition":{"StringEquals":{"ec2:CreateAction":"CreateNetworkInterface"}}}
""";
String subnetGrant = grant("subnet/" + subnet, "subnet-owner");
String firstGrant = grant("security-group/" + group, "group-owner");
String secondGrant = grant("security-group/" + second, "group-owner");
String all = create + "," + tag + "," + subnetGrant + "," + firstGrant + "," + secondGrant;
Runnable request = () -> create(client, subnet, group, second, "integration-test");
try {
policy(user, create + "," + subnetGrant + "," + firstGrant + "," + secondGrant);
assertAwsError("UnauthorizedOperation", 403, request::run);
policy(user, create + "," + tag + "," + firstGrant + "," + secondGrant);
assertAwsError("UnauthorizedOperation", 403, request::run);
policy(user, create + "," + tag + "," + subnetGrant + "," + firstGrant);
assertAwsError("UnauthorizedOperation", 403, request::run);
policy(user, all.replace("subnet-owner", "group-owner"));
assertAwsError("UnauthorizedOperation", 403, request::run);
policy(user, all + "," + secondGrant.replace("Allow", "Deny"));
assertAwsError("UnauthorizedOperation", 403, request::run);
policy(user, all);
assertAwsError("UnauthorizedOperation", 403,
() -> create(client, subnet, group, second, "wrong-owner"));
String eni = create(client, subnet, group, second, "integration-test");
assertEquals(2, admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(eni))
.networkInterfaces().getFirst().groups().size());
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
} finally {
for (NetworkInterface eni : admin.describeNetworkInterfaces().networkInterfaces()) {
if (subnet.equals(eni.subnetId())) {
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni.networkInterfaceId()));
}
}
admin.deleteSecurityGroup(r -> r.groupId(second));
admin.deleteSecurityGroup(r -> r.groupId(group));
admin.deleteSubnet(r -> r.subnetId(subnet));
admin.deleteVpc(r -> r.vpcId(vpc));
}
}
}
@Test
void creationTagsAuthorizeLaterMutationsAndStayInSync() {
String user = "eni-tags-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.204.0.0/16")).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.204.1.0/24")).subnet().subnetId();
String eni = admin.createNetworkInterface(r -> r.subnetId(subnet)
.tagSpecifications(tags("network-interface", "team-a"))).networkInterface().networkInterfaceId();
try {
policy(user, """
{"Effect":"Allow","Action":["ec2:CreateTags","ec2:DeleteTags"],
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/%s",
"Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"team-a",
"ec2:ResourceTag/ManagedBy":"team-a"}}}
""".formatted(eni));
client.createTags(r -> r.resources(eni).tags(t -> t.key("Purpose").value("fixture")));
assertEquals(2, admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(eni))
.networkInterfaces().getFirst().tagSet().size());
client.createTags(r -> r.resources(eni).tags(t -> t.key("ManagedBy").value("team-b")));
assertEquals("team-b", admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(eni))
.networkInterfaces().getFirst().tagSet().stream().filter(t -> t.key().equals("ManagedBy"))
.findFirst().orElseThrow().value());
assertAwsError("UnauthorizedOperation", 403,
() -> client.createTags(r -> r.resources(eni).tags(t -> t.key("Purpose").value("denied"))));
admin.createTags(r -> r.resources(eni).tags(t -> t.key("ManagedBy").value("team-a")));
client.deleteTags(r -> r.resources(eni).tags(t -> t.key("ManagedBy")));
assertAwsError("UnauthorizedOperation", 403,
() -> client.createTags(r -> r.resources(eni).tags(t -> t.key("Purpose").value("denied"))));
} finally {
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
assertEquals(0, admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(eni))).tags().size());
admin.deleteSubnet(r -> r.subnetId(subnet));
admin.deleteVpc(r -> r.vpcId(vpc));
}
}
}
private String create(Ec2Client client, String subnet, String group, String second, String owner) {
return client.createNetworkInterface(r -> r.subnetId(subnet).groups(group, second)
.tagSpecifications(tags("network-interface", owner))).networkInterface().networkInterfaceId();
}
private TagSpecification tags(String type, String owner) {
return TagSpecification.builder().resourceType(type).tags(t -> t.key("ManagedBy").value(owner)).build();
}
private String grant(String resource, String owner) {
return """
{"Effect":"Allow","Action":"ec2:CreateNetworkInterface",
"Resource":"arn:aws:ec2:us-east-1:000000000000:%s",
"Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"%s"}}}
""".formatted(resource, owner);
}
private void policy(String user, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
"network", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
}
@@ -0,0 +1,169 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.IpPermission;
import software.amazon.awssdk.services.ec2.model.RouteTableAssociation;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2NetworkMutationIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@ValueSource(strings = {"ModifySubnetAttribute", "AttachInternetGateway", "DetachInternetGateway",
"CreateRoute", "ReplaceRoute", "DeleteRoute", "AssociateRouteTable",
"AuthorizeSecurityGroupIngress", "AuthorizeSecurityGroupEgress", "RevokeSecurityGroupIngress",
"RevokeSecurityGroupEgress", "DeleteVpc", "DeleteSubnet", "DeleteRouteTable",
"DeleteInternetGateway", "DeleteSecurityGroup"})
void scopedMutationsReadCurrentOwnershipAndHonorDenies(String action) {
String user = "network-mutation-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint);
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.202.0.0/16").tagSpecifications(tags("vpc"))).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.202.1.0/24")
.tagSpecifications(tags("subnet"))).subnet().subnetId();
String table = admin.createRouteTable(r -> r.vpcId(vpc).tagSpecifications(tags("route-table")))
.routeTable().routeTableId();
String gateway = admin.createInternetGateway(r -> r.tagSpecifications(tags("internet-gateway")))
.internetGateway().internetGatewayId();
String group = admin.createSecurityGroup(r -> r.vpcId(vpc).groupName("scoped-" + UUID.randomUUID())
.description("IAM mutation fixture").tagSpecifications(tags("security-group"))).groupId();
IpPermission permission = IpPermission.builder().ipProtocol("tcp").fromPort(443).toPort(443)
.ipRanges(r -> r.cidrIp("192.0.2.0/24")).build();
if (action.equals("DetachInternetGateway") || action.endsWith("Route")) {
admin.attachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc));
}
if (action.equals("ReplaceRoute") || action.equals("DeleteRoute")) {
admin.createRoute(r -> r.routeTableId(table).gatewayId(gateway).destinationCidrBlock("0.0.0.0/0"));
}
if (action.equals("RevokeSecurityGroupIngress")) {
admin.authorizeSecurityGroupIngress(r -> r.groupId(group).ipPermissions(permission));
}
if (action.equals("RevokeSecurityGroupEgress")) {
admin.authorizeSecurityGroupEgress(r -> r.groupId(group).ipPermissions(permission));
}
if (action.equals("DeleteVpc")) {
admin.deleteSubnet(r -> r.subnetId(subnet));
admin.deleteRouteTable(r -> r.routeTableId(table));
admin.deleteSecurityGroup(r -> r.groupId(group));
}
Runnable mutate = () -> {
switch (action) {
case "ModifySubnetAttribute" -> client.modifySubnetAttribute(r -> r.subnetId(subnet)
.mapPublicIpOnLaunch(v -> v.value(true)));
case "AttachInternetGateway" -> client.attachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc));
case "DetachInternetGateway" -> client.detachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc));
case "CreateRoute" -> client.createRoute(r -> r.routeTableId(table).gatewayId(gateway)
.destinationCidrBlock("0.0.0.0/0"));
case "ReplaceRoute" -> client.replaceRoute(r -> r.routeTableId(table).gatewayId(gateway)
.destinationCidrBlock("0.0.0.0/0"));
case "DeleteRoute" -> client.deleteRoute(r -> r.routeTableId(table).destinationCidrBlock("0.0.0.0/0"));
case "AssociateRouteTable" -> client.associateRouteTable(r -> r.routeTableId(table).subnetId(subnet));
case "AuthorizeSecurityGroupIngress" -> client.authorizeSecurityGroupIngress(r -> r.groupId(group)
.ipPermissions(permission));
case "AuthorizeSecurityGroupEgress" -> client.authorizeSecurityGroupEgress(r -> r.groupId(group)
.ipPermissions(permission));
case "RevokeSecurityGroupIngress" -> client.revokeSecurityGroupIngress(r -> r.groupId(group)
.ipPermissions(permission));
case "RevokeSecurityGroupEgress" -> client.revokeSecurityGroupEgress(r -> r.groupId(group)
.ipPermissions(permission));
case "DeleteVpc" -> client.deleteVpc(r -> r.vpcId(vpc));
case "DeleteSubnet" -> client.deleteSubnet(r -> r.subnetId(subnet));
case "DeleteRouteTable" -> client.deleteRouteTable(r -> r.routeTableId(table));
case "DeleteInternetGateway" -> client.deleteInternetGateway(r -> r.internetGatewayId(gateway));
case "DeleteSecurityGroup" -> client.deleteSecurityGroup(r -> r.groupId(group));
default -> throw new IllegalArgumentException(action);
}
};
String grant = """
{"Effect":"Allow","Action":"ec2:%s","Resource":"arn:aws:ec2:us-east-1:000000000000:*",
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"integration-test"}}}
""".formatted(action);
// New rule IDs have no stored tags; authorization of the parent group remains required.
String rules = """
,{"Effect":"Allow","Action":"ec2:%s",
"Resource":"arn:aws:ec2:us-east-1:000000000000:security-group-rule/*"}
""".formatted(action);
try {
policy(user, grant.replace("integration-test", "wrong-owner") + rules);
assertAwsError("UnauthorizedOperation", 403, mutate::run);
policy(user, grant.replace(":000000000000:", ":111122223333:") + rules);
assertAwsError("UnauthorizedOperation", 403, mutate::run);
policy(user, grant + rules + "," + grant.replace("Allow", "Deny"));
assertAwsError("UnauthorizedOperation", 403, mutate::run);
policy(user, grant + rules);
mutate.run();
if (action.equals("ModifySubnetAttribute")) {
assertTrue(admin.describeSubnets(r -> r.subnetIds(subnet)).subnets().getFirst().mapPublicIpOnLaunch());
}
} finally {
if (!action.equals("DeleteVpc")) {
if (!action.equals("DeleteRouteTable")) {
for (RouteTableAssociation association : admin.describeRouteTables(r -> r.routeTableIds(table))
.routeTables().getFirst().associations()) {
if (!Boolean.TRUE.equals(association.main())) {
admin.disassociateRouteTable(r -> r.associationId(association.routeTableAssociationId()));
}
}
remove(() -> admin.deleteRouteTable(r -> r.routeTableId(table)));
}
remove(() -> admin.deleteSubnet(r -> r.subnetId(subnet)));
remove(() -> admin.deleteSecurityGroup(r -> r.groupId(group)));
}
remove(() -> admin.detachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc)));
remove(() -> admin.deleteInternetGateway(r -> r.internetGatewayId(gateway)));
remove(() -> admin.deleteVpc(r -> r.vpcId(vpc)));
}
}
}
private TagSpecification tags(String type) {
return TagSpecification.builder().resourceType(type).tags(t -> t.key("Owner").value("integration-test")).build();
}
private void remove(Runnable cleanup) {
try {
cleanup.run();
} catch (Ec2Exception expected) {
// The action under test may already have removed or detached this fixture.
if (!expected.awsErrorDetails().errorCode().endsWith(".NotFound")
&& !expected.awsErrorDetails().errorCode().equals("Gateway.NotAttached")) {
throw expected;
}
}
}
private void policy(String user, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
"mutation", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
}
@@ -0,0 +1,114 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Tag;
import java.net.URI;
import java.util.List;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2NetworkTagsIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void networkTagBatchesAuthorizeEachResourceAndItsOwnStoredTags() {
String user = "network-tags-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.206.0.0/16")).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.206.1.0/24")).subnet().subnetId();
String group = admin.describeSecurityGroups(r -> r.filters(f -> f.name("vpc-id").values(vpc)))
.securityGroups().getFirst().groupId();
String acl = admin.describeNetworkAcls(r -> r.filters(f -> f.name("vpc-id").values(vpc)))
.networkAcls().getFirst().networkAclId();
String route = admin.describeRouteTables(r -> r.filters(f -> f.name("vpc-id").values(vpc)))
.routeTables().getFirst().routeTableId();
String eni = admin.createNetworkInterface(r -> r.subnetId(subnet).groups(group))
.networkInterface().networkInterfaceId();
List<String> ids = List.of(group, acl, route, eni);
String resources = """
["arn:aws:ec2:us-east-1:000000000000:security-group/*",
"arn:aws:ec2:us-east-1:000000000000:network-acl/*",
"arn:aws:ec2:us-east-1:000000000000:route-table/*",
"arn:aws:ec2:us-east-1:000000000000:network-interface/*"]
""";
String grant = """
{"Effect":"Allow","Action":"ec2:CreateTags","Resource":%s,
"Condition":{"StringEquals":{"aws:RequestTag/Owner":"owner"},
"ForAllValues:StringEquals":{"aws:TagKeys":["Owner"]},
"StringEqualsIfExists":{"aws:ResourceTag/Owner":"${aws:RequestTag/Owner}"},
"Null":{"aws:ResourceTag/ManagedBy":"true"}}},
{"Effect":"Allow","Action":"ec2:DeleteTags","Resource":%s,
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"owner"}}}
""".formatted(resources, resources);
try {
policy(user, grant);
client.createTags(r -> r.resources(ids).tags(owner("owner")));
assertEquals(4, admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(ids)))
.tags().stream().filter(t -> "Owner".equals(t.key()) && "owner".equals(t.value())).count());
admin.createTags(r -> r.resources(eni).tags(owner("foreign")));
assertAwsError("UnauthorizedOperation", 403,
() -> client.createTags(r -> r.resources(ids).tags(owner("owner"))));
assertAwsError("UnauthorizedOperation", 403,
() -> client.deleteTags(r -> r.resources(ids).tags(owner("owner"))));
assertEquals(4, admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(ids)))
.tags().stream().filter(t -> "Owner".equals(t.key())).count());
admin.createTags(r -> r.resources(eni).tags(owner("owner")));
policy(user, grant + "," + """
{"Effect":"Deny","Action":["ec2:CreateTags","ec2:DeleteTags"],
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/%s"}
""".formatted(eni));
assertAwsError("UnauthorizedOperation", 403,
() -> client.createTags(r -> r.resources(ids).tags(owner("owner"))));
assertAwsError("UnauthorizedOperation", 403,
() -> client.deleteTags(r -> r.resources(ids).tags(owner("owner"))));
policy(user, grant);
// A resource type not covered by the grants must not borrow a preceding target's ARN.
assertAwsError("UnauthorizedOperation", 403,
() -> client.createTags(r -> r.resources(group, vpc).tags(owner("owner"))));
client.deleteTags(r -> r.resources(ids).tags(owner("owner")));
assertTrue(admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(ids))).tags().stream()
.noneMatch(t -> "Owner".equals(t.key())));
} finally {
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
admin.deleteSubnet(r -> r.subnetId(subnet));
admin.deleteVpc(r -> r.vpcId(vpc));
}
}
}
private void policy(String user, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user, "tags",
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
private static Tag owner(String value) {
return Tag.builder().key("Owner").value(value).build();
}
}
@@ -0,0 +1,93 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.ResourceType;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import software.amazon.awssdk.services.ec2.model.VpcAttributeName;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2VpcResourceTagsIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@ValueSource(strings = {"aws:ResourceTag/", "ec2:ResourceTag/"})
void modifyVpcAttributeUsesTheTargetsCurrentTagsAndHonorsDeny(String prefix) {
String user = "vpc-tag-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
String allow = """
{"Effect":"Allow","Action":"ec2:ModifyVpcAttribute",
"Resource":"arn:aws:ec2:us-east-1:000000000000:vpc/*",
"Condition":{"StringEquals":{"%sManagedBy":"integration-test"}}}
""".formatted(prefix);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String owned = create(admin, "integration-test");
String other = create(admin, "other");
String untagged = admin.createVpc(r -> r.cidrBlock("10.203.0.0/16")).vpc().vpcId();
try {
policy(user, allow);
client.modifyVpcAttribute(r -> r.vpcId(owned).enableDnsHostnames(a -> a.value(true)));
assertTrue(admin.describeVpcAttribute(r -> r.vpcId(owned)
.attribute(VpcAttributeName.ENABLE_DNS_HOSTNAMES)).enableDnsHostnames().value());
denied(client, other);
denied(client, untagged);
policy(user, allow + "," + """
{"Effect":"Deny","Action":"ec2:ModifyVpcAttribute",
"Resource":"arn:aws:ec2:us-east-1:000000000000:vpc/%s"}
""".formatted(owned));
denied(client, owned);
policy(user, allow);
admin.createTags(r -> r.resources(owned).tags(Tag.builder().key("ManagedBy").value("other").build()));
denied(client, owned);
} finally {
for (String id : new String[]{owned, other, untagged}) {
admin.deleteVpc(r -> r.vpcId(id));
}
}
}
}
private String create(Ec2Client client, String owner) {
return client.createVpc(r -> r.cidrBlock("10.202.0.0/16")
.tagSpecifications(TagSpecification.builder().resourceType(ResourceType.VPC)
.tags(Tag.builder().key("ManagedBy").value(owner).build()).build())).vpc().vpcId();
}
private void denied(Ec2Client client, String vpcId) {
assertAwsError("UnauthorizedOperation", 403,
() -> client.modifyVpcAttribute(r -> r.vpcId(vpcId).enableDnsHostnames(a -> a.value(true))));
}
private void policy(String user, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
"modify", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
}
@@ -447,7 +447,10 @@ class RequestResourceMembersTest {
}
String sent = where == null ? value : "other";
put(body, member, sent);
form.append('&').append(parameter(member)).append('=').append(encoded(sent));
String ec2Wire = table.ec2Query().getOrDefault(operation.getKey(), Map.of()).get(member);
String parameter = ec2Wire == null ? parameter(member)
: ec2Wire + (member.list() ? ".1" : "");
form.append('&').append(parameter).append('=').append(encoded(sent));
});
List<String> named = operation.getValue().stream()
.filter(other -> (other == resource || named(other) || sharesAMember(other, given)
@@ -31,6 +31,7 @@ class RequestResourcesTest {
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
private static final RegionResolver US_EAST_1 = new RegionResolver("us-east-1", "000000000000");
/** EventBridge as it answers the reader: the Region's default bus, {@code event-bus/default}. */
private static final StoredResourceArns EVENTS = new StoredResourceArns() {
@Override
@@ -50,6 +51,34 @@ class RequestResourcesTest {
}
};
@Test
void ec2ListsUseSdkWireNamesAndIgnoreForgedQuerySpellings() {
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
List<String> expected = List.of(prefix + "network-interface/*", prefix + "security-group/sg-one",
prefix + "security-group/sg-two", prefix + "subnet/subnet-one");
assertEquals(expected, of("ec2:CreateNetworkInterface", form("Action=CreateNetworkInterface"
+ "&SubnetId=subnet-one&SecurityGroupId.1=sg-one&SecurityGroupId.2=sg-two"
+ "&Groups.member.1=sg-forged&Groups.2=sg-forged&Groups=sg-forged")));
assertEquals(expected, of("ec2:CreateNetworkInterface", json("""
{"SubnetId":"subnet-one","Groups":["sg-one","sg-two"]}
""")));
}
@Test
void createVpcChecksItsNewArnAndOnlyThePoolsPresentInTheRequest() {
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
assertEquals(List.of(prefix + "vpc/*"), of("ec2:CreateVpc", json("{\"CidrBlock\":\"10.0.0.0/16\"}")));
assertEquals(List.of("arn:aws:ec2::000000000000:ipam-pool/ipam-pool-v4",
prefix + "ipv6pool-ec2/ipv6pool-one", prefix + "vpc/*",
"arn:aws:ec2::000000000000:ipam-pool/ipam-pool-v6"),
of("ec2:CreateVpc", json("""
{"Ipv4IpamPoolId":"ipam-pool-v4","Ipv6IpamPoolId":"ipam-pool-v6",
"Ipv6Pool":"ipv6pool-one"}
""")));
assertEquals(List.of(prefix + "vpc/*", "arn:aws:ec2::000000000000:ipam-pool/ipam-pool-v6"),
of("ec2:CreateVpc", json("{\"Ipv6IpamPoolId\":\"ipam-pool-v6\"}")));
}
@Test
void inferredLandingZoneIdentifiersKeepRawContextAcrossOperations() {
String arn = "arn:aws:controltower:::landingzone/missing";