mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iam): resolve resource and request tag condition keys for EC2 and S3 (#3212)
* feat(iam): resolve resource and request tag condition keys for EC2 and S3 bucket actions A policy scoped through aws:ResourceTag or aws:RequestTag never matched because neither key was placed in the request context. The resolver now reads aws:RequestTag from the tags named in RunInstances, CreateTags and PutBucketTagging, and aws:ResourceTag from the target's current tags for the EC2 tag and instance actions and the S3 bucket tagging and delete actions. EC2 and S3 are reached through Instance, as DynamoDB already is. Ported from lex00/floci#135. * fix(iam): authorize every target of a multi-resource EC2 request The resource tag context came from the first ResourceId or InstanceId only, so a caller could name a permitted resource first and act on later ones the policy did not allow. The resolver now yields one context per further target and the filter evaluates each of them, denying the request when any target fails. An untagged target gets an empty context so a tag condition fails on it. * fix(iam): read a repeated numbered parameter the way the EC2 handler does A Query request can repeat ResourceId.1 or InstanceId.1. The resolver kept the last value while the handler acts on the first, so the authorized resource and the acted-on resource could differ. The form parameters now keep the first value, and the remaining-targets pass starts only when member 1 is present, so both readers stop at the same numbering gap.
This commit is contained in:
1 parent
5b7c2c4a62
commit
64538f7d32
7 files changed
+797
-3
No files matched your search
+319
-1
@@ -6,24 +6,35 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IamConditionContextResolverTest {
|
||||
@@ -31,6 +42,8 @@ class IamConditionContextResolverTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private DynamoDbService dynamoDbService;
|
||||
private Instance<DynamoDbService> dynamoDbServiceInstance;
|
||||
private Ec2Service ec2Service;
|
||||
private S3Service s3Service;
|
||||
private RequestContext requestContext;
|
||||
private EmulatorConfig config;
|
||||
private IamConditionContextResolver resolver;
|
||||
@@ -42,12 +55,40 @@ class IamConditionContextResolverTest {
|
||||
dynamoDbServiceInstance = mock(Instance.class);
|
||||
when(dynamoDbServiceInstance.isResolvable()).thenReturn(true);
|
||||
when(dynamoDbServiceInstance.get()).thenReturn(dynamoDbService);
|
||||
ec2Service = mock(Ec2Service.class);
|
||||
Instance<Ec2Service> ec2ServiceInstance = mock(Instance.class);
|
||||
when(ec2ServiceInstance.isResolvable()).thenReturn(true);
|
||||
when(ec2ServiceInstance.get()).thenReturn(ec2Service);
|
||||
s3Service = mock(S3Service.class);
|
||||
Instance<S3Service> s3ServiceInstance = mock(Instance.class);
|
||||
when(s3ServiceInstance.isResolvable()).thenReturn(true);
|
||||
when(s3ServiceInstance.get()).thenReturn(s3Service);
|
||||
requestContext = new RequestContext();
|
||||
requestContext.setRegion("us-east-1");
|
||||
config = mock(EmulatorConfig.class);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
resolver = new IamConditionContextResolver(
|
||||
dynamoDbServiceInstance, requestContext, config);
|
||||
dynamoDbServiceInstance, ec2ServiceInstance, s3ServiceInstance, requestContext, config);
|
||||
}
|
||||
|
||||
/** A form request whose body can be read again, as a real request's restored stream can. */
|
||||
private static ContainerRequestContext formRequest(String body) {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
when(containerRequest.getMediaType())
|
||||
.thenReturn(MediaType.valueOf("application/x-www-form-urlencoded"));
|
||||
when(containerRequest.getEntityStream())
|
||||
.thenAnswer(invocation -> new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
|
||||
return containerRequest;
|
||||
}
|
||||
|
||||
private static ContainerRequestContext s3Request(String path, String body) {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn(path);
|
||||
when(containerRequest.getEntityStream())
|
||||
.thenReturn(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
|
||||
return containerRequest;
|
||||
}
|
||||
|
||||
private TableDefinition fgacTable() {
|
||||
@@ -183,4 +224,281 @@ class IamConditionContextResolverTest {
|
||||
|
||||
assertFalse(conditions.containsKey("dynamodb:LeadingKeys"));
|
||||
}
|
||||
|
||||
// ── aws:RequestTag and aws:ResourceTag ─────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void putBucketTaggingResolvesRequestTagsFromTheXmlBody() {
|
||||
ContainerRequestContext containerRequest = s3Request("/my-bucket", "<Tagging><TagSet>"
|
||||
+ "<Tag><Key>Team</Key><Value>payments</Value></Tag>"
|
||||
+ "<Tag><Key>Env</Key><Value>prod</Value></Tag>"
|
||||
+ "</TagSet></Tagging>");
|
||||
|
||||
Map<String, List<String>> conditions =
|
||||
resolver.resolve("s3", "s3:PutBucketTagging", containerRequest);
|
||||
|
||||
assertEquals(List.of("payments"), conditions.get("aws:RequestTag/Team"));
|
||||
assertEquals(List.of("prod"), conditions.get("aws:RequestTag/Env"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putBucketTaggingRestoresTheBodyForTheController() throws Exception {
|
||||
String body = "<Tagging><TagSet><Tag><Key>Team</Key><Value>payments</Value></Tag></TagSet></Tagging>";
|
||||
ContainerRequestContext containerRequest = s3Request("/my-bucket", body);
|
||||
|
||||
resolver.resolve("s3", "s3:PutBucketTagging", containerRequest);
|
||||
|
||||
var restored = org.mockito.ArgumentCaptor.forClass(java.io.InputStream.class);
|
||||
verify(containerRequest).setEntityStream(restored.capture());
|
||||
assertArrayEquals(body.getBytes(StandardCharsets.UTF_8), restored.getValue().readAllBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bucketActionsResolveResourceTagsFromTheBucketsCurrentTags() {
|
||||
when(s3Service.getBucketTagging("my-bucket")).thenReturn(Map.of("Owner", "alice"));
|
||||
|
||||
for (String action : List.of("s3:GetBucketTagging", "s3:DeleteBucketTagging", "s3:DeleteBucket")) {
|
||||
Map<String, List<String>> conditions =
|
||||
resolver.resolve("s3", action, s3Request("/my-bucket", ""));
|
||||
assertEquals(List.of("alice"), conditions.get("aws:ResourceTag/Owner"), action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void bucketActionsOfferNoResourceTagsWhenTheBucketLookupFails() {
|
||||
when(s3Service.getBucketTagging(anyString()))
|
||||
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
|
||||
assertNull(resolver.resolve("s3", "s3:GetBucketTagging", s3Request("/missing-bucket", "")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void runInstancesResolvesRequestTagsFromEveryTagSpecification() {
|
||||
ContainerRequestContext containerRequest = formRequest("Action=RunInstances"
|
||||
+ "&TagSpecification.1.ResourceType=instance"
|
||||
+ "&TagSpecification.1.Tag.1.Key=Team&TagSpecification.1.Tag.1.Value=payments"
|
||||
+ "&TagSpecification.2.ResourceType=volume"
|
||||
+ "&TagSpecification.2.Tag.1.Key=Env&TagSpecification.2.Tag.1.Value=prod");
|
||||
|
||||
Map<String, List<String>> conditions =
|
||||
resolver.resolve("ec2", "ec2:RunInstances", containerRequest);
|
||||
|
||||
assertEquals(List.of("payments"), conditions.get("aws:RequestTag/Team"));
|
||||
assertEquals(List.of("prod"), conditions.get("aws:RequestTag/Env"));
|
||||
assertFalse(conditions.containsKey("aws:ResourceTag/Team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTagsResolvesBothTheRequestedTagsAndTheResourcesCurrentTags() {
|
||||
when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Owner", "alice")));
|
||||
ContainerRequestContext containerRequest = formRequest(
|
||||
"Action=CreateTags&ResourceId.1=i-0123456789&Tag.1.Key=Env&Tag.1.Value=prod");
|
||||
|
||||
Map<String, List<String>> conditions =
|
||||
resolver.resolve("ec2", "ec2:CreateTags", containerRequest);
|
||||
|
||||
assertEquals(List.of("prod"), conditions.get("aws:RequestTag/Env"));
|
||||
assertEquals(List.of("alice"), conditions.get("aws:ResourceTag/Owner"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceActionsResolveResourceTagsFromTheFirstNamedInstance() {
|
||||
when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
|
||||
for (String action : List.of("ec2:TerminateInstances", "ec2:DescribeInstances")) {
|
||||
Map<String, List<String>> conditions = resolver.resolve("ec2", action,
|
||||
formRequest("Action=X&InstanceId.1=i-0123456789&InstanceId.2=i-9999999999"));
|
||||
assertEquals(List.of("payments"), conditions.get("aws:ResourceTag/Team"), action);
|
||||
}
|
||||
assertEquals(List.of("payments"),
|
||||
resolver.resolve("ec2", "ec2:DeleteTags",
|
||||
formRequest("Action=DeleteTags&ResourceId.1=i-0123456789&Tag.1.Key=Team"))
|
||||
.get("aws:ResourceTag/Team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2ContextIsAbsentWhenNoResourceIsNamedOrTheActionIsNotCovered() {
|
||||
assertNull(resolver.resolve("ec2", "ec2:DescribeInstances", formRequest("Action=DescribeInstances")));
|
||||
assertNull(resolver.resolve("ec2", "ec2:DescribeVpcs", formRequest("Action=DescribeVpcs")));
|
||||
assertNull(resolver.resolve("ec2", "ec2:CreateTags",
|
||||
formRequest("Action=CreateTags&ResourceId.1=i-0123456789")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void formParametersAreBufferedOncePerRequest() {
|
||||
ContainerRequestContext containerRequest = formRequest("Action=TerminateInstances&InstanceId.1=i-1");
|
||||
when(ec2Service.resourceTags("i-1")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
|
||||
resolver.resolve("ec2", "ec2:TerminateInstances", containerRequest);
|
||||
|
||||
verify(containerRequest).setEntityStream(any());
|
||||
verify(containerRequest).setProperty(eq("floci.bufferedFormBody"), any());
|
||||
}
|
||||
|
||||
// ── The resolved context drives the real evaluator ─────────────────────────
|
||||
|
||||
private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
|
||||
|
||||
@Test
|
||||
void resourceTagConditionAllowsATaggedInstanceAndDeniesAnUntaggedOne() {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}}
|
||||
]}""";
|
||||
String body = "Action=TerminateInstances&InstanceId.1=i-0123456789";
|
||||
|
||||
when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy),
|
||||
"ec2:TerminateInstances", "*",
|
||||
resolver.resolve("ec2", "ec2:TerminateInstances", formRequest(body))));
|
||||
|
||||
when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Team", "engineering")));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy),
|
||||
"ec2:TerminateInstances", "*",
|
||||
resolver.resolve("ec2", "ec2:TerminateInstances", formRequest(body))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestTagConditionAllowsTheDemandedTagValueAndDeniesAnotherOne() {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:CreateTags","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:RequestTag/CostCenter":"1234"}}}
|
||||
]}""";
|
||||
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), "ec2:CreateTags", "*",
|
||||
resolver.resolve("ec2", "ec2:CreateTags", formRequest(
|
||||
"Action=CreateTags&ResourceId.1=i-1&Tag.1.Key=CostCenter&Tag.1.Value=1234"))));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "ec2:CreateTags", "*",
|
||||
resolver.resolve("ec2", "ec2:CreateTags", formRequest(
|
||||
"Action=CreateTags&ResourceId.1=i-1&Tag.1.Key=CostCenter&Tag.1.Value=9999"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceTagConditionOnABucketFollowsItsOwnerTag() {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetBucketTagging","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"alice"}}}
|
||||
]}""";
|
||||
|
||||
when(s3Service.getBucketTagging("my-bucket")).thenReturn(Map.of("Owner", "alice"));
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), "s3:GetBucketTagging", "*",
|
||||
resolver.resolve("s3", "s3:GetBucketTagging", s3Request("/my-bucket", ""))));
|
||||
|
||||
when(s3Service.getBucketTagging("my-bucket")).thenReturn(Map.of("Owner", "bob"));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "s3:GetBucketTagging", "*",
|
||||
resolver.resolve("s3", "s3:GetBucketTagging", s3Request("/my-bucket", ""))));
|
||||
}
|
||||
|
||||
// ── Every target of a multi-resource request is evaluated ──────────────────
|
||||
|
||||
@Test
|
||||
void remainingTargetsCarryEachLaterResourcesOwnTags() {
|
||||
when(ec2Service.resourceTags("i-1")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "engineering")));
|
||||
when(ec2Service.resourceTags("i-3")).thenReturn(List.of());
|
||||
ContainerRequestContext containerRequest = formRequest(
|
||||
"Action=TerminateInstances&InstanceId.1=i-1&InstanceId.2=i-2&InstanceId.3=i-3");
|
||||
|
||||
List<Map<String, List<String>>> remaining =
|
||||
resolver.resolveRemainingTargets("ec2", "ec2:TerminateInstances", containerRequest);
|
||||
|
||||
assertEquals(2, remaining.size());
|
||||
assertEquals(List.of("engineering"), remaining.get(0).get("aws:ResourceTag/Team"));
|
||||
// An untagged target still gets its own, empty, context so a tag condition fails on it.
|
||||
assertEquals(Map.of(), remaining.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void remainingTargetsOfCreateTagsRepeatTheRequestedTagsPerResource() {
|
||||
when(ec2Service.resourceTags("vpc-2")).thenReturn(List.of(new Tag("Owner", "bob")));
|
||||
ContainerRequestContext containerRequest = formRequest(
|
||||
"Action=CreateTags&ResourceId.1=vpc-1&ResourceId.2=vpc-2&Tag.1.Key=Env&Tag.1.Value=prod");
|
||||
|
||||
List<Map<String, List<String>>> remaining =
|
||||
resolver.resolveRemainingTargets("ec2", "ec2:CreateTags", containerRequest);
|
||||
|
||||
assertEquals(1, remaining.size());
|
||||
assertEquals(List.of("prod"), remaining.get(0).get("aws:RequestTag/Env"));
|
||||
assertEquals(List.of("bob"), remaining.get(0).get("aws:ResourceTag/Owner"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleTargetRequestsAndOtherServicesHaveNoRemainingTargets() {
|
||||
assertEquals(List.of(), resolver.resolveRemainingTargets("ec2", "ec2:TerminateInstances",
|
||||
formRequest("Action=TerminateInstances&InstanceId.1=i-1")));
|
||||
assertEquals(List.of(), resolver.resolveRemainingTargets("ec2", "ec2:RunInstances",
|
||||
formRequest("Action=RunInstances&TagSpecification.1.ResourceType=instance")));
|
||||
assertEquals(List.of(), resolver.resolveRemainingTargets("s3", "s3:DeleteBucket",
|
||||
s3Request("/my-bucket", "")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyMustHoldForEveryTargetNotJustTheFirst() {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}}
|
||||
]}""";
|
||||
String body = "Action=TerminateInstances&InstanceId.1=i-1&InstanceId.2=i-2";
|
||||
when(ec2Service.resourceTags("i-1")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
|
||||
when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "engineering")));
|
||||
assertEquals(Decision.DENY, decisionForEveryTarget(policy, "ec2:TerminateInstances", formRequest(body)));
|
||||
|
||||
when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
assertEquals(Decision.ALLOW, decisionForEveryTarget(policy, "ec2:TerminateInstances", formRequest(body)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRepeatedNumberedParameterKeepsItsFirstValueLikeTheHandlers() {
|
||||
when(ec2Service.resourceTags("i-first")).thenReturn(List.of(new Tag("Team", "engineering")));
|
||||
when(ec2Service.resourceTags("i-second")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
|
||||
Map<String, List<String>> conditions = resolver.resolve("ec2", "ec2:TerminateInstances",
|
||||
formRequest("Action=TerminateInstances&InstanceId.1=i-first&InstanceId.1=i-second"));
|
||||
|
||||
assertEquals(List.of("engineering"), conditions.get("aws:ResourceTag/Team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void remainingTargetsStopAtTheFirstNumberingGapLikeTheHandlers() {
|
||||
when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
|
||||
assertEquals(List.of(), resolver.resolveRemainingTargets("ec2", "ec2:TerminateInstances",
|
||||
formRequest("Action=TerminateInstances&InstanceId.2=i-2")));
|
||||
assertEquals(List.of(), resolver.resolveRemainingTargets("ec2", "ec2:TerminateInstances",
|
||||
formRequest("Action=TerminateInstances&InstanceId.1=i-1&InstanceId.3=i-3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRepeatedKeyCannotSwapAnAllowedResourceInFrontOfTheDeniedOne() {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}}
|
||||
]}""";
|
||||
when(ec2Service.resourceTags("i-denied")).thenReturn(List.of(new Tag("Team", "engineering")));
|
||||
when(ec2Service.resourceTags("i-allowed")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
|
||||
// The handler terminates i-denied, the first value, so that is what must be authorized.
|
||||
assertEquals(Decision.DENY, decisionForEveryTarget(policy, "ec2:TerminateInstances",
|
||||
formRequest("Action=TerminateInstances&InstanceId.1=i-denied&InstanceId.1=i-allowed")));
|
||||
}
|
||||
|
||||
private Decision decisionForEveryTarget(String policy, String action, ContainerRequestContext request) {
|
||||
Decision first = evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
resolver.resolve("ec2", action, request));
|
||||
if (first == Decision.DENY) {
|
||||
return first;
|
||||
}
|
||||
for (Map<String, List<String>> target : resolver.resolveRemainingTargets("ec2", action, request)) {
|
||||
if (evaluator.simulateCustomPolicy(List.of(policy), action, "*", target) == Decision.DENY) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
}
|
||||
return Decision.ALLOW;
|
||||
}
|
||||
}
|
||||
@@ -253,6 +253,91 @@ class IamEnforcementFilterTest {
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterPassesEc2ResourceTagConditionContextAndHonoursTheDeny() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
Map<String, List<String>> conditions = Map.of("aws:ResourceTag/Team", List.of("engineering"));
|
||||
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIATAGGED/20260907/us-east-1/ec2/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("222233334444");
|
||||
requestContext.setRegion("us-east-1");
|
||||
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIATAGGED");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("ec2", containerRequest)).thenReturn("ec2:TerminateInstances");
|
||||
when(iamService.resolveCallerContext("AKIATAGGED"))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}}
|
||||
]}""")));
|
||||
when(conditionContextResolver.resolve("ec2", "ec2:TerminateInstances", containerRequest))
|
||||
.thenReturn(conditions);
|
||||
when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(conditions)))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(evaluator).evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(conditions));
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterDeniesWhenALaterTargetOfAMultiResourceRequestFailsThePolicy() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
Map<String, List<String>> first = Map.of("aws:ResourceTag/Team", List.of("payments"));
|
||||
Map<String, List<String>> second = Map.of("aws:ResourceTag/Team", List.of("engineering"));
|
||||
stubTaggedTerminate(containerRequest, first, List.of(second));
|
||||
when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(first)))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(second)))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(evaluator).evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(second));
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterAllowsAMultiResourceRequestWhenEveryTargetPassesThePolicy() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
Map<String, List<String>> first = Map.of("aws:ResourceTag/Team", List.of("payments"));
|
||||
Map<String, List<String>> second = Map.of("aws:ResourceTag/Team", List.of("payments"));
|
||||
stubTaggedTerminate(containerRequest, first, List.of(second));
|
||||
when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(evaluator, org.mockito.Mockito.times(2))
|
||||
.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), any());
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
private void stubTaggedTerminate(ContainerRequestContext containerRequest,
|
||||
Map<String, List<String>> first,
|
||||
List<Map<String, List<String>>> remaining) {
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIATAGGED/20260907/us-east-1/ec2/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("222233334444");
|
||||
requestContext.setRegion("us-east-1");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIATAGGED");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("ec2", containerRequest)).thenReturn("ec2:TerminateInstances");
|
||||
when(iamService.resolveCallerContext("AKIATAGGED"))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}}
|
||||
]}""")));
|
||||
when(conditionContextResolver.resolve("ec2", "ec2:TerminateInstances", containerRequest))
|
||||
.thenReturn(first);
|
||||
when(conditionContextResolver.resolveRemainingTargets("ec2", "ec2:TerminateInstances", containerRequest))
|
||||
.thenReturn(remaining);
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterPassesS3ListBucketConditionContext() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
|
||||
+110
@@ -1,16 +1,29 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import jakarta.inject.Inject;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Unit-style tests for the IAM enforcement engine components:
|
||||
@@ -25,6 +38,15 @@ class IamEnforcementIntegrationTest {
|
||||
@Inject
|
||||
IamPolicyEvaluator evaluator;
|
||||
|
||||
@Inject
|
||||
IamConditionContextResolver conditionContextResolver;
|
||||
|
||||
@Inject
|
||||
Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
// =========================================================================
|
||||
// IamPolicyEvaluator — basic allow / deny / implicit-deny
|
||||
// =========================================================================
|
||||
@@ -232,4 +254,92 @@ class IamEnforcementIntegrationTest {
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
|
||||
Map.of("dynamodb:LeadingKeys", List.of("USER_bob"))));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// aws:ResourceTag and aws:RequestTag, resolved from live EC2 and S3 state
|
||||
// =========================================================================
|
||||
|
||||
private static final String TEAM_SCOPED_EC2_POLICY = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:DeleteTags","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}}
|
||||
]}""";
|
||||
|
||||
private static final String OWNER_SCOPED_S3_POLICY = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetBucketTagging","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"alice"}}}
|
||||
]}""";
|
||||
|
||||
@Test
|
||||
void resourceTagConditionFollowsTheTagsEc2ActuallyHoldsForTheResource() {
|
||||
Vpc tagged = ec2Service.createVpc("us-east-1", "10.42.0.0/16", false);
|
||||
Vpc other = ec2Service.createVpc("us-east-1", "10.43.0.0/16", false);
|
||||
ec2Service.createTags("us-east-1", List.of(tagged.getVpcId()), List.of(new Tag("Team", "payments")));
|
||||
ec2Service.createTags("us-east-1", List.of(other.getVpcId()), List.of(new Tag("Team", "engineering")));
|
||||
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
|
||||
List.of(TEAM_SCOPED_EC2_POLICY), "ec2:DeleteTags", "*",
|
||||
conditionContextResolver.resolve("ec2", "ec2:DeleteTags",
|
||||
ec2Request("Action=DeleteTags&ResourceId.1=" + tagged.getVpcId() + "&Tag.1.Key=Team"))));
|
||||
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
|
||||
List.of(TEAM_SCOPED_EC2_POLICY), "ec2:DeleteTags", "*",
|
||||
conditionContextResolver.resolve("ec2", "ec2:DeleteTags",
|
||||
ec2Request("Action=DeleteTags&ResourceId.1=" + other.getVpcId() + "&Tag.1.Key=Team"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMultiResourceRequestIsAuthorizedOncePerResource() {
|
||||
Vpc payments = ec2Service.createVpc("us-east-1", "10.44.0.0/16", false);
|
||||
Vpc engineering = ec2Service.createVpc("us-east-1", "10.45.0.0/16", false);
|
||||
ec2Service.createTags("us-east-1", List.of(payments.getVpcId()), List.of(new Tag("Team", "payments")));
|
||||
ec2Service.createTags("us-east-1", List.of(engineering.getVpcId()), List.of(new Tag("Team", "engineering")));
|
||||
String mixed = "Action=DeleteTags&ResourceId.1=" + payments.getVpcId()
|
||||
+ "&ResourceId.2=" + engineering.getVpcId() + "&Tag.1.Key=Team";
|
||||
|
||||
// The permitted resource comes first, yet the second target still fails the policy.
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
|
||||
List.of(TEAM_SCOPED_EC2_POLICY), "ec2:DeleteTags", "*",
|
||||
conditionContextResolver.resolve("ec2", "ec2:DeleteTags", ec2Request(mixed))));
|
||||
List<Map<String, List<String>>> remaining =
|
||||
conditionContextResolver.resolveRemainingTargets("ec2", "ec2:DeleteTags", ec2Request(mixed));
|
||||
assertEquals(1, remaining.size());
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
|
||||
List.of(TEAM_SCOPED_EC2_POLICY), "ec2:DeleteTags", "*", remaining.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceTagConditionFollowsTheTagsS3ActuallyHoldsForTheBucket() {
|
||||
String alices = "iam-tag-ctx-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String bobs = "iam-tag-ctx-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
s3Service.createBucket(alices, "us-east-1");
|
||||
s3Service.createBucket(bobs, "us-east-1");
|
||||
s3Service.putBucketTagging(alices, Map.of("Owner", "alice"));
|
||||
s3Service.putBucketTagging(bobs, Map.of("Owner", "bob"));
|
||||
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
|
||||
List.of(OWNER_SCOPED_S3_POLICY), "s3:GetBucketTagging", "arn:aws:s3:::" + alices,
|
||||
conditionContextResolver.resolve("s3", "s3:GetBucketTagging", s3Request("/" + alices))));
|
||||
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
|
||||
List.of(OWNER_SCOPED_S3_POLICY), "s3:GetBucketTagging", "arn:aws:s3:::" + bobs,
|
||||
conditionContextResolver.resolve("s3", "s3:GetBucketTagging", s3Request("/" + bobs))));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext ec2Request(String form) {
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
when(request.getMediaType()).thenReturn(MediaType.valueOf("application/x-www-form-urlencoded"));
|
||||
when(request.getEntityStream())
|
||||
.thenReturn(new ByteArrayInputStream(form.getBytes(StandardCharsets.UTF_8)));
|
||||
return request;
|
||||
}
|
||||
|
||||
private static ContainerRequestContext s3Request(String path) {
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(request.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn(path);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user