mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): enforce STS session policies (#1636)
* test(iam): expose STS session policy S3 deny gap * fix(iam): enforce STS session policies ## Summary STS session policies were recorded on temporary credentials but IAM enforcement evaluated only the caller's identity policies. As a result, an assumed role with broad role permissions could still perform an action even when the inline `AssumeRole` session policy should have denied or narrowed it. This changes enforcement to evaluate the full caller context, including identity policies, session policies, and permission boundaries. It also keeps temporary-credential lookup account-independent so assumed-role sessions can be resolved after account routing moves the request into the role account, and it uses the resolved request account when building resource ARNs for policy evaluation. ## Type of change - [x] Bug fix (`fix:`) ## AWS Compatibility Incorrect behavior: STS `AssumeRole` accepted the standard inline `Policy` parameter, but later requests signed with those temporary credentials did not have that session policy applied by IAM enforcement. The fix matches AWS policy evaluation semantics: explicit denies in session policies participate in the deny pass, and a present session policy must also explicitly allow the request for the role's permissions to be effective. This preserves the existing Floci bypass behavior for unknown local credentials and the `test` root credential. ## What changed - `IamEnforcementFilter` resolves a `CallerContext` and evaluates the complete IAM context instead of identity-policy documents only. - `IamService` resolves STS sessions across account namespaces for caller context, caller ARN, account routing, and temporary secret lookup. - Enforcement resource ARN construction uses the request account already resolved by `AccountContextFilter`, so assumed-role credentials evaluate account-scoped resources against the role account. - IAM and multi-account docs now describe session-policy intersection and temporary-credential resolution accurately. - Java SDK compatibility coverage now checks that an assumed-role session policy deny overrides a role allow. ## Checklist - [x] `./mvnw test` passes locally - attempted; only failures were unrelated LambdaReactiveSyncIntegrationTest container startup Broken pipe errors - [x] Selected Java SDK compatibility tests pass locally - in `compatibility-tests/sdk-test-java`: `mvn -q -Dtest=IamEnforcementTest,IamTest,StsTest,S3Test test` - [x] New or updated integration test added - [x] Commit messages follow Conventional Commits * fix(iam): tighten cross-account session lookup
This commit is contained in:
1 parent
3304184bd3
commit
4f4e7be90e
8 files changed
+372
-23
No files matched your search
@@ -1,14 +1,28 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link IamEnforcementFilter#accessDeniedResponse}, focused on
|
||||
@@ -19,6 +33,56 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
*/
|
||||
class IamEnforcementFilterTest {
|
||||
|
||||
@Test
|
||||
void filterBuildsResourceArnWithRequestContextAccount() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.IamServiceConfig iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
|
||||
AccountResolver accountResolver = mock(AccountResolver.class);
|
||||
IamService iamService = mock(IamService.class);
|
||||
IamPolicyEvaluator evaluator = mock(IamPolicyEvaluator.class);
|
||||
IamActionRegistry actionRegistry = mock(IamActionRegistry.class);
|
||||
ResourceArnBuilder arnBuilder = mock(ResourceArnBuilder.class);
|
||||
RequestContext requestContext = new RequestContext();
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260629/us-east-1/lambda/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("222233334444");
|
||||
requestContext.setRegion("us-east-1");
|
||||
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.iam()).thenReturn(iamConfig);
|
||||
when(iamConfig.enforcementEnabled()).thenReturn(true);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(accountResolver.resolve(auth)).thenReturn("000000000000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("lambda", containerRequest)).thenReturn("lambda:InvokeFunction");
|
||||
when(iamService.resolveCallerContext("ASIASESSION"))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"lambda:InvokeFunction",
|
||||
"Resource":"arn:aws:lambda:us-east-1:222233334444:function:fn"}
|
||||
]}""")));
|
||||
when(arnBuilder.build("lambda", containerRequest, "us-east-1", "222233334444"))
|
||||
.thenReturn("arn:aws:lambda:us-east-1:222233334444:function:fn");
|
||||
when(evaluator.evaluate(
|
||||
any(),
|
||||
isNull(),
|
||||
eq("lambda:InvokeFunction"),
|
||||
eq("arn:aws:lambda:us-east-1:222233334444:function:fn"),
|
||||
isNull()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
|
||||
IamEnforcementFilter filter = new IamEnforcementFilter(
|
||||
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder, requestContext);
|
||||
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(arnBuilder).build("lambda", containerRequest, "us-east-1", "222233334444");
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryProtocolGetsXmlErrorResponse() {
|
||||
// IAM/STS/EC2/SQS/SNS/RDS/ELBv2/CFN/... — Query protocol, form-encoded body, XML response.
|
||||
|
||||
@@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamGroup;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
|
||||
@@ -10,6 +12,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -33,6 +36,11 @@ class IamServiceTest {
|
||||
}
|
||||
|
||||
private static IamService iamService(boolean seedDeployerPrincipal, InMemoryStorage<String, AccessKey> accessKeys) {
|
||||
return iamService(seedDeployerPrincipal, accessKeys, new InMemoryStorage<>());
|
||||
}
|
||||
|
||||
private static IamService iamService(boolean seedDeployerPrincipal, InMemoryStorage<String, AccessKey> accessKeys,
|
||||
StorageBackend<String, SessionCredential> sessions) {
|
||||
return new IamService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
@@ -40,7 +48,7 @@ class IamServiceTest {
|
||||
new InMemoryStorage<>(),
|
||||
accessKeys,
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
sessions,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
seedDeployerPrincipal
|
||||
);
|
||||
@@ -453,6 +461,31 @@ class IamServiceTest {
|
||||
assertTrue(iamService.resolveAccountId(null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveAccountIdDoesNotScanSessionsForLongTermAccessKey() {
|
||||
CountingAccountAwareSessionStorage sessions = new CountingAccountAwareSessionStorage();
|
||||
IamService service = iamService(false, new InMemoryStorage<>(), sessions);
|
||||
|
||||
assertTrue(service.resolveAccountId("AKIAIOSFODNN7EXAMPLE").isEmpty());
|
||||
assertEquals(0, sessions.scanAllAccountsAsMapCalls);
|
||||
}
|
||||
|
||||
private static final class CountingAccountAwareSessionStorage
|
||||
extends AccountAwareStorageBackend<SessionCredential> {
|
||||
|
||||
private int scanAllAccountsAsMapCalls;
|
||||
|
||||
private CountingAccountAwareSessionStorage() {
|
||||
super(new InMemoryStorage<>(), null, "000000000000");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, SessionCredential> scanAllAccountsAsMap() {
|
||||
scanAllAccountsAsMapCalls++;
|
||||
return super.scanAllAccountsAsMap();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveAccountIdEmptyForExpiredSession() {
|
||||
iamService.registerSession(
|
||||
@@ -467,6 +500,25 @@ class IamServiceTest {
|
||||
assertTrue(iamService.resolveAccountId("ASIAEXPIRED").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveCallerContextDeletesExpiredCrossAccountSessionFromOriginAccount() {
|
||||
String accessKeyId = "ASIAEXPIREDCROSSACCOUNT";
|
||||
AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "222233334444");
|
||||
sessions.putForAccount("111122223333", accessKeyId, new SessionCredential(
|
||||
accessKeyId,
|
||||
"temp-secret",
|
||||
"arn:aws:iam::222233334444:role/CrossAccountAccess",
|
||||
Instant.now().minusSeconds(60),
|
||||
null,
|
||||
"111122223333"));
|
||||
IamService service = iamService(false, new InMemoryStorage<>(), sessions);
|
||||
|
||||
assertNull(service.resolveCallerContext(accessKeyId));
|
||||
|
||||
assertTrue(sessions.getForAccount("111122223333", accessKeyId).isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Instance Profiles
|
||||
// =========================================================================
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(StsSessionPolicyS3EnforcementIntegrationTest.IamEnforcementProfile.class)
|
||||
class StsSessionPolicyS3EnforcementIntegrationTest {
|
||||
|
||||
private static final String CALLER_ACCOUNT_ID = "111122223333";
|
||||
private static final String ROLE_ACCOUNT_ID = "222233334444";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void assumeRoleSessionPolicyDenyRestrictsS3PutObject() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String bucket = "session-policy-" + suffix;
|
||||
String roleName = "SessionPolicyRole" + suffix;
|
||||
|
||||
createBucket(bucket);
|
||||
createRole(roleName);
|
||||
putBroadS3RolePolicy(roleName, bucket);
|
||||
|
||||
String accessKeyId = assumeRoleWithS3SessionPolicy(roleName, bucket);
|
||||
|
||||
given()
|
||||
.header("Authorization", auth(accessKeyId, "s3"))
|
||||
.contentType("text/plain")
|
||||
.body("allowed")
|
||||
.when()
|
||||
.put("/" + bucket + "/allowed/file.txt")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.header("Authorization", auth(accessKeyId, "s3"))
|
||||
.contentType("text/plain")
|
||||
.body("denied")
|
||||
.when()
|
||||
.put("/" + bucket + "/blocked/file.txt")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("<Code>AccessDenied</Code>"));
|
||||
}
|
||||
|
||||
private static void createBucket(String bucket) {
|
||||
given()
|
||||
.header("Authorization", auth(ROLE_ACCOUNT_ID, "s3"))
|
||||
.when()
|
||||
.put("/" + bucket)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void createRole(String roleName) {
|
||||
given()
|
||||
.formParam("Action", "CreateRole")
|
||||
.formParam("RoleName", roleName)
|
||||
.formParam("Path", "/")
|
||||
.formParam("AssumeRolePolicyDocument", """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": { "AWS": "*" },
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
}
|
||||
""")
|
||||
.header("Authorization", auth(ROLE_ACCOUNT_ID, "iam"))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void putBroadS3RolePolicy(String roleName, String bucket) {
|
||||
given()
|
||||
.formParam("Action", "PutRolePolicy")
|
||||
.formParam("RoleName", roleName)
|
||||
.formParam("PolicyName", "AllowS3")
|
||||
.formParam("PolicyDocument", """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:*",
|
||||
"Resource": [
|
||||
"arn:aws:s3:::%1$s",
|
||||
"arn:aws:s3:::%1$s/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(bucket))
|
||||
.header("Authorization", auth(ROLE_ACCOUNT_ID, "iam"))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static String assumeRoleWithS3SessionPolicy(String roleName, String bucket) {
|
||||
return given()
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT_ID + ":role/" + roleName)
|
||||
.formParam("RoleSessionName", "session-policy-test")
|
||||
.formParam("Policy", """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:*",
|
||||
"Resource": [
|
||||
"arn:aws:s3:::%1$s",
|
||||
"arn:aws:s3:::%1$s/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Action": "s3:*",
|
||||
"Resource": "arn:aws:s3:::%1$s/blocked/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(bucket))
|
||||
.header("Authorization", auth(CALLER_ACCOUNT_ID, "sts"))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA"))
|
||||
.extract()
|
||||
.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260629/" + REGION + "/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
|
||||
public static final class IamEnforcementProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.iam.enforcement-enabled", "true");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user