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:
lex00 authored and GitHub committed 2026-09-09 00:57:40 -05:00
1 parent 5b7c2c4a62
commit 64538f7d32
7 files changed
+797 -3

No files matched your search

+8
View File
@@ -408,6 +408,14 @@ A `Condition` operator can only match a key floci actually places in the request
floci populates:
- `s3:prefix`, `s3:delimiter`, `s3:max-keys`: from the S3 request parameters.
- `aws:RequestTag/<key>`: the tags named in the request itself, before they are applied, for
`ec2:RunInstances` (`TagSpecification.N`), `ec2:CreateTags` (`Tag.N`) and
`s3:PutBucketTagging` (the `<Tagging>` body).
- `aws:ResourceTag/<key>`: the target resource's current tags, for `ec2:CreateTags`,
`ec2:DeleteTags`, `ec2:TerminateInstances` and `ec2:DescribeInstances` (the first
`ResourceId.N` or `InstanceId.N`), and for `s3:GetBucketTagging`, `s3:DeleteBucketTagging`
and `s3:DeleteBucket` (the bucket). A request naming several EC2 resources is evaluated
once per resource and denied when any of them fails the condition, as on AWS.
- `aws:PrincipalArn`: the caller's ARN, resolved from the signing access key. It is the
IAM-user ARN for a user access key, the assumed-role ARN for an STS session, and
`arn:aws:iam::<account>:root` for the bare account-id key (floci's account-root principal),
@@ -5,12 +5,24 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbConditionKeys;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
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.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -18,22 +30,43 @@ import java.util.Map;
/**
* Builds the IAM request context: the condition keys a policy's Condition block can match,
* for the request currently being enforced.
*
* <p>Two keys are generic across services and populated the same way wherever they apply:
* <ul>
* <li>{@code aws:RequestTag/<key>}, a tag the caller asks to attach, read from the request
* before the operation is applied.</li>
* <li>{@code aws:ResourceTag/<key>}, a tag already on the target resource, read from current
* state. {@link #resolve} carries the first target's tags and
* {@link #resolveRemainingTargets} one context per further target, so the filter can
* require the policy to hold for every resource the request names, as AWS does.</li>
* </ul>
*/
@ApplicationScoped
public class IamConditionContextResolver {
private static final Logger LOG = Logger.getLogger(IamConditionContextResolver.class);
/** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */
private static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody";
private static final String BUFFERED_FORM_BODY = "floci.bufferedFormBody";
private static final String REQUEST_TAG_PREFIX = "aws:RequestTag/";
private static final String RESOURCE_TAG_PREFIX = "aws:ResourceTag/";
private final Instance<DynamoDbService> dynamoDbService;
private final Instance<Ec2Service> ec2Service;
private final Instance<S3Service> s3Service;
private final RequestContext requestContext;
private final EmulatorConfig config;
@Inject
public IamConditionContextResolver(Instance<DynamoDbService> dynamoDbService,
Instance<Ec2Service> ec2Service,
Instance<S3Service> s3Service,
RequestContext requestContext,
EmulatorConfig config) {
this.dynamoDbService = dynamoDbService;
this.ec2Service = ec2Service;
this.s3Service = s3Service;
this.requestContext = requestContext;
this.config = config;
}
@@ -42,6 +75,7 @@ public class IamConditionContextResolver {
ContainerRequestContext ctx) {
return switch (credentialScope) {
case "s3" -> s3ConditionContext(action, ctx);
case "ec2" -> ec2ConditionContext(action, ctx);
case "dynamodb" -> dynamoDbConditionContext(action, ctx);
default -> null;
};
@@ -52,6 +86,9 @@ public class IamConditionContextResolver {
private Map<String, List<String>> s3ConditionContext(String action, ContainerRequestContext ctx) {
return switch (action) {
case "s3:ListBucket" -> s3BucketListConditionContext(ctx.getUriInfo().getQueryParameters());
case "s3:PutBucketTagging" -> s3PutBucketTaggingConditionContext(ctx);
case "s3:GetBucketTagging", "s3:DeleteBucketTagging", "s3:DeleteBucket" ->
s3BucketResourceTagConditionContext(ctx);
default -> null;
};
}
@@ -72,6 +109,222 @@ public class IamConditionContextResolver {
}
}
/** {@code aws:RequestTag/<key>} from the {@code <Tagging><TagSet>} body of PutBucketTagging. */
private Map<String, List<String>> s3PutBucketTaggingConditionContext(ContainerRequestContext ctx) {
byte[] body = bufferEntity(ctx);
if (body == null || body.length == 0) {
return null;
}
Map<String, String> requested = XmlParser.extractPairs(
new String(body, StandardCharsets.UTF_8), "Tag", "Key", "Value");
Map<String, List<String>> conditions = new LinkedHashMap<>();
requested.forEach((key, value) -> conditions.put(REQUEST_TAG_PREFIX + key, List.of(value)));
return conditions.isEmpty() ? null : conditions;
}
/** {@code aws:ResourceTag/<key>} from the target bucket's current tags. */
private Map<String, List<String>> s3BucketResourceTagConditionContext(ContainerRequestContext ctx) {
String bucket = s3BucketName(ctx.getUriInfo().getPath());
if (bucket == null || !s3Service.isResolvable()) {
return null;
}
Map<String, String> existing;
try {
existing = s3Service.get().getBucketTagging(bucket);
} catch (RuntimeException e) {
// A bucket that does not exist has no tags to offer; the request fails on its own later.
LOG.debugv(e, "Could not read bucket tags for the IAM condition context: {0}", bucket);
return null;
}
if (existing == null || existing.isEmpty()) {
return null;
}
Map<String, List<String>> conditions = new LinkedHashMap<>();
existing.forEach((key, value) -> conditions.put(RESOURCE_TAG_PREFIX + key, List.of(value)));
return conditions;
}
/** Path-style bucket, the same reading {@code ResourceArnBuilder} applies to S3 paths. */
private static String s3BucketName(String path) {
String stripped = path.startsWith("/") ? path.substring(1) : path;
if (stripped.isEmpty()) {
return null;
}
int slash = stripped.indexOf('/');
return slash < 0 ? stripped : stripped.substring(0, slash);
}
// ── EC2 ─────────────────────────────────────────────────────────────────────
private Map<String, List<String>> ec2ConditionContext(String action, ContainerRequestContext ctx) {
return switch (action) {
case "ec2:RunInstances" -> ec2RunInstancesConditionContext(ctx);
case "ec2:CreateTags" -> ec2CreateTagsConditionContext(ctx);
case "ec2:DeleteTags" -> ec2ResourceTagConditionContext(ctx, "ResourceId.1");
case "ec2:TerminateInstances", "ec2:DescribeInstances" ->
ec2ResourceTagConditionContext(ctx, "InstanceId.1");
default -> null;
};
}
/**
* {@code aws:RequestTag/<key>} from every {@code TagSpecification.N.Tag.M} pair. The instance
* does not exist yet, so there is no resource tag to offer.
*/
private Map<String, List<String>> ec2RunInstancesConditionContext(ContainerRequestContext ctx) {
Map<String, String> form = formParameters(ctx);
Map<String, List<String>> conditions = new LinkedHashMap<>();
for (int spec = 1; form.containsKey("TagSpecification." + spec + ".ResourceType"); spec++) {
addRequestTags(conditions, form, "TagSpecification." + spec + ".Tag.");
}
return conditions.isEmpty() ? null : conditions;
}
/**
* CreateTags both requests tags and targets existing resources, so both keys apply: the
* {@code Tag.N} pairs being requested, and each {@code ResourceId.N}'s tags as they are
* before this call. This context carries the first target; the rest come from
* {@link #resolveRemainingTargets}.
*/
private Map<String, List<String>> ec2CreateTagsConditionContext(ContainerRequestContext ctx) {
Map<String, String> form = formParameters(ctx);
Map<String, List<String>> conditions = new LinkedHashMap<>();
addRequestTags(conditions, form, "Tag.");
addResourceTags(conditions, form.get("ResourceId.1"));
return conditions.isEmpty() ? null : conditions;
}
private Map<String, List<String>> ec2ResourceTagConditionContext(ContainerRequestContext ctx,
String idParameter) {
Map<String, List<String>> conditions = new LinkedHashMap<>();
addResourceTags(conditions, formParameters(ctx).get(idParameter));
return conditions.isEmpty() ? null : conditions;
}
/**
* One condition context per target after the first, for the EC2 actions that accept several
* resource ids in one request. An untagged target yields an empty context rather than none,
* so a policy scoped through {@code aws:ResourceTag} fails to match it. Requests naming a
* single target, and every other service, get an empty list.
*/
public List<Map<String, List<String>>> resolveRemainingTargets(String credentialScope, String action,
ContainerRequestContext ctx) {
if (!"ec2".equals(credentialScope)) {
return List.of();
}
String idParameter = switch (action) {
case "ec2:CreateTags", "ec2:DeleteTags" -> "ResourceId.";
case "ec2:TerminateInstances", "ec2:DescribeInstances" -> "InstanceId.";
default -> null;
};
if (idParameter == null) {
return List.of();
}
Map<String, String> form = formParameters(ctx);
List<Map<String, List<String>>> targets = new ArrayList<>();
if (!form.containsKey(idParameter + 1)) {
// The handlers read numbered members from 1 up to the first gap, and so does this.
return targets;
}
for (int i = 2; form.containsKey(idParameter + i); i++) {
Map<String, List<String>> conditions = new LinkedHashMap<>();
if ("ec2:CreateTags".equals(action)) {
addRequestTags(conditions, form, "Tag.");
}
addResourceTags(conditions, form.get(idParameter + i));
targets.add(conditions);
}
return targets;
}
private static void addRequestTags(Map<String, List<String>> conditions, Map<String, String> form,
String prefix) {
for (int i = 1; form.containsKey(prefix + i + ".Key"); i++) {
String value = form.get(prefix + i + ".Value");
conditions.put(REQUEST_TAG_PREFIX + form.get(prefix + i + ".Key"),
List.of(value == null ? "" : value));
}
}
private void addResourceTags(Map<String, List<String>> conditions, String resourceId) {
if (resourceId == null || resourceId.isBlank() || !ec2Service.isResolvable()) {
return;
}
for (Tag tag : ec2Service.get().resourceTags(resourceId)) {
conditions.put(RESOURCE_TAG_PREFIX + tag.getKey(),
List.of(tag.getValue() == null ? "" : tag.getValue()));
}
}
// ── Request body access ─────────────────────────────────────────────────────
/**
* The decoded form parameters of a Query-protocol request, buffered once per request and
* restored for the controller that reads the form next. A repeated key keeps its first
* value, which is the value the Query handlers read through {@code getFirst}, so the
* resource this context describes is the resource the handler acts on.
*/
@SuppressWarnings("unchecked")
private static Map<String, String> formParameters(ContainerRequestContext ctx) {
Object cached = ctx.getProperty(BUFFERED_FORM_BODY);
if (cached instanceof Map<?, ?> map) {
return (Map<String, String>) map;
}
MediaType mediaType = ctx.getMediaType();
if (mediaType == null
|| !"application".equalsIgnoreCase(mediaType.getType())
|| !"x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype())) {
return Map.of();
}
byte[] body = bufferEntity(ctx);
if (body == null || body.length == 0) {
return Map.of();
}
Charset charset = charsetOf(mediaType);
Map<String, String> parameters = new LinkedHashMap<>();
for (String pair : new String(body, charset).split("&")) {
if (pair.isEmpty()) {
continue;
}
int eq = pair.indexOf('=');
String key = eq < 0 ? pair : pair.substring(0, eq);
String value = eq < 0 ? "" : pair.substring(eq + 1);
parameters.putIfAbsent(URLDecoder.decode(key, charset), URLDecoder.decode(value, charset));
}
ctx.setProperty(BUFFERED_FORM_BODY, parameters);
return parameters;
}
/** Reads the entity fully and puts an equivalent stream back for downstream readers. */
private static byte[] bufferEntity(ContainerRequestContext ctx) {
InputStream in = ctx.getEntityStream();
if (in == null) {
return null;
}
byte[] body;
try {
body = in.readAllBytes();
} catch (IOException e) {
LOG.debugv(e, "Failed to buffer the request body for the IAM condition context");
ctx.setEntityStream(new ByteArrayInputStream(new byte[0]));
return null;
}
ctx.setEntityStream(new ByteArrayInputStream(body));
return body;
}
private static Charset charsetOf(MediaType mediaType) {
String name = mediaType.getParameters().get("charset");
if (name == null || name.isBlank()) {
return StandardCharsets.UTF_8;
}
try {
return Charset.forName(name);
} catch (RuntimeException e) {
return StandardCharsets.UTF_8;
}
}
// ── DynamoDB ────────────────────────────────────────────────────────────────
/**
@@ -20,6 +20,7 @@ import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -172,6 +173,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
List<String> resources = arnBuilder.buildResources(credentialScope, ctx, region, accountId);
Map<String, List<String>> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx);
// A request naming several resources is authorized once per resource, as on AWS, so a
// permitted first target cannot carry later targets that the policy does not allow.
List<Map<String, List<String>>> remainingTargets =
conditionContextResolver.resolveRemainingTargets(credentialScope, action, ctx);
// aws:PrincipalArn is populated for every principal this filter can identify — IAM users,
// assumed-role sessions, and now the synthesized account-root principal above, using AWS's
@@ -186,10 +191,20 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));
}
List<Map<String, List<String>>> targetContexts = new ArrayList<>();
targetContexts.add(conditionContext);
for (Map<String, List<String>> target : remainingTargets) {
Map<String, List<String>> targetContext = new HashMap<>(target);
principalArn.ifPresent(arn -> targetContext.put("aws:PrincipalArn", List.of(arn)));
targetContexts.add(targetContext);
}
for (String resource : resources) {
Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext);
if (decision == Decision.DENY) {
for (Map<String, List<String>> targetContext : targetContexts) {
Decision decision = evaluator.evaluate(caller, null, action, resource, targetContext);
if (decision != Decision.DENY) {
continue;
}
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
String denyMessage = "User: arn:aws:iam::" + accountId
+ ":user/" + akid + " is not authorized to perform: " + action
@@ -4888,6 +4888,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
}
/** The tags currently on one resource, as CreateTags and DeleteTags maintain them. */
public List<Tag> resourceTags(String resourceId) {
return List.copyOf(tags.get(resourceId).orElse(List.of()));
}
public List<Map<String, String>> describeTags(String region, Map<String, List<String>> filters) {
ensureDefaultResources(region);
List<String> filterResourceIds = filters != null ? filters.get("resource-id") : null;
@@ -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);
@@ -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;
}
}