mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): evaluate policies against real request resources and conditions (#3765)
* fix(iam): evaluate real request resources and S3 sub-resource actions * fix(iam): add global context to managed policy evaluation
This commit is contained in:
1 parent
1d009b9614
commit
33a95e92f2
9 files changed
+555
-174
No files matched your search
+45
@@ -488,6 +488,51 @@ class IamConditionContextResolverTest {
|
||||
formRequest("Action=TerminateInstances&InstanceId.1=i-denied&InstanceId.1=i-allowed")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalKeysArePopulatedForEveryServiceAndAction() {
|
||||
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
|
||||
null, "arn:aws:lambda:eu-west-2:000000000000:function:task", "eu-west-2",
|
||||
"000000000000", "000000000000");
|
||||
|
||||
assertEquals(List.of("000000000000"), conditions.get("aws:ResourceAccount"));
|
||||
assertEquals(List.of("000000000000"), conditions.get("aws:PrincipalAccount"));
|
||||
assertEquals(List.of("eu-west-2"), conditions.get("aws:RequestedRegion"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceAccountComesFromTheResourceArnWhenItCarriesOne() {
|
||||
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
|
||||
Map.of("service:key", List.of("value")),
|
||||
"arn:aws:sqs:eu-west-2:111111111111:queue", "eu-west-2", "000000000000", "000000000000");
|
||||
|
||||
assertEquals(List.of("111111111111"), conditions.get("aws:ResourceAccount"));
|
||||
assertEquals(List.of("value"), conditions.get("service:key"));
|
||||
assertFalse(conditions.containsKey("aws:SecureTransport"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceAccountIsTheBucketOwnerWhenAnS3ArnCarriesNoAccount() {
|
||||
// S3 bucket and object ARNs have an empty account segment by design, so the owner has to
|
||||
// come from service state. Falling back to the caller would make a cross-account bucket
|
||||
// look like the caller's own.
|
||||
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
|
||||
null, "arn:aws:s3:::partner-bucket/report.csv", "eu-west-2",
|
||||
"000000000000", "111111111111");
|
||||
|
||||
assertEquals(List.of("111111111111"), conditions.get("aws:ResourceAccount"));
|
||||
assertEquals(List.of("000000000000"), conditions.get("aws:PrincipalAccount"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceAccountIsOmittedWhenNeitherTheArnNorServiceStateKnowsTheOwner() {
|
||||
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
|
||||
null, "arn:aws:s3:::orphan-bucket", "eu-west-2", "000000000000", null);
|
||||
|
||||
assertFalse(conditions.containsKey("aws:ResourceAccount"),
|
||||
"guessing the owner would authorize cross-account access a Condition meant to refuse");
|
||||
assertEquals(List.of("000000000000"), conditions.get("aws:PrincipalAccount"));
|
||||
}
|
||||
|
||||
private Decision decisionForEveryTarget(String policy, String action, ContainerRequestContext request) {
|
||||
Decision first = evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
resolver.resolve("ec2", action, request));
|
||||
|
||||
+96
-13
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicy
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
@@ -203,7 +204,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("dynamodb:BatchGetItem"),
|
||||
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
|
||||
isNull()))
|
||||
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
@@ -211,7 +212,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("dynamodb:BatchGetItem"),
|
||||
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
|
||||
isNull()))
|
||||
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest))
|
||||
.thenReturn(null);
|
||||
@@ -225,14 +226,14 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("dynamodb:BatchGetItem"),
|
||||
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
|
||||
isNull());
|
||||
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000")));
|
||||
verify(evaluator).evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
eq(ResourcePolicyDecision.NEUTRAL),
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("dynamodb:BatchGetItem"),
|
||||
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
|
||||
isNull());
|
||||
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000")));
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@@ -261,7 +262,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("dynamodb:BatchGetItem"),
|
||||
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
|
||||
isNull()))
|
||||
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
@@ -269,7 +270,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("dynamodb:BatchGetItem"),
|
||||
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
|
||||
isNull()))
|
||||
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest))
|
||||
.thenReturn(null);
|
||||
@@ -326,7 +327,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("ec2:TerminateInstances"),
|
||||
eq("*"),
|
||||
eq(conditions)))
|
||||
eq(globalContext(conditions, "*", "222233334444"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
@@ -337,7 +338,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("ec2:TerminateInstances"),
|
||||
eq("*"),
|
||||
eq(conditions));
|
||||
eq(globalContext(conditions, "*", "222233334444")));
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
@@ -353,7 +354,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("ec2:TerminateInstances"),
|
||||
eq("*"),
|
||||
eq(first)))
|
||||
eq(globalContext(first, "*", "222233334444"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
@@ -361,7 +362,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("ec2:TerminateInstances"),
|
||||
eq("*"),
|
||||
eq(second)))
|
||||
eq(globalContext(second, "*", "222233334444"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
@@ -372,7 +373,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("ec2:TerminateInstances"),
|
||||
eq("*"),
|
||||
eq(second));
|
||||
eq(globalContext(second, "*", "222233334444")));
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
@@ -404,6 +405,15 @@ class IamEnforcementFilterTest {
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
// These cases stub no resource policy, so the filter resolves no owner and passes null. Where
|
||||
// the ARN carries an account the key is still populated from it; where it does not, such as an
|
||||
// S3 bucket ARN or a bare "*", the key is correctly absent rather than defaulted to the caller.
|
||||
private static Map<String, List<String>> globalContext(Map<String, List<String>> serviceContext,
|
||||
String resourceArn, String accountId) {
|
||||
return IamConditionContextResolver.withGlobalContext(
|
||||
serviceContext, resourceArn, "us-east-1", accountId, null);
|
||||
}
|
||||
|
||||
private void stubTaggedTerminate(ContainerRequestContext containerRequest,
|
||||
Map<String, List<String>> first,
|
||||
List<Map<String, List<String>>> remaining) {
|
||||
@@ -454,7 +464,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("s3:ListBucket"),
|
||||
eq("arn:aws:s3:::bucket"),
|
||||
eq(conditions)))
|
||||
eq(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444"))))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
|
||||
IamEnforcementFilter filter = newFilter();
|
||||
@@ -467,7 +477,7 @@ class IamEnforcementFilterTest {
|
||||
eq(ResourceAccountRelationship.SAME_ACCOUNT),
|
||||
eq("s3:ListBucket"),
|
||||
eq("arn:aws:s3:::bucket"),
|
||||
eq(conditions));
|
||||
eq(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1007,4 +1017,77 @@ class IamEnforcementFilterTest {
|
||||
}
|
||||
return entity.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3ResourceAccountIsTheBucketOwnerNotTheCallerOnCrossAccountAccess() {
|
||||
// An S3 bucket ARN carries no account, so aws:ResourceAccount has to come from S3 state.
|
||||
// The caller is 222233334444 and the bucket belongs to 111111111111; a policy conditioned
|
||||
// on aws:ResourceAccount must see the owner, not the caller.
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
Map<String, List<String>> conditions = Map.of("s3:prefix", List.of("shared/"));
|
||||
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIACROSS/20260706/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("222233334444");
|
||||
requestContext.setRegion("us-east-1");
|
||||
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIACROSS");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:ListBucket");
|
||||
when(iamService.resolveCallerContext("ASIACROSS"))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
.thenReturn(List.of("arn:aws:s3:::partner-bucket"));
|
||||
when(conditionContextResolver.resolve("s3", "s3:ListBucket", containerRequest))
|
||||
.thenReturn(conditions);
|
||||
|
||||
Map<String, List<String>> expected = IamConditionContextResolver.withGlobalContext(
|
||||
conditions, "arn:aws:s3:::partner-bucket", "us-east-1", "222233334444", "111111111111");
|
||||
assertEquals(List.of("111111111111"), expected.get("aws:ResourceAccount"));
|
||||
|
||||
when(evaluator.evaluateResourcePolicy(any(), any(), anyString(), anyString(), any()))
|
||||
.thenReturn(ResourcePolicyDecision.NEUTRAL);
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
eq(ResourcePolicyDecision.NEUTRAL),
|
||||
eq(ResourceAccountRelationship.CROSS_ACCOUNT),
|
||||
eq("s3:ListBucket"),
|
||||
eq("arn:aws:s3:::partner-bucket"),
|
||||
eq(expected)))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
|
||||
filterWithBucketOwner("111111111111").filter(containerRequest);
|
||||
|
||||
verify(evaluator).evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
eq(ResourcePolicyDecision.NEUTRAL),
|
||||
eq(ResourceAccountRelationship.CROSS_ACCOUNT),
|
||||
eq("s3:ListBucket"),
|
||||
eq("arn:aws:s3:::partner-bucket"),
|
||||
eq(expected));
|
||||
}
|
||||
|
||||
/** Builds a filter whose only resource-policy provider reports the given bucket owner. */
|
||||
private IamEnforcementFilter filterWithBucketOwner(String ownerAccountId) {
|
||||
ResourcePolicyProvider provider = (scope, arn) ->
|
||||
List.of(new ResourcePolicyProvider.ResourcePolicy(null, ownerAccountId));
|
||||
@SuppressWarnings("unchecked")
|
||||
jakarta.enterprise.inject.Instance<ResourcePolicyProvider> providers =
|
||||
mock(jakarta.enterprise.inject.Instance.class);
|
||||
when(providers.isUnsatisfied()).thenReturn(false);
|
||||
when(providers.iterator()).thenReturn(List.of(provider).iterator());
|
||||
@SuppressWarnings("unchecked")
|
||||
jakarta.enterprise.inject.Instance<io.github.hectorvent.floci.services.iam.ScpProvider> scpProvider =
|
||||
mock(jakarta.enterprise.inject.Instance.class);
|
||||
when(scpProvider.isResolvable()).thenReturn(false);
|
||||
return new IamEnforcementFilter(
|
||||
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
|
||||
requestContext, conditionContextResolver,
|
||||
mock(CloudTrailService.class),
|
||||
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup, providers);
|
||||
}
|
||||
}
|
||||
@@ -176,18 +176,15 @@ class IamActionRegistryTest {
|
||||
|
||||
@Test
|
||||
void s3AccelerateYieldsToSubresourcesDispatchedFirst() {
|
||||
// The controller executes the requestPayment operation for this request, so the
|
||||
// accelerate mapping must not claim it; resolution falls back to the rule table,
|
||||
// exactly like a plain ?requestPayment request today.
|
||||
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
|
||||
withRequestPayment.add("requestPayment", "");
|
||||
withRequestPayment.add("accelerate", "");
|
||||
assertEquals("s3:CreateBucket",
|
||||
assertEquals("s3:PutBucketRequestPayment",
|
||||
registry.resolve("s3", mockCtx("PUT", "/bucket", withRequestPayment, null, "")));
|
||||
MultivaluedMap<String, String> withLocation = new MultivaluedHashMap<>();
|
||||
withLocation.add("location", "");
|
||||
withLocation.add("accelerate", "");
|
||||
assertEquals("s3:ListBucket",
|
||||
assertEquals("s3:GetBucketLocation",
|
||||
registry.resolve("s3", mockCtx("GET", "/bucket", withLocation, null, "")));
|
||||
// uploads is a GET-only dispatch branch; on PUT it is inert and accelerate executes,
|
||||
// so the mapping must still claim the request there.
|
||||
@@ -230,23 +227,22 @@ class IamActionRegistryTest {
|
||||
|
||||
@Test
|
||||
void s3ReplicationYieldsToSubresourcesDispatchedFirst() {
|
||||
// The controller executes the requestPayment operation for this request, so the
|
||||
// replication mapping must not claim it; resolution falls back to the rule table.
|
||||
// The first dispatched subresource determines the required permission.
|
||||
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
|
||||
withRequestPayment.add("requestPayment", "");
|
||||
withRequestPayment.add("replication", "");
|
||||
assertEquals("s3:CreateBucket",
|
||||
assertEquals("s3:PutBucketRequestPayment",
|
||||
registry.resolve("s3", mockCtx("PUT", "/bucket", withRequestPayment, null, "")));
|
||||
MultivaluedMap<String, String> withLocation = new MultivaluedHashMap<>();
|
||||
withLocation.add("location", "");
|
||||
withLocation.add("replication", "");
|
||||
assertEquals("s3:ListBucket",
|
||||
assertEquals("s3:GetBucketLocation",
|
||||
registry.resolve("s3", mockCtx("GET", "/bucket", withLocation, null, "")));
|
||||
// The DELETE chain dispatches website ahead of replication.
|
||||
MultivaluedMap<String, String> withWebsite = new MultivaluedHashMap<>();
|
||||
withWebsite.add("website", "");
|
||||
withWebsite.add("replication", "");
|
||||
assertEquals("s3:DeleteBucket",
|
||||
assertEquals("s3:DeleteBucketWebsite",
|
||||
registry.resolve("s3", mockCtx("DELETE", "/bucket", withWebsite, null, "")));
|
||||
// requestPayment has no DELETE dispatch branch; it is inert there and
|
||||
// replication executes, so the mapping must still claim the request.
|
||||
@@ -309,6 +305,67 @@ class IamActionRegistryTest {
|
||||
registry.resolve("s3", mockCtx("DELETE", "/bucket/key.txt", withTagging, null, "")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketSubResourceWritesResolveToTheirOwnActionNotCreateBucket() {
|
||||
// The live failure: CDK's BucketNotificationsHandler role grants s3:PutBucketNotification
|
||||
// on "*", exactly what real AWS requires, and the deploy died on
|
||||
// "not authorized to perform: s3:CreateBucket" because method + path alone decided.
|
||||
assertEquals("s3:PutBucketNotification", bucketAction("PUT", "notification"));
|
||||
assertEquals("s3:GetBucketNotification", bucketAction("GET", "notification"));
|
||||
|
||||
assertEquals("s3:PutBucketPolicy", bucketAction("PUT", "policy"));
|
||||
assertEquals("s3:PutBucketVersioning", bucketAction("PUT", "versioning"));
|
||||
assertEquals("s3:PutEncryptionConfiguration", bucketAction("PUT", "encryption"));
|
||||
assertEquals("s3:PutLifecycleConfiguration", bucketAction("PUT", "lifecycle"));
|
||||
assertEquals("s3:PutBucketCORS", bucketAction("PUT", "cors"));
|
||||
assertEquals("s3:PutBucketPublicAccessBlock", bucketAction("PUT", "publicAccessBlock"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketSubResourceReadsResolveToTheirOwnActionNotListBucket() {
|
||||
assertEquals("s3:GetBucketLocation", bucketAction("GET", "location"));
|
||||
assertEquals("s3:GetBucketVersioning", bucketAction("GET", "versioning"));
|
||||
assertEquals("s3:ListBucketVersions", bucketAction("GET", "versions"));
|
||||
assertEquals("s3:ListBucketMultipartUploads", bucketAction("GET", "uploads"));
|
||||
assertEquals("s3:GetBucketPolicy", bucketAction("GET", "policy"));
|
||||
assertEquals("s3:GetLifecycleConfiguration", bucketAction("GET", "lifecycle"));
|
||||
assertEquals("s3:GetEncryptionConfiguration", bucketAction("GET", "encryption"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketSubResourceDeletesDoNotDemandDeleteBucket() {
|
||||
// Removing a CORS rule asked for permission to delete the whole bucket. AWS authorises
|
||||
// most sub-resource removals with the same Put* action that sets them; only policy and
|
||||
// website have their own Delete action.
|
||||
assertEquals("s3:PutBucketCORS", bucketAction("DELETE", "cors"));
|
||||
assertEquals("s3:PutLifecycleConfiguration", bucketAction("DELETE", "lifecycle"));
|
||||
assertEquals("s3:PutEncryptionConfiguration", bucketAction("DELETE", "encryption"));
|
||||
assertEquals("s3:PutReplicationConfiguration", bucketAction("DELETE", "replication"));
|
||||
assertEquals("s3:DeleteBucketPolicy", bucketAction("DELETE", "policy"));
|
||||
assertEquals("s3:DeleteBucketWebsite", bucketAction("DELETE", "website"));
|
||||
// A plain DELETE with no sub-resource still deletes the bucket.
|
||||
assertEquals("s3:DeleteBucket",
|
||||
registry.resolve("s3", mockCtx("DELETE", "/bucket", new MultivaluedHashMap<>(), null, "")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketOnlySubResourcesStayInertOnAnObjectPath() {
|
||||
// ?notification on an object path is ignored by the object routes, so the request really
|
||||
// is a GetObject/PutObject and must resolve as one.
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("notification", "");
|
||||
assertEquals("s3:GetObject",
|
||||
registry.resolve("s3", mockCtx("GET", "/bucket/key.txt", params, null, "")));
|
||||
assertEquals("s3:PutObject",
|
||||
registry.resolve("s3", mockCtx("PUT", "/bucket/key.txt", params, null, "")));
|
||||
}
|
||||
|
||||
private String bucketAction(String method, String subResource) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add(subResource, "");
|
||||
return registry.resolve("s3", mockCtx(method, "/bucket", params, null, ""));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private static ContainerRequestContext mockCtx(String method, String path,
|
||||
|
||||
+10
-1
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
@@ -14,6 +15,7 @@ import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -296,7 +298,14 @@ class IamManagedPolicyAccountScopeTest {
|
||||
assertTrue(caller.identityPolicies().stream()
|
||||
.anyMatch(document -> document.contains("logs:CreateLogGroup")));
|
||||
assertTrue(caller.boundaryPolicyDocument().contains("NotAction"));
|
||||
assertFalse(caller.boundaryPolicyDocument().contains("\"Action\":\"*\""));
|
||||
assertFalse(caller.boundaryPolicyDocument().contains("\"Action\":\"*\"")); IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
|
||||
String logArn = "arn:aws:logs:us-east-1:" + REQUEST_ACCT + ":log-group:/aws/lambda/task-role:*";
|
||||
for (String action : List.of("logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents")) {
|
||||
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
|
||||
evaluator.evaluate(caller, List.of(), action, logArn, Map.of()));
|
||||
}
|
||||
assertEquals(IamPolicyEvaluator.Decision.DENY,
|
||||
evaluator.evaluate(caller, List.of(), "s3:GetObject", "arn:aws:s3:::private-bucket/key", Map.of()));
|
||||
}
|
||||
/**
|
||||
* The alias is the only IAM entity keyed by a constant rather than a caller-supplied name, so
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(LambdaExecutionRoleIamEnforcementIntegrationTest.IamEnforcementProfile.class)
|
||||
class LambdaScopedTablePermissionIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials;
|
||||
|
||||
@Test
|
||||
void executionRoleCanUseOnlyItsGrantedTableAndRequestBodySurvivesAuthorization() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String tableName = "granted-table-" + suffix;
|
||||
String roleName = "ScopedTableRole" + suffix;
|
||||
String tableArn = "arn:aws:dynamodb:" + REGION + ":" + ACCOUNT_ID + ":table/" + tableName;
|
||||
given().config(io.restassured.RestAssured.config().encoderConfig(
|
||||
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
|
||||
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
|
||||
.header("Authorization", auth("test"))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("""
|
||||
{"TableName":"%s","KeySchema":[{"AttributeName":"id","KeyType":"HASH"}],
|
||||
"AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"}],
|
||||
"BillingMode":"PAY_PER_REQUEST"}
|
||||
""".formatted(tableName))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
iamService.createRole(roleName, "/", "{}", null, 3600, null);
|
||||
iamService.putRolePolicy(roleName, "TableAccess", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":["dynamodb:PutItem","dynamodb:GetItem"],"Resource":"%s"}]}
|
||||
""".formatted(tableArn));
|
||||
LambdaFunction function = new LambdaFunction();
|
||||
function.setFunctionName("scoped-table-" + suffix);
|
||||
function.setAccountId(ACCOUNT_ID);
|
||||
function.setRole("arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName);
|
||||
SessionCreds credentials = executionRoleCredentials.forFunction(function).orElseThrow();
|
||||
try {
|
||||
given().config(io.restassured.RestAssured.config().encoderConfig(
|
||||
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
|
||||
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
|
||||
.header("Authorization", auth(credentials.accessKeyId()))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("""
|
||||
{"TableName":"%s","Item":{"id":{"S":"record"},"value":{"S":"persisted"}}}
|
||||
""".formatted(tableName))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
given().config(io.restassured.RestAssured.config().encoderConfig(
|
||||
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
|
||||
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
|
||||
.header("Authorization", auth(credentials.accessKeyId()))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("""
|
||||
{"TableName":"%s","Key":{"id":{"S":"record"}}}
|
||||
""".formatted(tableName))
|
||||
.when().post("/")
|
||||
.then().statusCode(200).body(containsString("persisted"));
|
||||
|
||||
given().config(io.restassured.RestAssured.config().encoderConfig(
|
||||
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
|
||||
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
|
||||
.header("Authorization", auth(credentials.accessKeyId()))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("""
|
||||
{"TableName":"not-granted-%s","Key":{"id":{"S":"record"}}}
|
||||
""".formatted(suffix))
|
||||
.when().post("/")
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
} finally {
|
||||
executionRoleCredentials.unregister(ACCOUNT_ID, credentials.accessKeyId());
|
||||
iamService.deleteRolePolicy(roleName, "TableAccess");
|
||||
iamService.deleteRole(roleName);
|
||||
}
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260910/" + REGION
|
||||
+ "/dynamodb/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user