Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

Add IAM provisioning preflight support (#1250)

Jason van Zyl3acab2bf27f8
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java
index 2088f70fad..66c2f08d06 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java
@@ -58,6 +58,7 @@ import software.amazon.awssdk.services.iam.model.NoSuchEntityException;
import software.amazon.awssdk.services.iam.model.PutRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.RemoveRoleFromInstanceProfileRequest;
import software.amazon.awssdk.services.iam.model.RemoveUserFromGroupRequest;
+import software.amazon.awssdk.services.iam.model.SimulatePrincipalPolicyRequest;
import software.amazon.awssdk.services.iam.model.StatusType;
import software.amazon.awssdk.services.iam.model.TagUserRequest;
import software.amazon.awssdk.services.iam.model.UntagUserRequest;
@@ -377,6 +378,27 @@ class IamTest {
@Test
@Order(24)
+ void simulatePrincipalPolicy() {
+ var response = iam.simulatePrincipalPolicy(SimulatePrincipalPolicyRequest.builder()
+ .policySourceArn("arn:aws:iam::000000000000:user/" + USER_NAME)
+ .actionNames("s3:GetObject", "ec2:RunInstances")
+ .resourceArns("*")
+ .build());
+
+ assertThat(response.evaluationResults()).hasSize(2);
+ assertThat(response.evaluationResults())
+ .anySatisfy(result -> {
+ assertThat(result.evalActionName()).isEqualTo("s3:GetObject");
+ assertThat(result.evalDecisionAsString()).isEqualTo("allowed");
+ })
+ .anySatisfy(result -> {
+ assertThat(result.evalActionName()).isEqualTo("ec2:RunInstances");
+ assertThat(result.evalDecisionAsString()).isEqualTo("implicitDeny");
+ });
+ }
+
+ @Test
+ @Order(25)
void putRolePolicy() {
iam.putRolePolicy(PutRolePolicyRequest.builder()
.roleName(ROLE_NAME)
@@ -386,7 +408,7 @@ class IamTest {
}
@Test
- @Order(25)
+ @Order(26)
void getRolePolicy() {
GetRolePolicyResponse response = iam.getRolePolicy(GetRolePolicyRequest.builder()
.roleName(ROLE_NAME).policyName("inline-exec").build());
@@ -395,7 +417,7 @@ class IamTest {
}
@Test
- @Order(26)
+ @Order(27)
void listRolePolicies() {
ListRolePoliciesResponse response = iam.listRolePolicies(
ListRolePoliciesRequest.builder().roleName(ROLE_NAME).build());
@@ -406,7 +428,7 @@ class IamTest {
// ── Instance Profiles ──────────────────────────────────────────────
@Test
- @Order(27)
+ @Order(28)
void createInstanceProfile() {
CreateInstanceProfileResponse response = iam.createInstanceProfile(
CreateInstanceProfileRequest.builder()
@@ -417,14 +439,14 @@ class IamTest {
}
@Test
- @Order(28)
+ @Order(29)
void addRoleToInstanceProfile() {
iam.addRoleToInstanceProfile(AddRoleToInstanceProfileRequest.builder()
.instanceProfileName(INSTANCE_PROFILE_NAME).roleName(ROLE_NAME).build());
}
@Test
- @Order(29)
+ @Order(30)
void getInstanceProfile() {
GetInstanceProfileResponse response = iam.getInstanceProfile(
GetInstanceProfileRequest.builder()
@@ -435,7 +457,7 @@ class IamTest {
}
@Test
- @Order(30)
+ @Order(31)
void listInstanceProfiles() {
ListInstanceProfilesResponse response = iam.listInstanceProfiles();
@@ -446,7 +468,7 @@ class IamTest {
// ── Error Cases ────────────────────────────────────────────────────
@Test
- @Order(31)
+ @Order(32)
void getUserNotFoundThrows() {
assertThatThrownBy(() -> iam.getUser(GetUserRequest.builder()
.userName("nonexistent-user-xyz").build()))
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index d588f78c65..4f97b5c293 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -103,7 +103,8 @@ public class AwsQueryController {
"TagPolicy", "UntagPolicy", "ListPolicyTags",
"CreateLoginProfile", "GetLoginProfile", "DeleteLoginProfile", "UpdateLoginProfile",
"GenerateCredentialReport", "GetCredentialReport",
- "GetAccountSummary", "GetAccountAuthorizationDetails"
+ "GetAccountSummary", "GetAccountAuthorizationDetails",
+ "SimulatePrincipalPolicy"
);
private static final Set<String> AUTOSCALING_ACTIONS = Set.of(
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java b/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java
index 45d353c016..efdaadc885 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java
@@ -39,6 +39,8 @@ final class AwsManagedPolicies {
"Provides full access to Amazon DynamoDB via the AWS Management Console."),
new ManagedPolicyDef("AmazonEC2FullAccess", "/",
"Provides full access to Amazon EC2 via the AWS Management Console."),
+ new ManagedPolicyDef("AmazonEC2ContainerRegistryReadOnly", "/",
+ "Provides read-only access to Amazon EC2 Container Registry repositories."),
new ManagedPolicyDef("AmazonSQSFullAccess", "/",
"Provides full access to Amazon SQS via the AWS Management Console."),
new ManagedPolicyDef("AmazonSNSFullAccess", "/",
@@ -47,6 +49,8 @@ final class AwsManagedPolicies {
"Provides full access to Amazon VPC via the AWS Management Console."),
new ManagedPolicyDef("CloudWatchFullAccess", "/",
"Provides full access to CloudWatch."),
+ new ManagedPolicyDef("CloudWatchAgentServerPolicy", "/",
+ "Provides permissions required to use the CloudWatch agent on servers."),
new ManagedPolicyDef("AWSLambdaFullAccess", "/",
"Provides full access to Lambda, S3, DynamoDB, CloudWatch Metrics and Logs."),
@@ -108,6 +112,8 @@ final class AwsManagedPolicies {
"Provides permissions for AWS Systems Manager diagnosis automation execution."),
new ManagedPolicyDef("AWS-SSM-RemediationAutomation-ExecutionRolePolicy", "/",
"Provides permissions for AWS Systems Manager remediation automation execution."),
+ new ManagedPolicyDef("AmazonSSMManagedInstanceCore", "/",
+ "Provides permissions required for instances to use AWS Systems Manager core service functionality."),
// SageMaker execution role policies
new ManagedPolicyDef("AmazonSageMakerGeospatialExecutionRole", "/service-role/",
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
index 41041818ca..b971ad109f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
@@ -40,6 +40,22 @@ public class IamPolicyEvaluator {
public enum Decision { ALLOW, DENY }
+ public enum SimulationDecision {
+ ALLOWED("allowed"),
+ EXPLICIT_DENY("explicitDeny"),
+ IMPLICIT_DENY("implicitDeny");
+
+ private final String awsValue;
+
+ SimulationDecision(String awsValue) {
+ this.awsValue = awsValue;
+ }
+
+ public String awsValue() {
+ return awsValue;
+ }
+ }
+
private static final Logger LOG = Logger.getLogger(IamPolicyEvaluator.class);
private final ObjectMapper objectMapper;
@@ -56,7 +72,7 @@ public class IamPolicyEvaluator {
* @param resourcePolicies resource-based policy documents (Phase 2); may be null or empty
* @param action IAM action, e.g. "s3:GetObject"
* @param resource resource ARN, e.g. "arn:aws:s3:::my-bucket/key"
- * @param conditionCtx condition context key-value pairs (lowercase keys); may be null or empty
+ * @param conditionCtx condition context key-value pairs; may be null or empty
* @return {@link Decision#ALLOW} or {@link Decision#DENY}
*/
public Decision evaluate(CallerContext caller,
@@ -64,7 +80,7 @@ public class IamPolicyEvaluator {
String action,
String resource,
Map<String, String> conditionCtx) {
- Map<String, String> ctx = conditionCtx == null ? Map.of() : conditionCtx;
+ Map<String, String> ctx = normalizeConditionContext(conditionCtx);
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
List<PolicyStatement> resourceStmts = resourcePolicies == null ? List.of() : parseAll(resourcePolicies);
@@ -119,10 +135,50 @@ public class IamPolicyEvaluator {
return evaluate(CallerContext.of(policyDocuments), null, action, resource, conditionCtx);
}
+ public SimulationDecision simulatePrincipalPolicy(CallerContext caller,
+ String action,
+ String resource,
+ Map<String, String> conditionCtx) {
+ Map<String, String> ctx = normalizeConditionContext(conditionCtx);
+ List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
+ List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null
+ ? null : parseAll(List.of(caller.sessionPolicyDocument()));
+ List<PolicyStatement> boundaryStmts = caller.boundaryPolicyDocument() == null
+ ? null : parseAll(List.of(caller.boundaryPolicyDocument()));
+
+ if (anyExplicitDeny(identityStmts, action, resource, ctx)
+ || (sessionStmts != null && anyExplicitDeny(sessionStmts, action, resource, ctx))
+ || (boundaryStmts != null && anyExplicitDeny(boundaryStmts, action, resource, ctx))) {
+ return SimulationDecision.EXPLICIT_DENY;
+ }
+ if (!anyExplicitAllow(identityStmts, action, resource, ctx)) {
+ return SimulationDecision.IMPLICIT_DENY;
+ }
+ if (sessionStmts != null && !anyExplicitAllow(sessionStmts, action, resource, ctx)) {
+ return SimulationDecision.IMPLICIT_DENY;
+ }
+ if (boundaryStmts != null && !anyExplicitAllow(boundaryStmts, action, resource, ctx)) {
+ return SimulationDecision.IMPLICIT_DENY;
+ }
+ return SimulationDecision.ALLOWED;
+ }
+
// -----------------------------------------------------------------------
// Statement matching
// -----------------------------------------------------------------------
+ private Map<String, String> normalizeConditionContext(Map<String, String> conditionCtx) {
+ if (conditionCtx == null || conditionCtx.isEmpty()) {
+ return Map.of();
+ }
+ return conditionCtx.entrySet().stream()
+ .filter(entry -> entry.getKey() != null && entry.getValue() != null)
+ .collect(java.util.stream.Collectors.toMap(
+ entry -> entry.getKey().toLowerCase(java.util.Locale.ROOT),
+ Map.Entry::getValue,
+ (first, ignored) -> first));
+ }
+
private boolean anyExplicitDeny(List<PolicyStatement> stmts, String action, String resource,
Map<String, String> ctx) {
for (PolicyStatement stmt : stmts) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
index 504ba55a1a..562439c58f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
@@ -8,6 +8,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.CallerContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -33,10 +34,12 @@ public class IamQueryHandler {
private static final Logger LOG = Logger.getLogger(IamQueryHandler.class);
private final IamService iamService;
+ private final IamPolicyEvaluator policyEvaluator;
@Inject
- public IamQueryHandler(IamService iamService) {
+ public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator) {
this.iamService = iamService;
+ this.policyEvaluator = policyEvaluator;
}
public Response handle(String action, MultivaluedMap<String, String> params) {
@@ -142,6 +145,9 @@ public class IamQueryHandler {
case "PutRolePermissionsBoundary" -> handlePutRolePermissionsBoundary(params);
case "DeleteRolePermissionsBoundary" -> handleDeleteRolePermissionsBoundary(params);
+ // Policy Simulation
+ case "SimulatePrincipalPolicy" -> handleSimulatePrincipalPolicy(params);
+
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.IAM, 400);
};
@@ -711,6 +717,39 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("DeleteRolePermissionsBoundary", AwsNamespaces.IAM, "")).build();
}
+ private Response handleSimulatePrincipalPolicy(MultivaluedMap<String, String> params) {
+ String policySourceArn = getParam(params, "PolicySourceArn");
+ CallerContext caller = iamService.resolvePrincipalContext(policySourceArn);
+ List<String> actionNames = extractIndexedValues(params, "ActionNames.member");
+ if (actionNames.isEmpty()) {
+ throw new AwsException("ValidationError", "At least one ActionNames member is required.", 400);
+ }
+ List<String> resourceArns = extractIndexedValues(params, "ResourceArns.member");
+ if (resourceArns.isEmpty()) {
+ resourceArns = List.of("*");
+ }
+ Map<String, String> context = extractContextEntries(params);
+
+ XmlBuilder results = new XmlBuilder().start("EvaluationResults");
+ for (String actionName : actionNames) {
+ for (String resourceArn : resourceArns) {
+ IamPolicyEvaluator.SimulationDecision decision =
+ policyEvaluator.simulatePrincipalPolicy(caller, actionName, resourceArn, context);
+ results.start("member")
+ .elem("EvalActionName", actionName)
+ .elem("EvalResourceName", resourceArn)
+ .elem("EvalDecision", decision.awsValue())
+ .start("MatchedStatements").end("MatchedStatements")
+ .start("MissingContextValues").end("MissingContextValues")
+ .end("member");
+ }
+ }
+ String result = results.end("EvaluationResults")
+ .elem("IsTruncated", false)
+ .build();
+ return Response.ok(AwsQueryResponse.envelope("SimulatePrincipalPolicy", AwsNamespaces.IAM, result)).build();
+ }
+
// =========================================================================
// XML serialization helpers
// =========================================================================
@@ -854,6 +893,29 @@ public class IamQueryHandler {
return keys;
}
+ private List<String> extractIndexedValues(MultivaluedMap<String, String> params, String prefix) {
+ List<String> values = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String value = params.getFirst(prefix + "." + i);
+ if (value == null) break;
+ values.add(value);
+ }
+ return values;
+ }
+
+ private Map<String, String> extractContextEntries(MultivaluedMap<String, String> params) {
+ Map<String, String> context = new HashMap<>();
+ for (int i = 1; ; i++) {
+ String name = params.getFirst("ContextEntries.member." + i + ".ContextKeyName");
+ if (name == null) break;
+ String value = params.getFirst("ContextEntries.member." + i + ".ContextKeyValues.member.1");
+ if (value != null) {
+ context.put(name, value);
+ }
+ }
+ return context;
+ }
+
private String getParam(MultivaluedMap<String, String> params, String name) {
return params.getFirst(name);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index 82c118082e..cdbc7f255d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -37,6 +37,9 @@ public class IamService {
private static final Logger LOG = Logger.getLogger(IamService.class);
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String DEFAULT_DEPLOYER_USER = "floci-deployer";
+ private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci";
+ private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci";
private final StorageBackend<String, IamUser> users;
private final StorageBackend<String, IamGroup> groups;
@@ -80,6 +83,11 @@ public class IamService {
}
@PostConstruct
+ void seedDefaults() {
+ seedAwsManagedPolicies();
+ seedDefaultDeployerPrincipal();
+ }
+
void seedAwsManagedPolicies() {
int seeded = 0;
for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.POLICIES) {
@@ -98,6 +106,30 @@ public class IamService {
}
}
+ private void seedDefaultDeployerPrincipal() {
+ String adminPolicyArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess";
+ IamUser user = users.get(DEFAULT_DEPLOYER_USER)
+ .orElseGet(() -> {
+ String userId = "AIDA" + randomId(16);
+ String arn = iamArn("user", "/", DEFAULT_DEPLOYER_USER);
+ IamUser seededUser = new IamUser(userId, DEFAULT_DEPLOYER_USER, "/", arn);
+ users.put(DEFAULT_DEPLOYER_USER, seededUser);
+ LOG.infov("Seeded default IAM deployer user: {0}", DEFAULT_DEPLOYER_USER);
+ return seededUser;
+ });
+ if (!user.getAttachedPolicyArns().contains(adminPolicyArn)) {
+ user.getAttachedPolicyArns().add(adminPolicyArn);
+ users.put(DEFAULT_DEPLOYER_USER, user);
+ }
+ if (accessKeys.get(DEFAULT_DEPLOYER_ACCESS_KEY_ID).isEmpty()) {
+ accessKeys.put(DEFAULT_DEPLOYER_ACCESS_KEY_ID, new AccessKey(
+ DEFAULT_DEPLOYER_ACCESS_KEY_ID,
+ DEFAULT_DEPLOYER_SECRET_ACCESS_KEY,
+ DEFAULT_DEPLOYER_USER));
+ LOG.infov("Seeded default IAM deployer access key: {0}", DEFAULT_DEPLOYER_ACCESS_KEY_ID);
+ }
+ }
+
// =========================================================================
// Users
// =========================================================================
@@ -893,6 +925,56 @@ public class IamService {
return ctx == null ? null : ctx.identityPolicies();
}
+ public Optional<String> resolveCallerArn(String accessKeyId) {
+ if (accessKeyId == null || accessKeyId.isBlank()) {
+ return Optional.empty();
+ }
+
+ Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);
+ if (akOpt.isPresent()) {
+ String userName = akOpt.get().getUserName();
+ return users.get(userName).map(IamUser::getArn);
+ }
+
+ Optional<SessionCredential> sessionOpt = sessions.get(accessKeyId);
+ if (sessionOpt.isPresent()) {
+ SessionCredential session = sessionOpt.get();
+ if (session.getExpiration() != null && session.getExpiration().isBefore(java.time.Instant.now())) {
+ sessions.delete(accessKeyId);
+ return Optional.empty();
+ }
+ String roleArn = session.getRoleArn();
+ String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
+ String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
+ return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/floci-session").toString());
+ }
+
+ return Optional.empty();
+ }
+
+ public CallerContext resolvePrincipalContext(String principalArn) {
+ if (principalArn == null || principalArn.isBlank()) {
+ throw new AwsException("ValidationError", "PolicySourceArn is required.", 400);
+ }
+ if (principalArn.contains(":user/")) {
+ String userName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
+ List<String> identityPolicies = collectUserPolicies(userName);
+ if (identityPolicies == null) {
+ throw new AwsException("NoSuchEntity", "User " + userName + " cannot be found.", 404);
+ }
+ return new CallerContext(identityPolicies, null, resolveUserBoundaryDocument(userName));
+ }
+ if (principalArn.contains(":role/")) {
+ String roleName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
+ List<String> identityPolicies = collectRolePolicies(principalArn);
+ if (identityPolicies == null) {
+ throw new AwsException("NoSuchEntity", "Role " + roleName + " cannot be found.", 404);
+ }
+ return new CallerContext(identityPolicies, null, resolveRoleBoundaryDocument(principalArn));
+ }
+ throw new AwsException("InvalidInput", "PolicySourceArn must identify an IAM user or role.", 400);
+ }
+
private String resolveUserBoundaryDocument(String userName) {
return users.get(userName)
.map(IamUser::getPermissionsBoundaryArn)
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
index fb6b9b903c..e8fae85dbf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
@@ -4,10 +4,13 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryController;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
+import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
@@ -28,11 +31,16 @@ public class StsQueryHandler {
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private final IamService iamService;
+ private final AccountResolver accountResolver;
private final RegionResolver regionResolver;
+ @Context
+ HttpHeaders headers;
+
@Inject
- public StsQueryHandler(IamService iamService, RegionResolver regionResolver) {
+ public StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver) {
this.iamService = iamService;
+ this.accountResolver = accountResolver;
this.regionResolver = regionResolver;
}
@@ -91,10 +99,14 @@ public class StsQueryHandler {
private Response handleGetCallerIdentity(MultivaluedMap<String, String> params) {
String accountId = regionResolver.getAccountId();
+ String authorization = headers == null ? null : headers.getHeaderString("Authorization");
+ String accessKeyId = authorization == null ? null : accountResolver.extractAccessKeyId(authorization);
+ String arn = iamService.resolveCallerArn(accessKeyId)
+ .orElse(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
String result = new XmlBuilder()
.elem("UserId", accountId)
.elem("Account", accountId)
- .elem("Arn", AwsArnUtils.Arn.of("iam", "", accountId, "root").toString())
+ .elem("Arn", arn)
.build();
return Response.ok(AwsQueryResponse.envelope("GetCallerIdentity", AwsNamespaces.STS, result)).build();
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java
index 6650a23f93..70a780af83 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java
@@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test;
import jakarta.inject.Inject;
import java.util.List;
+import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -119,6 +120,22 @@ class IamEnforcementIntegrationTest {
evaluator.evaluate(List.of("not-json"), "s3:GetObject", "*"));
}
+ @Test
+ void conditionContextKeysAreCaseInsensitive() {
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
+ "Condition":{"StringEquals":{"aws:SourceIp":"127.0.0.1"}}}
+ ]}""";
+
+ assertEquals(Decision.ALLOW,
+ evaluator.simulateCustomPolicy(
+ List.of(policy),
+ "s3:GetObject",
+ "arn:aws:s3:::bucket/key",
+ Map.of("AWS:SourceIP", "127.0.0.1")));
+ }
+
// =========================================================================
// IamPolicyEvaluator.globMatches — unit tests
// =========================================================================
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
index 73a5714948..bc4ea6417b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
@@ -29,6 +29,10 @@ class IamIntegrationTest {
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
+ private static final String EXPLICIT_DENY_POLICY_DOCUMENT =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\","
+ + "\"Action\":\"ec2:RunInstances\",\"Resource\":\"*\"}]}";
+
private static String createdPolicyArn;
// =========================================================================
@@ -154,7 +158,7 @@ class IamIntegrationTest {
// The standard EKS managed policies the EKS console/SDK and the
// terraform-aws-modules/eks module attach to cluster and node roles (#1092).
@ParameterizedTest
- @Order(6)
+ @Order(15)
@ValueSource(strings = {
"arn:aws:iam::aws:policy/AmazonEKSClusterPolicy",
"arn:aws:iam::aws:policy/AmazonEKSServicePolicy",
@@ -177,6 +181,163 @@ class IamIntegrationTest {
.body("GetPolicyResponse.GetPolicyResult.Policy.Arn", equalTo(arn));
}
+ @Test
+ @Order(16)
+ void getSsmManagedInstanceCorePolicy() {
+ given()
+ .formParam("Action", "GetPolicy")
+ .formParam("PolicyArn", "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("GetPolicyResponse.GetPolicyResult.Policy.PolicyName",
+ equalTo("AmazonSSMManagedInstanceCore"))
+ .body("GetPolicyResponse.GetPolicyResult.Policy.Arn",
+ equalTo("arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"));
+ }
+
+ @Test
+ @Order(7)
+ void getCloudWatchAgentServerPolicy() {
+ given()
+ .formParam("Action", "GetPolicy")
+ .formParam("PolicyArn", "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("GetPolicyResponse.GetPolicyResult.Policy.PolicyName",
+ equalTo("CloudWatchAgentServerPolicy"))
+ .body("GetPolicyResponse.GetPolicyResult.Policy.Arn",
+ equalTo("arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"));
+ }
+
+ @Test
+ @Order(8)
+ void getEcrReadOnlyPolicy() {
+ given()
+ .formParam("Action", "GetPolicy")
+ .formParam("PolicyArn", "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("GetPolicyResponse.GetPolicyResult.Policy.PolicyName",
+ equalTo("AmazonEC2ContainerRegistryReadOnly"))
+ .body("GetPolicyResponse.GetPolicyResult.Policy.Arn",
+ equalTo("arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"));
+ }
+
+ @Test
+ @Order(9)
+ void stsGetCallerIdentityHonoursSeededFlociAccessKey() {
+ given()
+ .formParam("Action", "GetCallerIdentity")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=floci/20260227/us-east-1/sts/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo("000000000000"))
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",
+ equalTo("arn:aws:iam::000000000000:user/floci-deployer"));
+ }
+
+ @Test
+ @Order(34)
+ void simulatePrincipalPolicyEvaluatesIdentityPolicies() {
+ given()
+ .formParam("Action", "CreateUser")
+ .formParam("UserName", "simulate-user")
+ .formParam("Path", "/")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String policyArn = given()
+ .formParam("Action", "CreatePolicy")
+ .formParam("PolicyName", "SimulatePolicy")
+ .formParam("Path", "/")
+ .formParam("PolicyDocument", POLICY_DOCUMENT)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
+
+ String denyPolicyArn = given()
+ .formParam("Action", "CreatePolicy")
+ .formParam("PolicyName", "SimulateExplicitDenyPolicy")
+ .formParam("Path", "/")
+ .formParam("PolicyDocument", EXPLICIT_DENY_POLICY_DOCUMENT)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
+
+ given()
+ .formParam("Action", "AttachUserPolicy")
+ .formParam("UserName", "simulate-user")
+ .formParam("PolicyArn", policyArn)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .formParam("Action", "AttachUserPolicy")
+ .formParam("UserName", "simulate-user")
+ .formParam("PolicyArn", denyPolicyArn)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .formParam("Action", "SimulatePrincipalPolicy")
+ .formParam("PolicySourceArn", "arn:aws:iam::000000000000:user/simulate-user")
+ .formParam("ActionNames.member.1", "s3:GetObject")
+ .formParam("ActionNames.member.2", "ec2:RunInstances")
+ .formParam("ActionNames.member.3", "ssm:GetParameter")
+ .formParam("ResourceArns.member.1", "*")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("SimulatePrincipalPolicyResponse.SimulatePrincipalPolicyResult.EvaluationResults.member.find { it.EvalActionName == 's3:GetObject' }.EvalDecision",
+ equalTo("allowed"))
+ .body("SimulatePrincipalPolicyResponse.SimulatePrincipalPolicyResult.EvaluationResults.member.find { it.EvalActionName == 'ec2:RunInstances' }.EvalDecision",
+ equalTo("explicitDeny"))
+ .body("SimulatePrincipalPolicyResponse.SimulatePrincipalPolicyResult.EvaluationResults.member.find { it.EvalActionName == 'ssm:GetParameter' }.EvalDecision",
+ equalTo("implicitDeny"));
+ }
+
@Test
@Order(35)
void attachManagedPolicyToRole() {
@@ -270,7 +431,7 @@ class IamIntegrationTest {
.then()
.statusCode(200)
.body("ListUsersResponse.ListUsersResult.Users.member.UserName",
- equalTo("test-user"));
+ hasItem("test-user"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index ecc4d8bace..e9b903d2c6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -481,6 +481,18 @@ class IamServiceTest {
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole");
assertEquals("AWSLambdaBasicExecutionRole", lambda.getPolicyName());
assertEquals("/service-role/", lambda.getPath());
+
+ IamPolicy ssm = iamService.getPolicy("arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore");
+ assertEquals("AmazonSSMManagedInstanceCore", ssm.getPolicyName());
+ assertEquals("/", ssm.getPath());
+
+ IamPolicy cloudWatchAgent = iamService.getPolicy("arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy");
+ assertEquals("CloudWatchAgentServerPolicy", cloudWatchAgent.getPolicyName());
+ assertEquals("/", cloudWatchAgent.getPath());
+
+ IamPolicy ecrReadOnly = iamService.getPolicy("arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly");
+ assertEquals("AmazonEC2ContainerRegistryReadOnly", ecrReadOnly.getPolicyName());
+ assertEquals("/", ecrReadOnly.getPath());
}
@Test
@@ -494,6 +506,29 @@ class IamServiceTest {
assertEquals(firstId, secondId);
}
+ @Test
+ void seedDefaultsCreatesDefaultDeployerPrincipal() {
+ iamService.seedDefaults();
+
+ IamUser user = iamService.getUser("floci-deployer");
+ assertEquals("arn:aws:iam::000000000000:user/floci-deployer", user.getArn());
+ assertTrue(user.getAttachedPolicyArns().contains("arn:aws:iam::aws:policy/AdministratorAccess"));
+ assertEquals(
+ "arn:aws:iam::000000000000:user/floci-deployer",
+ iamService.resolveCallerArn("floci").orElseThrow());
+ assertNotNull(iamService.resolveCallerContext("floci"));
+ assertNotNull(iamService.resolvePrincipalContext(user.getArn()));
+ }
+
+ @Test
+ void simulatePrincipalPolicyRejectsUnsupportedPrincipalArnType() {
+ AwsException ex = assertThrows(AwsException.class,
+ () -> iamService.resolvePrincipalContext("arn:aws:iam::000000000000:group/admins"));
+
+ assertEquals("InvalidInput", ex.getErrorCode());
+ assertEquals("PolicySourceArn must identify an IAM user or role.", ex.getMessage());
+ }
+
@Test
void attachManagedPolicyToRole() {
iamService.seedAwsManagedPolicies();
@@ -507,6 +542,45 @@ class IamServiceTest {
assertEquals(policyArn, attached.getFirst().getArn());
}
+ @Test
+ void attachSsmManagedInstanceCorePolicyToRole() {
+ iamService.seedAwsManagedPolicies();
+ iamService.createRole("Ec2Exec", "/", "{}", null, 0, null);
+
+ String policyArn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore";
+ iamService.attachRolePolicy("Ec2Exec", policyArn);
+
+ List<IamPolicy> attached = iamService.listAttachedRolePolicies("Ec2Exec", null);
+ assertEquals(1, attached.size());
+ assertEquals(policyArn, attached.getFirst().getArn());
+ }
+
+ @Test
+ void attachCloudWatchAgentServerPolicyToRole() {
+ iamService.seedAwsManagedPolicies();
+ iamService.createRole("Ec2Exec", "/", "{}", null, 0, null);
+
+ String policyArn = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy";
+ iamService.attachRolePolicy("Ec2Exec", policyArn);
+
+ List<IamPolicy> attached = iamService.listAttachedRolePolicies("Ec2Exec", null);
+ assertEquals(1, attached.size());
+ assertEquals(policyArn, attached.getFirst().getArn());
+ }
+
+ @Test
+ void attachEcrReadOnlyPolicyToRole() {
+ iamService.seedAwsManagedPolicies();
+ iamService.createRole("Ec2Exec", "/", "{}", null, 0, null);
+
+ String policyArn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly";
+ iamService.attachRolePolicy("Ec2Exec", policyArn);
+
+ List<IamPolicy> attached = iamService.listAttachedRolePolicies("Ec2Exec", null);
+ assertEquals(1, attached.size());
+ assertEquals(policyArn, attached.getFirst().getArn());
+ }
+
@Test
void awsManagedPolicyDeleteRejected() {
iamService.seedAwsManagedPolicies();