Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(iam): enforce iam when it turned on (#411)

Hector Venturacfe48dfabe33
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java
new file mode 100644
index 0000000000..cf3ae7b50f
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java
@@ -0,0 +1,296 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.*;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.iam.IamClient;
+import software.amazon.awssdk.services.iam.model.*;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.S3Exception;
+import software.amazon.awssdk.services.sts.StsClient;
+import software.amazon.awssdk.services.sts.model.*;
+
+import static org.assertj.core.api.Assertions.*;
+
+/**
+ * End-to-end compatibility tests for IAM Enforcement Mode.
+ *
+ * <p>These tests require the Floci instance to be running with
+ * {@code floci.services.iam.enforcement-enabled=true}.
+ * When enforcement is disabled (the default), all tests are skipped via
+ * {@link Assumptions} so the standard test-suite always passes.
+ *
+ * <p>Scenarios covered:
+ * <ul>
+ * <li>User with no policy → DENY</li>
+ * <li>User with explicit allow policy → ALLOW</li>
+ * <li>Explicit Deny inline policy overrides attached Allow → DENY</li>
+ * <li>Wildcard action policy grants access → ALLOW</li>
+ * <li>Assumed role with no policies → DENY</li>
+ * <li>Assumed role with attached allow policy → ALLOW</li>
+ * </ul>
+ */
+@DisplayName("IAM Enforcement Mode")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class IamEnforcementTest {
+
+ // ── Resource names ─────────────────────────────────────────────────────────
+ private static final String USER = "iam-enf-test-user";
+ private static final String ROLE = "iam-enf-test-role";
+ private static final String POLICY_NAME = "iam-enf-allow-s3list";
+
+ private static final String TRUST_POLICY = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"Service":"sts.amazonaws.com"},
+ "Action":"sts:AssumeRole"}
+ ]}""";
+
+ // s3:ListAllMyBuckets is the IAM action for ListBuckets — simple, resource-agnostic.
+ private static final String ALLOW_S3_LIST_POLICY = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}
+ ]}""";
+
+ private static final String DENY_S3_LIST_POLICY = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Deny","Action":"s3:ListAllMyBuckets","Resource":"*"}
+ ]}""";
+
+ private static final String ALLOW_S3_WILDCARD_POLICY = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:*","Resource":"*"}
+ ]}""";
+
+ // ── Shared state ───────────────────────────────────────────────────────────
+ private static IamClient iam;
+ private static StsClient sts;
+ private static String userAccessKeyId;
+ private static String userSecretKey;
+ private static String roleArn;
+ private static String allowPolicyArn;
+ /** Cached at @BeforeAll before any policies are attached. */
+ private static boolean enforcementEnabled;
+
+ @BeforeAll
+ static void setup() {
+ iam = TestFixtures.iamClient();
+ sts = TestFixtures.stsClient();
+
+ // Create the test user
+ iam.createUser(CreateUserRequest.builder().userName(USER).build());
+
+ // Create an access key for the test user
+ CreateAccessKeyResponse keyResp = iam.createAccessKey(
+ CreateAccessKeyRequest.builder().userName(USER).build());
+ userAccessKeyId = keyResp.accessKey().accessKeyId();
+ userSecretKey = keyResp.accessKey().secretAccessKey();
+
+ // Create the test role (no policies attached initially)
+ CreateRoleResponse roleResp = iam.createRole(CreateRoleRequest.builder()
+ .roleName(ROLE)
+ .assumeRolePolicyDocument(TRUST_POLICY)
+ .build());
+ roleArn = roleResp.role().arn();
+
+ // Create a managed allow-s3-list policy (attached/detached per test)
+ CreatePolicyResponse policyResp = iam.createPolicy(CreatePolicyRequest.builder()
+ .policyName(POLICY_NAME)
+ .policyDocument(ALLOW_S3_LIST_POLICY)
+ .build());
+ allowPolicyArn = policyResp.policy().arn();
+
+ // Probe enforcement ONCE before any policies are attached to the test user.
+ // The user currently has zero policies — if enforcement is on, ListBuckets → 403.
+ enforcementEnabled = probeEnforcementEnabled();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (iam == null) return;
+ try { iam.detachRolePolicy(DetachRolePolicyRequest.builder()
+ .roleName(ROLE).policyArn(allowPolicyArn).build()); } catch (Exception ignored) {}
+ try { iam.detachUserPolicy(DetachUserPolicyRequest.builder()
+ .userName(USER).policyArn(allowPolicyArn).build()); } catch (Exception ignored) {}
+ try { iam.deleteUserPolicy(DeleteUserPolicyRequest.builder()
+ .userName(USER).policyName("inline-deny").build()); } catch (Exception ignored) {}
+ try { iam.deleteAccessKey(DeleteAccessKeyRequest.builder()
+ .userName(USER).accessKeyId(userAccessKeyId).build()); } catch (Exception ignored) {}
+ try { iam.deleteRole(DeleteRoleRequest.builder().roleName(ROLE).build()); } catch (Exception ignored) {}
+ try { iam.deletePolicy(DeletePolicyRequest.builder().policyArn(allowPolicyArn).build()); } catch (Exception ignored) {}
+ try { iam.deleteUser(DeleteUserRequest.builder().userName(USER).build()); } catch (Exception ignored) {}
+ iam.close();
+ sts.close();
+ }
+
+ // ── Client factories ───────────────────────────────────────────────────────
+
+ private static S3Client s3WithCredentials(String akid, String secret) {
+ return S3Client.builder()
+ .endpointOverride(TestFixtures.endpoint())
+ .region(Region.US_EAST_1)
+ .credentialsProvider(StaticCredentialsProvider.create(
+ AwsBasicCredentials.create(akid, secret)))
+ .forcePathStyle(true)
+ .build();
+ }
+
+ private static S3Client s3WithSessionCredentials(
+ String akid, String secret, String sessionToken) {
+ return S3Client.builder()
+ .endpointOverride(TestFixtures.endpoint())
+ .region(Region.US_EAST_1)
+ .credentialsProvider(StaticCredentialsProvider.create(
+ AwsSessionCredentials.create(akid, secret, sessionToken)))
+ .forcePathStyle(true)
+ .build();
+ }
+
+ /**
+ * Probes whether enforcement is active by calling ListBuckets with
+ * the test user (who must have NO attached policies at this point).
+ *
+ * Returns {@code true} if the call is denied (HTTP 403), {@code false}
+ * if the call succeeds (enforcement disabled).
+ *
+ * Must be called from {@code @BeforeAll} before any policies are attached.
+ */
+ private static boolean probeEnforcementEnabled() {
+ try (S3Client s3 = s3WithCredentials(userAccessKeyId, userSecretKey)) {
+ s3.listBuckets();
+ return false;
+ } catch (S3Exception e) {
+ return e.statusCode() == 403;
+ }
+ }
+
+ private static void assumeEnforcementEnabled() {
+ Assumptions.assumeTrue(enforcementEnabled,
+ "IAM enforcement is not enabled — set floci.services.iam.enforcement-enabled=true to run these tests");
+ }
+
+ // ── Tests ──────────────────────────────────────────────────────────────────
+
+ @Test
+ @Order(1)
+ @DisplayName("user with no policy is denied")
+ void noPolicyGetsDenied() {
+ assumeEnforcementEnabled();
+
+ try (S3Client s3 = s3WithCredentials(userAccessKeyId, userSecretKey)) {
+ assertThatThrownBy(s3::listBuckets)
+ .isInstanceOf(S3Exception.class)
+ .extracting(e -> ((S3Exception) e).statusCode())
+ .isEqualTo(403);
+ }
+ }
+
+ @Test
+ @Order(2)
+ @DisplayName("attached allow policy grants access")
+ void allowPolicyGrantsAccess() {
+ assumeEnforcementEnabled();
+
+ iam.attachUserPolicy(AttachUserPolicyRequest.builder()
+ .userName(USER).policyArn(allowPolicyArn).build());
+
+ try (S3Client s3 = s3WithCredentials(userAccessKeyId, userSecretKey)) {
+ assertThatCode(s3::listBuckets).doesNotThrowAnyException();
+ }
+ }
+
+ @Test
+ @Order(3)
+ @DisplayName("explicit inline Deny overrides attached Allow")
+ void explicitDenyOverridesAllow() {
+ assumeEnforcementEnabled();
+ // allow policy was attached in @Order(2); add an inline deny on top
+
+ iam.putUserPolicy(PutUserPolicyRequest.builder()
+ .userName(USER)
+ .policyName("inline-deny")
+ .policyDocument(DENY_S3_LIST_POLICY)
+ .build());
+
+ try (S3Client s3 = s3WithCredentials(userAccessKeyId, userSecretKey)) {
+ assertThatThrownBy(s3::listBuckets)
+ .isInstanceOf(S3Exception.class)
+ .extracting(e -> ((S3Exception) e).statusCode())
+ .isEqualTo(403);
+ }
+
+ // Remove the inline deny; restore to allow-only state
+ iam.deleteUserPolicy(DeleteUserPolicyRequest.builder()
+ .userName(USER).policyName("inline-deny").build());
+ }
+
+ @Test
+ @Order(4)
+ @DisplayName("wildcard action policy (s3:*) grants access")
+ void wildcardActionPolicyGrantsAccess() {
+ assumeEnforcementEnabled();
+ // Detach the specific allow; replace with a wildcard s3:* inline policy
+
+ iam.detachUserPolicy(DetachUserPolicyRequest.builder()
+ .userName(USER).policyArn(allowPolicyArn).build());
+ iam.putUserPolicy(PutUserPolicyRequest.builder()
+ .userName(USER)
+ .policyName("inline-s3-wildcard")
+ .policyDocument(ALLOW_S3_WILDCARD_POLICY)
+ .build());
+
+ try (S3Client s3 = s3WithCredentials(userAccessKeyId, userSecretKey)) {
+ assertThatCode(s3::listBuckets).doesNotThrowAnyException();
+ }
+
+ // Cleanup inline policy
+ iam.deleteUserPolicy(DeleteUserPolicyRequest.builder()
+ .userName(USER).policyName("inline-s3-wildcard").build());
+ }
+
+ @Test
+ @Order(5)
+ @DisplayName("assumed role with no policies is denied")
+ void assumedRoleNoPolicyGetsDenied() {
+ assumeEnforcementEnabled();
+ // Role has no policies attached
+
+ AssumeRoleResponse assumed = sts.assumeRole(AssumeRoleRequest.builder()
+ .roleArn(roleArn)
+ .roleSessionName("enf-test-no-policy")
+ .build());
+
+ try (S3Client s3 = s3WithSessionCredentials(
+ assumed.credentials().accessKeyId(),
+ assumed.credentials().secretAccessKey(),
+ assumed.credentials().sessionToken())) {
+ assertThatThrownBy(s3::listBuckets)
+ .isInstanceOf(S3Exception.class)
+ .extracting(e -> ((S3Exception) e).statusCode())
+ .isEqualTo(403);
+ }
+ }
+
+ @Test
+ @Order(6)
+ @DisplayName("assumed role with allow policy grants access")
+ void assumedRoleWithAllowPolicyGrantsAccess() {
+ assumeEnforcementEnabled();
+
+ iam.attachRolePolicy(AttachRolePolicyRequest.builder()
+ .roleName(ROLE).policyArn(allowPolicyArn).build());
+
+ AssumeRoleResponse assumed = sts.assumeRole(AssumeRoleRequest.builder()
+ .roleArn(roleArn)
+ .roleSessionName("enf-test-with-policy")
+ .build());
+
+ try (S3Client s3 = s3WithSessionCredentials(
+ assumed.credentials().accessKeyId(),
+ assumed.credentials().secretAccessKey(),
+ assumed.credentials().sessionToken())) {
+ assertThatCode(s3::listBuckets).doesNotThrowAnyException();
+ }
+ }
+}
diff --git a/docs/configuration/application-yml.md b/docs/configuration/application-yml.md
index 88362b0c7c..a67087c63c 100644
--- a/docs/configuration/application-yml.md
+++ b/docs/configuration/application-yml.md
@@ -108,6 +108,7 @@ floci:
iam:
enabled: true
+ enforcement-enabled: false # Set to true to enforce IAM policies on all requests
elasticache:
enabled: true
@@ -218,6 +219,7 @@ All keys in this table are declared on `EmulatorConfig` and accept environment v
| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for ECS task containers |
| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when task definition omits it |
| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when task definition omits it |
+| `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` | `false` | Enforce IAM identity-based policies on every request when `true` |
Per-queue SQS redrive policy (`maxReceiveCount`) is configured at queue creation time via `SetQueueAttributes` / `CreateQueue`, not as a global default.
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 91ccfb0c87..f24c1c6d27 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -16,6 +16,9 @@
### Policies
`CreatePolicy` · `GetPolicy` · `DeletePolicy` · `ListPolicies` · `CreatePolicyVersion` · `GetPolicyVersion` · `DeletePolicyVersion` · `ListPolicyVersions` · `SetDefaultPolicyVersion` · `TagPolicy` · `UntagPolicy` · `ListPolicyTags`
+### Permission Boundaries
+`PutUserPermissionsBoundary` · `DeleteUserPermissionsBoundary` · `PutRolePermissionsBoundary` · `DeleteRolePermissionsBoundary`
+
### Policy Attachments
`AttachUserPolicy` · `DetachUserPolicy` · `ListAttachedUserPolicies`
`AttachGroupPolicy` · `DetachGroupPolicy` · `ListAttachedGroupPolicies`
@@ -35,6 +38,96 @@
### Login Profiles
`CreateLoginProfile` · `DeleteLoginProfile` · `UpdateLoginProfile`
+## IAM Enforcement Mode
+
+By default Floci accepts any credentials without enforcing IAM policies — all requests are allowed through regardless of what policies are attached to the calling identity. This preserves backward compatibility and keeps the default setup frictionless.
+
+Setting `enforcement-enabled: true` activates the policy evaluator as a JAX-RS request filter. Every inbound request is then evaluated against the identity-based policies of the calling IAM user or assumed role before it reaches the service handler.
+
+### Enable enforcement
+
+**Environment variable:**
+```bash
+FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true
+```
+
+**application.yml:**
+```yaml
+floci:
+ services:
+ iam:
+ enforcement-enabled: true
+```
+
+### Evaluation rules
+
+Policy evaluation follows the standard AWS precedence:
+
+1. An explicit **Deny** in any policy → request is denied (HTTP 403 `AccessDeniedException`)
+2. An explicit **Allow** in any policy → request is allowed
+3. No matching statement → implicit deny (HTTP 403)
+
+### Bypass rules
+
+These identities always bypass enforcement (backward-compatible defaults):
+
+| Identity | Behaviour |
+|---|---|
+| Access key `test` (the default dev credential) | Always allowed — no policy lookup |
+| Unknown access key (not in IAM store) | Always allowed — backward-compatible with pre-existing keys |
+| No `Authorization` header | Allowed — unauthenticated path (e.g. health checks) |
+| Unresolvable IAM action for the request | Allowed — unknown mappings are permissive |
+
+### Supported policy features
+
+- **Identity-based policies**: inline user/group/role policies and managed attached policies.
+- **Session policies**: inline policies passed during `sts:AssumeRole`.
+- **Permission boundaries**: managed policies used to cap maximum permissions.
+- **Action/Resource patterns**: literal matches, wildcards (`*`, `?`), and `NotAction`/`NotResource` blocks.
+- **Conditions**: support for `Condition` blocks with multiple operators.
+- **Effects**: `Allow` and `Deny`.
+
+#### Supported Condition Operators:
+- `StringEquals`, `StringNotEquals`, `StringEqualsIgnoreCase`, `StringNotEqualsIgnoreCase`
+- `StringLike`, `StringNotLike`
+- `ArnEquals`, `ArnLike`, `ArnNotEquals`, `ArnNotLike`
+- `NumericEquals`, `NumericNotEquals`, `NumericLessThan`, `NumericGreaterThan` (and Equals variants)
+- `DateEquals`, `DateNotEquals`, `DateLessThan`, `DateGreaterThan` (and Equals variants)
+- `Bool`, `IpAddress`, `NotIpAddress`, `Null`
+- Supports `...IfExists` variants for all operators.
+
+**Not yet supported**: `NotPrincipal`, resource-based policies (S3 bucket policy, Lambda resource policy).
+
+### Assumed roles
+
+When a caller uses `sts:AssumeRole` the returned session credentials are registered internally. Subsequent requests signed with those session credentials are evaluated against:
+1. The **role's** attached and inline policies.
+2. The **session policy** (if provided during `AssumeRole`), acting as an intersection filter.
+
+### Example — minimal enforcement setup
+
+```bash
+export AWS_ENDPOINT_URL=http://localhost:4566
+
+# Create a user and get credentials
+aws iam create-user --user-name alice
+KEY=$(aws iam create-access-key --user-name alice --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text)
+AKID=$(echo $KEY | awk '{print $1}')
+SECRET=$(echo $KEY | awk '{print $2}')
+
+# Create and attach a policy that allows S3 list
+POLICY_ARN=$(aws iam create-policy \
+ --policy-name allow-s3-list \
+ --policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}]}' \
+ --query 'Policy.Arn' --output text)
+
+aws iam attach-user-policy --user-name alice --policy-arn $POLICY_ARN
+
+# alice can now list buckets
+AWS_ACCESS_KEY_ID=$AKID AWS_SECRET_ACCESS_KEY=$SECRET \
+ aws s3 ls
+```
+
## Examples
```bash
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 4ad166c5ac..22ab2e6027 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -270,6 +270,9 @@ public interface EmulatorConfig {
interface IamServiceConfig {
@WithDefault("true")
boolean enabled();
+
+ @WithDefault("false")
+ boolean enforcementEnabled();
}
interface ElastiCacheServiceConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
new file mode 100644
index 0000000000..1c8e7aedf0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -0,0 +1,130 @@
+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.IamPolicyEvaluator.Decision;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.Provider;
+import org.jboss.logging.Logger;
+
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * JAX-RS filter that enforces IAM policies on every incoming request when
+ * {@code floci.iam.enforcement-enabled = true}.
+ *
+ * <p>Bypass rules (request is always allowed through):
+ * <ul>
+ * <li>Enforcement is disabled (default)</li>
+ * <li>Access key is {@code "test"} (root/admin stand-in)</li>
+ * <li>Access key is not found in the IAM store (backward-compatible with pre-existing credentials)</li>
+ * <li>The action cannot be resolved (unknown mapping → permissive)</li>
+ * </ul>
+ *
+ * <p>Phase 1 evaluates identity-based policies only.
+ * Resource-based policies (S3 bucket policy, Lambda resource policy, etc.) are Phase 2.
+ */
+@Provider
+@ApplicationScoped
+public class IamEnforcementFilter implements ContainerRequestFilter {
+
+ private static final Logger LOG = Logger.getLogger(IamEnforcementFilter.class);
+
+ /** Extracts the access key ID from an AWS SigV4 Authorization header. */
+ private static final Pattern AKID_PATTERN =
+ Pattern.compile("Credential=([^/]+)/");
+
+ /** Extracts the credential-scope service name (e.g. "s3", "lambda"). */
+ private static final Pattern SERVICE_PATTERN =
+ Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
+
+ private final EmulatorConfig config;
+ private final IamService iamService;
+ private final IamPolicyEvaluator evaluator;
+ private final IamActionRegistry actionRegistry;
+ private final ResourceArnBuilder arnBuilder;
+
+ @Inject
+ public IamEnforcementFilter(EmulatorConfig config,
+ IamService iamService,
+ IamPolicyEvaluator evaluator,
+ IamActionRegistry actionRegistry,
+ ResourceArnBuilder arnBuilder) {
+ this.config = config;
+ this.iamService = iamService;
+ this.evaluator = evaluator;
+ this.actionRegistry = actionRegistry;
+ this.arnBuilder = arnBuilder;
+ }
+
+ @Override
+ public void filter(ContainerRequestContext ctx) {
+ if (!config.services().iam().enforcementEnabled()) {
+ return;
+ }
+
+ String auth = ctx.getHeaderString("Authorization");
+ if (auth == null) {
+ return;
+ }
+
+ String akid = extractAccessKeyId(auth);
+ if (akid == null || "test".equals(akid)) {
+ return; // root bypass
+ }
+
+ String credentialScope = extractCredentialScope(auth);
+ if (credentialScope == null) {
+ return;
+ }
+
+ String action = actionRegistry.resolve(credentialScope, ctx);
+ if (action == null) {
+ return; // unknown action → ALLOW (permissive)
+ }
+
+ List<String> policies = iamService.resolveCallerPolicies(akid);
+ if (policies == null) {
+ return; // unknown access key → bypass (backward-compat)
+ }
+
+ String region = config.defaultRegion();
+ String accountId = config.defaultAccountId();
+ String resource = arnBuilder.build(credentialScope, ctx, region, accountId);
+
+ Decision decision = evaluator.evaluate(policies, action, resource);
+ if (decision == Decision.DENY) {
+ LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
+ ctx.abortWith(accessDeniedResponse(action));
+ }
+ }
+
+ private String extractAccessKeyId(String auth) {
+ Matcher m = AKID_PATTERN.matcher(auth);
+ return m.find() ? m.group(1) : null;
+ }
+
+ private String extractCredentialScope(String auth) {
+ Matcher m = SERVICE_PATTERN.matcher(auth);
+ return m.find() ? m.group(1) : null;
+ }
+
+ private Response accessDeniedResponse(String action) {
+ String message = "User is not authorized to perform: " + action;
+ String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}";
+ return Response.status(403)
+ .type(MediaType.APPLICATION_JSON)
+ .entity(body)
+ .build();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java
new file mode 100644
index 0000000000..82d205ee06
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java
@@ -0,0 +1,124 @@
+package io.github.hectorvent.floci.services.iam;
+
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import org.jboss.logging.Logger;
+
+import java.util.List;
+import java.util.regex.Pattern;
+
+/**
+ * Maps (credentialScope, httpMethod, requestPath) → IAM action string.
+ *
+ * For Query-protocol services (SQS, SNS, IAM, STS, ...) the Action form
+ * parameter is mapped directly to {@code <service>:<Action>}.
+ *
+ * For REST-JSON services the first matching rule wins (specific before wildcard).
+ */
+@ApplicationScoped
+public class IamActionRegistry {
+
+ private static final Logger LOG = Logger.getLogger(IamActionRegistry.class);
+
+ private record ActionRule(String service, String method, Pattern pathPattern, String action) {}
+
+ private static final List<ActionRule> RULES = List.of(
+ // ── S3 ─────────────────────────────────────────────────────────────────
+ rule("s3", "GET", "^/?$", "s3:ListAllMyBuckets"),
+ rule("s3", "PUT", "^/[^/]+/?$", "s3:CreateBucket"),
+ rule("s3", "DELETE", "^/[^/]+/?$", "s3:DeleteBucket"),
+ rule("s3", "HEAD", "^/[^/]+/?$", "s3:ListBucket"),
+ rule("s3", "GET", "^/[^/]+/?$", "s3:ListBucket"),
+ rule("s3", "GET", "^/[^/]+/.+", "s3:GetObject"),
+ rule("s3", "PUT", "^/[^/]+/.+", "s3:PutObject"),
+ rule("s3", "DELETE", "^/[^/]+/.+", "s3:DeleteObject"),
+ rule("s3", "HEAD", "^/[^/]+/.+", "s3:GetObject"),
+
+ // ── Lambda ──────────────────────────────────────────────────────────────
+ rule("lambda", "GET", ".*/functions$", "lambda:ListFunctions"),
+ rule("lambda", "POST", ".*/functions$", "lambda:CreateFunction"),
+ rule("lambda", "GET", ".*/functions/[^/]+$", "lambda:GetFunction"),
+ rule("lambda", "PUT", ".*/functions/[^/]+/code$", "lambda:UpdateFunctionCode"),
+ rule("lambda", "PUT", ".*/functions/[^/]+/configuration$", "lambda:UpdateFunctionConfiguration"),
+ rule("lambda", "DELETE", ".*/functions/[^/]+$", "lambda:DeleteFunction"),
+ rule("lambda", "POST", ".*/functions/[^/]+/invocations$", "lambda:InvokeFunction"),
+ rule("lambda", "GET", ".*/functions/[^/]+/aliases$", "lambda:ListAliases"),
+ rule("lambda", "POST", ".*/functions/[^/]+/aliases$", "lambda:CreateAlias"),
+ rule("lambda", "GET", ".*/functions/[^/]+/aliases/[^/]+$", "lambda:GetAlias"),
+ rule("lambda", "PUT", ".*/functions/[^/]+/aliases/[^/]+$", "lambda:UpdateAlias"),
+ rule("lambda", "DELETE", ".*/functions/[^/]+/aliases/[^/]+$", "lambda:DeleteAlias"),
+ rule("lambda", "GET", ".*/functions/[^/]+/policy$", "lambda:GetPolicy"),
+ rule("lambda", "POST", ".*/functions/[^/]+/policy$", "lambda:AddPermission"),
+ rule("lambda", "DELETE", ".*/functions/[^/]+/policy/.+", "lambda:RemovePermission"),
+ rule("lambda", "GET", ".*/event-source-mappings$", "lambda:ListEventSourceMappings"),
+ rule("lambda", "POST", ".*/event-source-mappings$", "lambda:CreateEventSourceMapping"),
+ rule("lambda", "DELETE", ".*/event-source-mappings/[^/]+$", "lambda:DeleteEventSourceMapping"),
+ rule("lambda", "GET", ".*/functions/[^/]+/url$", "lambda:GetFunctionUrlConfig"),
+ rule("lambda", "POST", ".*/functions/[^/]+/url$", "lambda:CreateFunctionUrlConfig"),
+ rule("lambda", "PUT", ".*/functions/[^/]+/url$", "lambda:UpdateFunctionUrlConfig"),
+ rule("lambda", "DELETE", ".*/functions/[^/]+/url$", "lambda:DeleteFunctionUrlConfig"),
+
+ // ── DynamoDB (JSON 1.1, action from X-Amz-Target handled separately) ──
+ // Handled via Query-style action extraction in the filter
+
+ // ── API Gateway ────────────────────────────────────────────────────────
+ rule("apigateway", "GET", ".*/restapis$", "apigateway:GET"),
+ rule("apigateway", "POST", ".*/restapis$", "apigateway:POST"),
+ rule("apigateway", "GET", ".*/restapis/.+", "apigateway:GET"),
+ rule("apigateway", "PUT", ".*/restapis/.+", "apigateway:PUT"),
+ rule("apigateway", "PATCH", ".*/restapis/.+", "apigateway:PATCH"),
+ rule("apigateway", "DELETE", ".*/restapis/.+", "apigateway:DELETE"),
+ rule("apigateway", "POST", ".*/restapis/.+", "apigateway:POST"),
+
+ // ── Kinesis ────────────────────────────────────────────────────────────
+ rule("kinesis", "POST", ".*", "kinesis:*")
+ );
+
+ private static ActionRule rule(String service, String method, String path, String action) {
+ return new ActionRule(service, method, Pattern.compile(path, Pattern.CASE_INSENSITIVE), action);
+ }
+
+ /**
+ * Resolves the IAM action for an incoming request.
+ *
+ * For Query-protocol services the action comes directly from the {@code Action}
+ * form param (e.g. {@code sqs:SendMessage}).
+ *
+ * For JSON 1.1 protocol the action comes from {@code X-Amz-Target}
+ * (e.g. {@code DynamoDB_20120810.PutItem} → {@code dynamodb:PutItem}).
+ *
+ * For REST-JSON services the action is derived from the path rule table.
+ *
+ * Returns {@code null} when the action is unknown (caller treats this as ALLOW).
+ */
+ public String resolve(String credentialScope, ContainerRequestContext ctx) {
+ // Query-protocol: Action form param → service:Action
+ String queryAction = ctx.getUriInfo().getQueryParameters().getFirst("Action");
+ if (queryAction != null && !queryAction.isBlank()) {
+ return credentialScope + ":" + queryAction;
+ }
+
+ // JSON 1.1: X-Amz-Target → service:OperationName
+ String target = ctx.getHeaderString("X-Amz-Target");
+ if (target != null && target.contains(".")) {
+ String operationName = target.substring(target.lastIndexOf('.') + 1);
+ return credentialScope + ":" + operationName;
+ }
+
+ // REST-JSON: match against rule table
+ String method = ctx.getMethod().toUpperCase();
+ String path = ctx.getUriInfo().getPath();
+ if (!path.startsWith("/")) path = "/" + path;
+
+ for (ActionRule rule : RULES) {
+ if (rule.service().equals(credentialScope)
+ && rule.method().equals(method)
+ && rule.pathPattern().matcher(path).find()) {
+ return rule.action();
+ }
+ }
+
+ LOG.debugv("No action mapping for {0} {1} {2} — defaulting to ALLOW", credentialScope, method, path);
+ return null;
+ }
+}
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
new file mode 100644
index 0000000000..41041818ca
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
@@ -0,0 +1,455 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import io.github.hectorvent.floci.services.iam.model.PolicyStatement;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Evaluates IAM policy documents against a requested action and resource.
+ *
+ * <p>Implements the AWS policy evaluation logic across Phases 1-4:
+ * <ul>
+ * <li>Phase 1: identity-based policies (inline + attached + groups)</li>
+ * <li>Phase 2: resource-based policies (same-account grant semantics)</li>
+ * <li>Phase 3: session policies + permission boundaries</li>
+ * <li>Phase 4: condition operators, NotAction, NotResource</li>
+ * </ul>
+ *
+ * <p>Evaluation algorithm (AWS order of precedence):
+ * <ol>
+ * <li>Explicit Deny in ANY policy → DENY</li>
+ * <li>identityAllow OR resourceAllow</li>
+ * <li>AND (no session policy OR sessionAllow)</li>
+ * <li>AND (no boundary OR boundaryAllow)</li>
+ * <li>→ ALLOW</li>
+ * <li>Otherwise → DENY (implicit)</li>
+ * </ol>
+ */
+@ApplicationScoped
+public class IamPolicyEvaluator {
+
+ public enum Decision { ALLOW, DENY }
+
+ private static final Logger LOG = Logger.getLogger(IamPolicyEvaluator.class);
+
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public IamPolicyEvaluator(ObjectMapper objectMapper) {
+ this.objectMapper = objectMapper;
+ }
+
+ /**
+ * Full evaluation including resource policies, session policy, boundary, and conditions.
+ *
+ * @param caller identity context (identity policies, optional session policy, optional boundary)
+ * @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
+ * @return {@link Decision#ALLOW} or {@link Decision#DENY}
+ */
+ public Decision evaluate(CallerContext caller,
+ List<String> resourcePolicies,
+ String action,
+ String resource,
+ Map<String, String> conditionCtx) {
+ Map<String, String> ctx = conditionCtx == null ? Map.of() : conditionCtx;
+
+ List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
+ List<PolicyStatement> resourceStmts = resourcePolicies == null ? List.of() : parseAll(resourcePolicies);
+ List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null
+ ? null : parseAll(List.of(caller.sessionPolicyDocument()));
+ List<PolicyStatement> boundaryStmts = caller.boundaryPolicyDocument() == null
+ ? null : parseAll(List.of(caller.boundaryPolicyDocument()));
+
+ // 1. Explicit deny in ANY policy → DENY immediately
+ if (anyExplicitDeny(identityStmts, action, resource, ctx)
+ || anyExplicitDeny(resourceStmts, action, resource, ctx)
+ || (sessionStmts != null && anyExplicitDeny(sessionStmts, action, resource, ctx))
+ || (boundaryStmts != null && anyExplicitDeny(boundaryStmts, action, resource, ctx))) {
+ return Decision.DENY;
+ }
+
+ // 2. Base grant: identity OR resource-based policy must allow
+ boolean identityAllow = anyExplicitAllow(identityStmts, action, resource, ctx);
+ boolean resourceAllow = anyExplicitAllow(resourceStmts, action, resource, ctx);
+ if (!identityAllow && !resourceAllow) {
+ return Decision.DENY;
+ }
+
+ // 3. Session policy (if present) must also allow (intersection)
+ if (sessionStmts != null && !anyExplicitAllow(sessionStmts, action, resource, ctx)) {
+ return Decision.DENY;
+ }
+
+ // 4. Permission boundary (if present) must also allow (caps maximum permissions)
+ if (boundaryStmts != null && !anyExplicitAllow(boundaryStmts, action, resource, ctx)) {
+ return Decision.DENY;
+ }
+
+ return Decision.ALLOW;
+ }
+
+ /**
+ * Convenience overload: identity policies only, no conditions.
+ * Backward-compatible with Phase 1 callers.
+ */
+ public Decision evaluate(List<String> policyDocuments, String action, String resource) {
+ return evaluate(CallerContext.of(policyDocuments), null, action, resource, null);
+ }
+
+ /**
+ * Evaluates a standalone set of policy documents — used by SimulateCustomPolicy.
+ */
+ public Decision simulateCustomPolicy(List<String> policyDocuments,
+ String action,
+ String resource,
+ Map<String, String> conditionCtx) {
+ return evaluate(CallerContext.of(policyDocuments), null, action, resource, conditionCtx);
+ }
+
+ // -----------------------------------------------------------------------
+ // Statement matching
+ // -----------------------------------------------------------------------
+
+ private boolean anyExplicitDeny(List<PolicyStatement> stmts, String action, String resource,
+ Map<String, String> ctx) {
+ for (PolicyStatement stmt : stmts) {
+ if (stmt.isDeny() && matchesStatement(stmt, action, resource, ctx)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean anyExplicitAllow(List<PolicyStatement> stmts, String action, String resource,
+ Map<String, String> ctx) {
+ for (PolicyStatement stmt : stmts) {
+ if (stmt.isAllow() && matchesStatement(stmt, action, resource, ctx)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean matchesStatement(PolicyStatement stmt, String action, String resource,
+ Map<String, String> ctx) {
+ return matchesAction(stmt, action)
+ && matchesResource(stmt, resource)
+ && matchesConditions(stmt.getConditions(), ctx);
+ }
+
+ /** Action: matches if any Action pattern matches; NotAction: matches if NO pattern matches. */
+ private boolean matchesAction(PolicyStatement stmt, String action) {
+ if (stmt.getActions() != null) {
+ return matchesAny(stmt.getActions(), action);
+ }
+ if (stmt.getNotActions() != null) {
+ return !matchesAny(stmt.getNotActions(), action);
+ }
+ return false;
+ }
+
+ /** Resource: matches if any Resource pattern matches; NotResource: matches if NO pattern matches. */
+ private boolean matchesResource(PolicyStatement stmt, String resource) {
+ if (stmt.getResources() != null) {
+ return matchesAny(stmt.getResources(), resource);
+ }
+ if (stmt.getNotResources() != null) {
+ return !matchesAny(stmt.getNotResources(), resource);
+ }
+ return false;
+ }
+
+ private boolean matchesAny(List<String> patterns, String value) {
+ if (patterns == null) {
+ return false;
+ }
+ for (String pattern : patterns) {
+ if (globMatches(pattern, value)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // -----------------------------------------------------------------------
+ // Condition evaluation (Phase 4)
+ // -----------------------------------------------------------------------
+
+ /**
+ * Evaluates all condition blocks. AND between blocks, OR within each block's value list.
+ * Returns true if ALL blocks pass (or there are no conditions).
+ */
+ private boolean matchesConditions(Map<String, Map<String, List<String>>> conditions,
+ Map<String, String> ctx) {
+ if (conditions == null || conditions.isEmpty()) {
+ return true;
+ }
+ for (Map.Entry<String, Map<String, List<String>>> entry : conditions.entrySet()) {
+ if (!evaluateConditionBlock(entry.getKey(), entry.getValue(), ctx)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean evaluateConditionBlock(String operator,
+ Map<String, List<String>> keyValueMap,
+ Map<String, String> ctx) {
+ boolean ifExists = operator.endsWith("IfExists");
+ String baseOp = ifExists ? operator.substring(0, operator.length() - "IfExists".length()) : operator;
+
+ for (Map.Entry<String, List<String>> entry : keyValueMap.entrySet()) {
+ String condKey = entry.getKey().toLowerCase();
+ List<String> condValues = entry.getValue();
+ String ctxValue = ctx.get(condKey);
+
+ if (ctxValue == null) {
+ if ("Null".equalsIgnoreCase(baseOp)) {
+ // Null: {key: "true"} → key must be absent → pass when any condValue is "true"
+ boolean expectAbsent = condValues.stream().anyMatch("true"::equalsIgnoreCase);
+ if (!expectAbsent) {
+ return false;
+ }
+ continue;
+ }
+ if (ifExists) {
+ continue; // key missing + IfExists → pass this key
+ }
+ return false; // key missing, no IfExists → fail entire block
+ }
+
+ if ("Null".equalsIgnoreCase(baseOp)) {
+ // Key is present — Null:{key:"true"} should fail, Null:{key:"false"} should pass
+ boolean expectAbsent = condValues.stream().anyMatch("true"::equalsIgnoreCase);
+ if (expectAbsent) {
+ return false; // expected absent but key has value
+ }
+ continue;
+ }
+
+ // OR across condValues for this key
+ boolean keyMatch = false;
+ for (String condValue : condValues) {
+ if (evaluateSingleCondition(baseOp, ctxValue, condValue)) {
+ keyMatch = true;
+ break;
+ }
+ }
+ if (!keyMatch) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean evaluateSingleCondition(String operator, String ctxValue, String condValue) {
+ return switch (operator) {
+ case "StringEquals" -> ctxValue.equals(condValue);
+ case "StringNotEquals" -> !ctxValue.equals(condValue);
+ case "StringEqualsIgnoreCase" -> ctxValue.equalsIgnoreCase(condValue);
+ case "StringNotEqualsIgnoreCase" -> !ctxValue.equalsIgnoreCase(condValue);
+ case "StringLike" -> globMatches(condValue, ctxValue);
+ case "StringNotLike" -> !globMatches(condValue, ctxValue);
+ case "ArnEquals", "ArnLike" -> globMatches(condValue, ctxValue);
+ case "ArnNotEquals", "ArnNotLike"-> !globMatches(condValue, ctxValue);
+ case "Bool" -> Boolean.parseBoolean(condValue) == Boolean.parseBoolean(ctxValue);
+ case "NumericEquals" -> compareNumeric(ctxValue, condValue) == 0;
+ case "NumericNotEquals" -> compareNumeric(ctxValue, condValue) != 0;
+ case "NumericLessThan" -> compareNumeric(ctxValue, condValue) < 0;
+ case "NumericLessThanEquals" -> compareNumeric(ctxValue, condValue) <= 0;
+ case "NumericGreaterThan" -> compareNumeric(ctxValue, condValue) > 0;
+ case "NumericGreaterThanEquals" -> compareNumeric(ctxValue, condValue) >= 0;
+ case "DateEquals" -> compareDates(ctxValue, condValue) == 0;
+ case "DateNotEquals" -> compareDates(ctxValue, condValue) != 0;
+ case "DateLessThan" -> compareDates(ctxValue, condValue) < 0;
+ case "DateLessThanEquals" -> compareDates(ctxValue, condValue) <= 0;
+ case "DateGreaterThan" -> compareDates(ctxValue, condValue) > 0;
+ case "DateGreaterThanEquals" -> compareDates(ctxValue, condValue) >= 0;
+ case "IpAddress" -> matchesIpAddress(condValue, ctxValue);
+ case "NotIpAddress" -> !matchesIpAddress(condValue, ctxValue);
+ default -> {
+ LOG.warnv("Unsupported condition operator: {0} — treating as no-match", operator);
+ yield false;
+ }
+ };
+ }
+
+ private int compareNumeric(String ctxValue, String condValue) {
+ try {
+ return Double.compare(Double.parseDouble(ctxValue), Double.parseDouble(condValue));
+ } catch (NumberFormatException e) {
+ return 0;
+ }
+ }
+
+ private int compareDates(String ctxValue, String condValue) {
+ try {
+ return Instant.parse(ctxValue).compareTo(Instant.parse(condValue));
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+ private boolean matchesIpAddress(String condValue, String ctxValue) {
+ if (condValue.contains("/")) {
+ return matchesCidr(condValue, ctxValue);
+ }
+ return condValue.equals(ctxValue);
+ }
+
+ private boolean matchesCidr(String cidr, String ip) {
+ try {
+ String[] parts = cidr.split("/");
+ int prefix = Integer.parseInt(parts[1]);
+ long cidrAddr = ipToLong(parts[0]);
+ long ipAddr = ipToLong(ip);
+ long mask = prefix == 0 ? 0L : (0xFFFFFFFFL << (32 - prefix)) & 0xFFFFFFFFL;
+ return (cidrAddr & mask) == (ipAddr & mask);
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ private long ipToLong(String ip) {
+ String[] octets = ip.split("\\.");
+ long result = 0;
+ for (String octet : octets) {
+ result = (result << 8) | Integer.parseInt(octet);
+ }
+ return result;
+ }
+
+ // -----------------------------------------------------------------------
+ // Glob matching (case-insensitive, supports * and ?)
+ // -----------------------------------------------------------------------
+
+ /**
+ * Case-insensitive glob matching supporting {@code *} (any sequence) and {@code ?} (any char).
+ */
+ public static boolean globMatches(String pattern, String value) {
+ if (pattern == null || value == null) {
+ return false;
+ }
+ return globMatchesHelper(pattern.toLowerCase(), value.toLowerCase(), 0, 0);
+ }
+
+ private static boolean globMatchesHelper(String pat, String val, int pi, int vi) {
+ while (pi < pat.length() && vi < val.length()) {
+ char p = pat.charAt(pi);
+ if (p == '*') {
+ while (pi < pat.length() && pat.charAt(pi) == '*') {
+ pi++;
+ }
+ if (pi == pat.length()) {
+ return true;
+ }
+ for (int i = vi; i <= val.length(); i++) {
+ if (globMatchesHelper(pat, val, pi, i)) {
+ return true;
+ }
+ }
+ return false;
+ } else if (p == '?' || p == val.charAt(vi)) {
+ pi++;
+ vi++;
+ } else {
+ return false;
+ }
+ }
+ while (pi < pat.length() && pat.charAt(pi) == '*') {
+ pi++;
+ }
+ return pi == pat.length() && vi == val.length();
+ }
+
+ // -----------------------------------------------------------------------
+ // Policy document parsing
+ // -----------------------------------------------------------------------
+
+ private List<PolicyStatement> parseAll(List<String> documents) {
+ List<PolicyStatement> result = new ArrayList<>();
+ if (documents == null) {
+ return result;
+ }
+ for (String doc : documents) {
+ try {
+ result.addAll(parseStatements(doc));
+ } catch (Exception e) {
+ LOG.warnv("Failed to parse policy document: {0}", e.getMessage());
+ }
+ }
+ return result;
+ }
+
+ private List<PolicyStatement> parseStatements(String document) throws Exception {
+ JsonNode root = objectMapper.readTree(document);
+ JsonNode stmtNode = root.path("Statement");
+ List<PolicyStatement> result = new ArrayList<>();
+ if (stmtNode.isArray()) {
+ for (JsonNode s : stmtNode) {
+ result.add(parseStatement(s));
+ }
+ } else if (stmtNode.isObject()) {
+ result.add(parseStatement(stmtNode));
+ }
+ return result;
+ }
+
+ private PolicyStatement parseStatement(JsonNode stmt) {
+ String effect = stmt.path("Effect").asText("Allow");
+ List<String> actions = nodeToList(stmt.get("Action"));
+ List<String> notActions = nodeToList(stmt.get("NotAction"));
+ List<String> resources = nodeToList(stmt.get("Resource"));
+ List<String> notResources= nodeToList(stmt.get("NotResource"));
+ Map<String, Map<String, List<String>>> conditions = parseConditions(stmt.get("Condition"));
+ return new PolicyStatement(
+ effect,
+ actions.isEmpty() ? null : actions,
+ notActions.isEmpty() ? null : notActions,
+ resources.isEmpty() ? null : resources,
+ notResources.isEmpty()? null : notResources,
+ conditions);
+ }
+
+ private Map<String, Map<String, List<String>>> parseConditions(JsonNode condNode) {
+ if (condNode == null || condNode.isNull() || !condNode.isObject()) {
+ return null;
+ }
+ Map<String, Map<String, List<String>>> result = new LinkedHashMap<>();
+ condNode.fields().forEachRemaining(opEntry -> {
+ Map<String, List<String>> kvMap = new LinkedHashMap<>();
+ opEntry.getValue().fields().forEachRemaining(kvEntry ->
+ kvMap.put(kvEntry.getKey(), nodeToList(kvEntry.getValue())));
+ result.put(opEntry.getKey(), kvMap);
+ });
+ return result.isEmpty() ? null : result;
+ }
+
+ private List<String> nodeToList(JsonNode node) {
+ List<String> list = new ArrayList<>();
+ if (node == null) {
+ return list;
+ }
+ if (node.isTextual()) {
+ list.add(node.asText());
+ } else if (node.isArray()) {
+ for (JsonNode item : node) {
+ list.add(item.asText());
+ }
+ }
+ return list;
+ }
+}
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 2e3be29212..504ba55a1a 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
@@ -136,6 +136,12 @@ public class IamQueryHandler {
case "RemoveRoleFromInstanceProfile" -> handleRemoveRoleFromInstanceProfile(params);
case "ListInstanceProfilesForRole" -> handleListInstanceProfilesForRole(params);
+ // Permission Boundaries
+ case "PutUserPermissionsBoundary" -> handlePutUserPermissionsBoundary(params);
+ case "DeleteUserPermissionsBoundary" -> handleDeleteUserPermissionsBoundary(params);
+ case "PutRolePermissionsBoundary" -> handlePutRolePermissionsBoundary(params);
+ case "DeleteRolePermissionsBoundary" -> handleDeleteRolePermissionsBoundary(params);
+
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.IAM, 400);
};
@@ -675,6 +681,36 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListInstanceProfilesForRole", AwsNamespaces.IAM, xml.build())).build();
}
+ // =========================================================================
+ // Permission Boundaries
+ // =========================================================================
+
+ private Response handlePutUserPermissionsBoundary(MultivaluedMap<String, String> params) {
+ String userName = getParam(params, "UserName");
+ String boundaryArn = getParam(params, "PermissionsBoundary");
+ iamService.putUserPermissionsBoundary(userName, boundaryArn);
+ return Response.ok(AwsQueryResponse.envelope("PutUserPermissionsBoundary", AwsNamespaces.IAM, "")).build();
+ }
+
+ private Response handleDeleteUserPermissionsBoundary(MultivaluedMap<String, String> params) {
+ String userName = getParam(params, "UserName");
+ iamService.deleteUserPermissionsBoundary(userName);
+ return Response.ok(AwsQueryResponse.envelope("DeleteUserPermissionsBoundary", AwsNamespaces.IAM, "")).build();
+ }
+
+ private Response handlePutRolePermissionsBoundary(MultivaluedMap<String, String> params) {
+ String roleName = getParam(params, "RoleName");
+ String boundaryArn = getParam(params, "PermissionsBoundary");
+ iamService.putRolePermissionsBoundary(roleName, boundaryArn);
+ return Response.ok(AwsQueryResponse.envelope("PutRolePermissionsBoundary", AwsNamespaces.IAM, "")).build();
+ }
+
+ private Response handleDeleteRolePermissionsBoundary(MultivaluedMap<String, String> params) {
+ String roleName = getParam(params, "RoleName");
+ iamService.deleteRolePermissionsBoundary(roleName);
+ return Response.ok(AwsQueryResponse.envelope("DeleteRolePermissionsBoundary", AwsNamespaces.IAM, "")).build();
+ }
+
// =========================================================================
// XML serialization helpers
// =========================================================================
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 f55946d871..ea943791ab 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
@@ -11,6 +11,8 @@ 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 io.github.hectorvent.floci.services.iam.model.SessionCredential;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
@@ -18,6 +20,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
+import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.ArrayList;
import java.util.List;
@@ -39,6 +42,7 @@ public class IamService {
private final StorageBackend<String, IamPolicy> policies;
private final StorageBackend<String, AccessKey> accessKeys;
private final StorageBackend<String, InstanceProfile> instanceProfiles;
+ private final StorageBackend<String, SessionCredential> sessions;
private final String accountId;
@Inject
@@ -50,6 +54,7 @@ public class IamService {
storageFactory.create("iam", "iam-policies.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-access-keys.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-instance-profiles.json", new TypeReference<>() {}),
+ storageFactory.create("iam", "iam-sessions.json", new TypeReference<>() {}),
config.defaultAccountId()
);
}
@@ -60,6 +65,7 @@ public class IamService {
StorageBackend<String, IamPolicy> policies,
StorageBackend<String, AccessKey> accessKeys,
StorageBackend<String, InstanceProfile> instanceProfiles,
+ StorageBackend<String, SessionCredential> sessions,
String accountId) {
this.users = users;
this.groups = groups;
@@ -67,6 +73,7 @@ public class IamService {
this.policies = policies;
this.accessKeys = accessKeys;
this.instanceProfiles = instanceProfiles;
+ this.sessions = sessions;
this.accountId = accountId;
}
@@ -799,10 +806,194 @@ public class IamService {
return accountId;
}
- public java.util.Optional<String> findSecretKey(String accessKeyId) {
+ public Optional<String> findSecretKey(String accessKeyId) {
return accessKeys.get(accessKeyId).map(AccessKey::getSecretAccessKey);
}
+ // =========================================================================
+ // IAM Enforcement — session tracking and policy collection
+ // =========================================================================
+
+ /**
+ * Stores an assumed-role session so the enforcement filter can resolve its policies.
+ */
+ public void registerSession(String sessionAccessKeyId, String roleArn, java.time.Instant expiration) {
+ sessions.put(sessionAccessKeyId, new SessionCredential(sessionAccessKeyId, roleArn, expiration));
+ }
+
+ /**
+ * Stores an assumed-role session with an optional inline session policy document.
+ */
+ public void registerSession(String sessionAccessKeyId, String roleArn, java.time.Instant expiration,
+ String sessionPolicyDocument) {
+ sessions.put(sessionAccessKeyId,
+ new SessionCredential(sessionAccessKeyId, roleArn, expiration, sessionPolicyDocument));
+ }
+
+ /**
+ * Resolves the full caller context for the given access key, including identity policies,
+ * optional session policy, and optional permission boundary.
+ *
+ * <p>Returns {@code null} if the access key is unknown (bypass — backward-compatible).
+ */
+ public CallerContext resolveCallerContext(String accessKeyId) {
+ // Check user access keys
+ Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);
+ if (akOpt.isPresent()) {
+ String userName = akOpt.get().getUserName();
+ List<String> identityPolicies = collectUserPolicies(userName);
+ String boundaryDoc = resolveUserBoundaryDocument(userName);
+ return new CallerContext(identityPolicies, null, boundaryDoc);
+ }
+
+ // Check assumed-role sessions
+ 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 null; // expired — unknown key → bypass
+ }
+ List<String> identityPolicies = collectRolePolicies(session.getRoleArn());
+ String boundaryDoc = resolveRoleBoundaryDocument(session.getRoleArn());
+ return new CallerContext(identityPolicies, session.getSessionPolicyDocument(), boundaryDoc);
+ }
+
+ // Unknown key — bypass
+ return null;
+ }
+
+ /**
+ * Collects all identity-based policy documents applicable to the caller identified
+ * by {@code accessKeyId}.
+ *
+ * <p>Returns {@code null} if the access key is unknown (bypass — backward-compatible).
+ * Returns an empty list if the key is known but has no policies attached (implicit deny).
+ *
+ * <p>Order: inline policies first, then attached managed policies.
+ */
+ public List<String> resolveCallerPolicies(String accessKeyId) {
+ CallerContext ctx = resolveCallerContext(accessKeyId);
+ return ctx == null ? null : ctx.identityPolicies();
+ }
+
+ private String resolveUserBoundaryDocument(String userName) {
+ return users.get(userName)
+ .map(IamUser::getPermissionsBoundaryArn)
+ .flatMap(arn -> policies.get(arn))
+ .map(IamPolicy::getDefaultDocument)
+ .orElse(null);
+ }
+
+ private String resolveRoleBoundaryDocument(String roleArn) {
+ String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
+ return roles.get(roleName)
+ .map(IamRole::getPermissionsBoundaryArn)
+ .flatMap(arn -> policies.get(arn))
+ .map(IamPolicy::getDefaultDocument)
+ .orElse(null);
+ }
+
+ // =========================================================================
+ // Permission Boundaries
+ // =========================================================================
+
+ public void putUserPermissionsBoundary(String userName, String permissionsBoundaryArn) {
+ getPolicy(permissionsBoundaryArn); // validate policy exists
+ IamUser user = getUser(userName);
+ user.setPermissionsBoundaryArn(permissionsBoundaryArn);
+ users.put(userName, user);
+ LOG.infov("Set permissions boundary for user {0}: {1}", userName, permissionsBoundaryArn);
+ }
+
+ public void deleteUserPermissionsBoundary(String userName) {
+ IamUser user = getUser(userName);
+ if (user.getPermissionsBoundaryArn() == null) {
+ throw new AwsException("NoSuchEntity",
+ "User " + userName + " does not have a permissions boundary.", 404);
+ }
+ user.setPermissionsBoundaryArn(null);
+ users.put(userName, user);
+ LOG.infov("Deleted permissions boundary for user: {0}", userName);
+ }
+
+ public void putRolePermissionsBoundary(String roleName, String permissionsBoundaryArn) {
+ getPolicy(permissionsBoundaryArn); // validate policy exists
+ IamRole role = getRole(roleName);
+ role.setPermissionsBoundaryArn(permissionsBoundaryArn);
+ roles.put(roleName, role);
+ LOG.infov("Set permissions boundary for role {0}: {1}", roleName, permissionsBoundaryArn);
+ }
+
+ public void deleteRolePermissionsBoundary(String roleName) {
+ IamRole role = getRole(roleName);
+ if (role.getPermissionsBoundaryArn() == null) {
+ throw new AwsException("NoSuchEntity",
+ "Role " + roleName + " does not have a permissions boundary.", 404);
+ }
+ role.setPermissionsBoundaryArn(null);
+ roles.put(roleName, role);
+ LOG.infov("Deleted permissions boundary for role: {0}", roleName);
+ }
+
+ private List<String> collectUserPolicies(String userName) {
+ Optional<IamUser> userOpt = users.get(userName);
+ if (userOpt.isEmpty()) {
+ return null;
+ }
+ IamUser user = userOpt.get();
+
+ // User inline policies
+ List<String> docs = new ArrayList<>(user.getInlinePolicies().values());
+
+ // User attached managed policies
+ for (String arn : user.getAttachedPolicyArns()) {
+ Optional<IamPolicy> p = policies.get(arn);
+ if (p.isPresent() && p.get().getDefaultDocument() != null) {
+ docs.add(p.get().getDefaultDocument());
+ }
+ }
+
+ // Group policies
+ for (String groupName : user.getGroupNames()) {
+ Optional<IamGroup> groupOpt = groups.get(groupName);
+ if (groupOpt.isEmpty()) continue;
+ IamGroup group = groupOpt.get();
+ docs.addAll(group.getInlinePolicies().values());
+ for (String arn : group.getAttachedPolicyArns()) {
+ Optional<IamPolicy> p = policies.get(arn);
+ if (p.isPresent() && p.get().getDefaultDocument() != null) {
+ docs.add(p.get().getDefaultDocument());
+ }
+ }
+ }
+
+ return docs;
+ }
+
+ private List<String> collectRolePolicies(String roleArn) {
+ String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
+ Optional<IamRole> roleOpt = roles.get(roleName);
+ if (roleOpt.isEmpty()) {
+ return null;
+ }
+ IamRole role = roleOpt.get();
+ List<String> docs = new ArrayList<>();
+
+ // Role inline policies
+ docs.addAll(role.getInlinePolicies().values());
+
+ // Role attached managed policies
+ for (String arn : role.getAttachedPolicyArns()) {
+ Optional<IamPolicy> p = policies.get(arn);
+ if (p.isPresent() && p.get().getDefaultDocument() != null) {
+ docs.add(p.get().getDefaultDocument());
+ }
+ }
+
+ return docs;
+ }
+
private String iamArn(String resourceType, String path, String name) {
return "arn:aws:iam::" + accountId + ":" + resourceType + path + name;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
new file mode 100644
index 0000000000..27372e7fb4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
@@ -0,0 +1,123 @@
+package io.github.hectorvent.floci.services.iam;
+
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.ws.rs.container.ContainerRequestContext;
+
+/**
+ * Constructs the target resource ARN for a request so the policy evaluator
+ * can match it against Resource patterns in policy documents.
+ *
+ * Returns {@code *} when the resource cannot be determined, which matches
+ * permissive wildcard policies.
+ */
+@ApplicationScoped
+public class ResourceArnBuilder {
+
+ public String build(String credentialScope, ContainerRequestContext ctx,
+ String region, String accountId) {
+ String path = ctx.getUriInfo().getPath();
+ return switch (credentialScope) {
+ case "s3" -> buildS3Arn(path);
+ case "lambda" -> buildLambdaArn(path, region, accountId);
+ case "sqs" -> buildSqsArn(ctx, region, accountId);
+ case "sns" -> buildSnsArn(ctx, region, accountId);
+ case "dynamodb" -> buildDynamoDbArn(ctx, region, accountId);
+ case "kinesis" -> buildKinesisArn(ctx, region, accountId);
+ case "secretsmanager" -> buildSecretsManagerArn(ctx, region, accountId);
+ case "ssm" -> buildSsmArn(ctx, region, accountId);
+ case "kms" -> buildKmsArn(path, region, accountId);
+ default -> "*";
+ };
+ }
+
+ // ── S3 ──────────────────────────────────────────────────────────────────────
+ private String buildS3Arn(String path) {
+ // path: /bucket or /bucket/key
+ String stripped = path.startsWith("/") ? path.substring(1) : path;
+ if (stripped.isEmpty()) {
+ return "arn:aws:s3:::*";
+ }
+ int slash = stripped.indexOf('/');
+ if (slash < 0) {
+ return "arn:aws:s3:::" + stripped;
+ }
+ return "arn:aws:s3:::" + stripped;
+ }
+
+ // ── Lambda ──────────────────────────────────────────────────────────────────
+ private String buildLambdaArn(String path, String region, String accountId) {
+ // path: /2015-03-31/functions/name or similar
+ String name = extractSegmentAfter(path, "functions");
+ if (name == null) return "*";
+ // strip qualifier if present
+ int colon = name.indexOf(':');
+ if (colon > 0) name = name.substring(0, colon);
+ return "arn:aws:lambda:" + region + ":" + accountId + ":function:" + name;
+ }
+
+ // ── SQS ─────────────────────────────────────────────────────────────────────
+ private String buildSqsArn(ContainerRequestContext ctx, String region, String accountId) {
+ String queueUrl = ctx.getUriInfo().getQueryParameters().getFirst("QueueUrl");
+ if (queueUrl == null) {
+ // Try form param for Query-protocol
+ queueUrl = firstFormParam(ctx, "QueueUrl");
+ }
+ if (queueUrl != null) {
+ String queueName = queueUrl.substring(queueUrl.lastIndexOf('/') + 1);
+ return "arn:aws:sqs:" + region + ":" + accountId + ":" + queueName;
+ }
+ return "arn:aws:sqs:" + region + ":" + accountId + ":*";
+ }
+
+ // ── SNS ─────────────────────────────────────────────────────────────────────
+ private String buildSnsArn(ContainerRequestContext ctx, String region, String accountId) {
+ String topicArn = firstFormParam(ctx, "TopicArn");
+ return topicArn != null ? topicArn : "arn:aws:sns:" + region + ":" + accountId + ":*";
+ }
+
+ // ── DynamoDB ─────────────────────────────────────────────────────────────────
+ private String buildDynamoDbArn(ContainerRequestContext ctx, String region, String accountId) {
+ // TableName comes in the JSON body; use wildcard since we don't parse the body here
+ return "arn:aws:dynamodb:" + region + ":" + accountId + ":table/*";
+ }
+
+ // ── Kinesis ──────────────────────────────────────────────────────────────────
+ private String buildKinesisArn(ContainerRequestContext ctx, String region, String accountId) {
+ return "arn:aws:kinesis:" + region + ":" + accountId + ":stream/*";
+ }
+
+ // ── Secrets Manager ──────────────────────────────────────────────────────────
+ private String buildSecretsManagerArn(ContainerRequestContext ctx, String region, String accountId) {
+ return "arn:aws:secretsmanager:" + region + ":" + accountId + ":secret:*";
+ }
+
+ // ── SSM ──────────────────────────────────────────────────────────────────────
+ private String buildSsmArn(ContainerRequestContext ctx, String region, String accountId) {
+ return "arn:aws:ssm:" + region + ":" + accountId + ":parameter/*";
+ }
+
+ // ── KMS ──────────────────────────────────────────────────────────────────────
+ private String buildKmsArn(String path, String region, String accountId) {
+ String keyId = extractSegmentAfter(path, "keys");
+ if (keyId == null) return "arn:aws:kms:" + region + ":" + accountId + ":key/*";
+ return "arn:aws:kms:" + region + ":" + accountId + ":key/" + keyId;
+ }
+
+ // ── Helpers ──────────────────────────────────────────────────────────────────
+
+ private String extractSegmentAfter(String path, String segment) {
+ String marker = "/" + segment + "/";
+ int idx = path.indexOf(marker);
+ if (idx < 0) return null;
+ String after = path.substring(idx + marker.length());
+ // take only the first segment (stop at next /)
+ int slash = after.indexOf('/');
+ return slash > 0 ? after.substring(0, slash) : after;
+ }
+
+ private String firstFormParam(ContainerRequestContext ctx, String name) {
+ // Form params are typically available as query params in REST-Assured / JAX-RS
+ String v = ctx.getUriInfo().getQueryParameters().getFirst(name);
+ return v;
+ }
+}
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 3e5ff58580..ffb33eca69 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
@@ -69,6 +69,10 @@ public class StsQueryHandler {
String assumedRoleArn = "arn:aws:sts::" + accountId + ":assumed-role/" + roleName + "/" + sessionName;
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
+ // Register session so IAM enforcement can resolve the role's policies
+ String sessionPolicy = getParam(params, "Policy");
+ iamService.registerSession(accessKeyId, roleArn, expiration, sessionPolicy);
+
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
.start("AssumedRoleUser")
@@ -122,6 +126,9 @@ public class StsQueryHandler {
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
String provider = providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com";
+ String sessionPolicy = getParam(params, "Policy");
+ iamService.registerSession(accessKeyId, roleArn, expiration, sessionPolicy);
+
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
.start("AssumedRoleUser")
@@ -155,6 +162,8 @@ public class StsQueryHandler {
String assumedRoleArn = "arn:aws:sts::" + accountId + ":assumed-role/" + roleName + "/" + sessionName;
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
+ iamService.registerSession(accessKeyId, roleArn, expiration, null);
+
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
.start("AssumedRoleUser")
@@ -187,6 +196,10 @@ public class StsQueryHandler {
String federatedUserId = accountId + ":" + name;
String federatedUserArn = "arn:aws:sts::" + accountId + ":federated-user/" + name;
+ String sessionPolicy = getParam(params, "Policy");
+ // Register federation token so enforcement can scope its policies via session policy
+ iamService.registerSession(accessKeyId, federatedUserArn, expiration, sessionPolicy);
+
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
.start("FederatedUser")
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java
new file mode 100644
index 0000000000..fd839ce89f
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.services.iam.model;
+
+import java.util.List;
+
+/**
+ * Full IAM context for the calling identity, used by the enforcement filter.
+ *
+ * <p>Carries all inputs required for the complete AWS policy evaluation algorithm:
+ * <ul>
+ * <li>{@code identityPolicies} — inline + attached policies of the user, role, and groups</li>
+ * <li>{@code sessionPolicyDocument} — optional inline session policy from AssumeRole (Phase 3)</li>
+ * <li>{@code boundaryPolicyDocument} — optional permissions boundary document (Phase 3)</li>
+ * </ul>
+ */
+public record CallerContext(
+ List<String> identityPolicies,
+ String sessionPolicyDocument,
+ String boundaryPolicyDocument
+) {
+ /** Convenience factory: no session policy, no boundary. */
+ public static CallerContext of(List<String> identityPolicies) {
+ return new CallerContext(identityPolicies, null, null);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java
index 259eb61afa..1c445a808e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java
@@ -24,6 +24,7 @@ public class IamRole {
private Map<String, String> tags = new HashMap<>();
private List<String> attachedPolicyArns = new ArrayList<>();
private Map<String, String> inlinePolicies = new HashMap<>();
+ private String permissionsBoundaryArn;
public IamRole() {}
@@ -69,4 +70,7 @@ public class IamRole {
public Map<String, String> getInlinePolicies() { return inlinePolicies; }
public void setInlinePolicies(Map<String, String> inlinePolicies) { this.inlinePolicies = inlinePolicies; }
+
+ public String getPermissionsBoundaryArn() { return permissionsBoundaryArn; }
+ public void setPermissionsBoundaryArn(String permissionsBoundaryArn) { this.permissionsBoundaryArn = permissionsBoundaryArn; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/IamUser.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/IamUser.java
index 439d937b21..07705952a0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/IamUser.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/IamUser.java
@@ -23,6 +23,7 @@ public class IamUser {
private List<String> groupNames = new ArrayList<>();
private List<String> attachedPolicyArns = new ArrayList<>();
private Map<String, String> inlinePolicies = new HashMap<>();
+ private String permissionsBoundaryArn;
public IamUser() {}
@@ -63,4 +64,7 @@ public class IamUser {
public Map<String, String> getInlinePolicies() { return inlinePolicies; }
public void setInlinePolicies(Map<String, String> inlinePolicies) { this.inlinePolicies = inlinePolicies; }
+
+ public String getPermissionsBoundaryArn() { return permissionsBoundaryArn; }
+ public void setPermissionsBoundaryArn(String permissionsBoundaryArn) { this.permissionsBoundaryArn = permissionsBoundaryArn; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyStatement.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyStatement.java
new file mode 100644
index 0000000000..cc3040ab1f
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyStatement.java
@@ -0,0 +1,49 @@
+package io.github.hectorvent.floci.services.iam.model;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A single parsed statement from an IAM policy document.
+ *
+ * <p>Supports Phase 1 (actions, resources), Phase 4 (NotAction, NotResource, Condition).
+ */
+public class PolicyStatement {
+
+ private final String effect; // "Allow" or "Deny"
+ private final List<String> actions; // IAM action patterns; null when notActions is set
+ private final List<String> notActions; // NotAction patterns; null when actions is set
+ private final List<String> resources; // resource ARN patterns; null when notResources is set
+ private final List<String> notResources;// NotResource patterns; null when resources is set
+ // Condition: outer key = operator (e.g. "StringEquals"), inner key = context key, value = list of values
+ private final Map<String, Map<String, List<String>>> conditions;
+
+ public PolicyStatement(String effect,
+ List<String> actions,
+ List<String> notActions,
+ List<String> resources,
+ List<String> notResources,
+ Map<String, Map<String, List<String>>> conditions) {
+ this.effect = effect;
+ this.actions = actions;
+ this.notActions = notActions;
+ this.resources = resources;
+ this.notResources = notResources;
+ this.conditions = conditions;
+ }
+
+ /** Convenience constructor for simple allow/deny without conditions or Not* fields. */
+ public PolicyStatement(String effect, List<String> actions, List<String> resources) {
+ this(effect, actions, null, resources, null, null);
+ }
+
+ public String getEffect() { return effect; }
+ public List<String> getActions() { return actions; }
+ public List<String> getNotActions() { return notActions; }
+ public List<String> getResources() { return resources; }
+ public List<String> getNotResources() { return notResources; }
+ public Map<String, Map<String, List<String>>> getConditions() { return conditions; }
+
+ public boolean isDeny() { return "Deny".equalsIgnoreCase(effect); }
+ public boolean isAllow() { return "Allow".equalsIgnoreCase(effect); }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java
new file mode 100644
index 0000000000..8952644f0b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java
@@ -0,0 +1,44 @@
+package io.github.hectorvent.floci.services.iam.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class SessionCredential {
+
+ private String accessKeyId;
+ private String roleArn;
+ private Instant expiration;
+ /** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */
+ private String sessionPolicyDocument;
+
+ public SessionCredential() {}
+
+ public SessionCredential(String accessKeyId, String roleArn, Instant expiration) {
+ this.accessKeyId = accessKeyId;
+ this.roleArn = roleArn;
+ this.expiration = expiration;
+ }
+
+ public SessionCredential(String accessKeyId, String roleArn, Instant expiration, String sessionPolicyDocument) {
+ this.accessKeyId = accessKeyId;
+ this.roleArn = roleArn;
+ this.expiration = expiration;
+ this.sessionPolicyDocument = sessionPolicyDocument;
+ }
+
+ public String getAccessKeyId() { return accessKeyId; }
+ public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; }
+
+ public String getRoleArn() { return roleArn; }
+ public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
+
+ public Instant getExpiration() { return expiration; }
+ public void setExpiration(Instant expiration) { this.expiration = expiration; }
+
+ public String getSessionPolicyDocument() { return sessionPolicyDocument; }
+ public void setSessionPolicyDocument(String sessionPolicyDocument) { this.sessionPolicyDocument = sessionPolicyDocument; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 4948a42e59..39d6dbf94e 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -85,6 +85,7 @@ floci:
enabled: true
iam:
enabled: true
+ enforcement-enabled: false
elasticache:
enabled: true
proxy-base-port: 6379
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
new file mode 100644
index 0000000000..6650a23f93
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java
@@ -0,0 +1,159 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
+import org.junit.jupiter.api.Test;
+
+import jakarta.inject.Inject;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit-style tests for the IAM enforcement engine components:
+ * {@link IamPolicyEvaluator}, {@link IamActionRegistry}, and glob matching.
+ *
+ * The full HTTP enforcement path (filter → evaluator) is covered by the SDK
+ * compatibility test {@code IamEnforcementTest.java} in sdk-test-java.
+ */
+@QuarkusTest
+class IamEnforcementIntegrationTest {
+
+ @Inject
+ IamPolicyEvaluator evaluator;
+
+ // =========================================================================
+ // IamPolicyEvaluator — basic allow / deny / implicit-deny
+ // =========================================================================
+
+ @Test
+ void allowMatchingAction() {
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}
+ ]}""";
+ assertEquals(Decision.ALLOW,
+ evaluator.evaluate(List.of(policy), "s3:GetObject", "arn:aws:s3:::my-bucket/key"));
+ }
+
+ @Test
+ void implicitDenyWhenNoPolicies() {
+ assertEquals(Decision.DENY,
+ evaluator.evaluate(List.of(), "s3:GetObject", "arn:aws:s3:::my-bucket/key"));
+ }
+
+ @Test
+ void implicitDenyWhenNoMatchingStatement() {
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
+ ]}""";
+ assertEquals(Decision.DENY,
+ evaluator.evaluate(List.of(policy), "s3:GetObject", "arn:aws:s3:::my-bucket/key"));
+ }
+
+ @Test
+ void explicitDenyOverridesAllow() {
+ String allow = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:*","Resource":"*"}
+ ]}""";
+ String deny = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Deny","Action":"s3:GetObject","Resource":"*"}
+ ]}""";
+ assertEquals(Decision.DENY,
+ evaluator.evaluate(List.of(allow, deny), "s3:GetObject", "arn:aws:s3:::bucket/key"));
+ }
+
+ @Test
+ void wildcardActionMatchesService() {
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:*","Resource":"*"}
+ ]}""";
+ assertEquals(Decision.ALLOW,
+ evaluator.evaluate(List.of(policy), "s3:DeleteObject", "arn:aws:s3:::bucket/key"));
+ }
+
+ @Test
+ void fullyWildcardPolicyAllowsAnything() {
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"*","Resource":"*"}
+ ]}""";
+ assertEquals(Decision.ALLOW,
+ evaluator.evaluate(List.of(policy), "lambda:InvokeFunction",
+ "arn:aws:lambda:us-east-1:000000000000:function:my-fn"));
+ }
+
+ @Test
+ void resourceArnPatternMatchesBucket() {
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::my-bucket/*"}
+ ]}""";
+ assertEquals(Decision.ALLOW,
+ evaluator.evaluate(List.of(policy), "s3:GetObject", "arn:aws:s3:::my-bucket/sub/key.txt"));
+ assertEquals(Decision.DENY,
+ evaluator.evaluate(List.of(policy), "s3:GetObject", "arn:aws:s3:::other-bucket/key"));
+ }
+
+ @Test
+ void actionListInStatement() {
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":"*"}
+ ]}""";
+ assertEquals(Decision.ALLOW, evaluator.evaluate(List.of(policy), "s3:GetObject", "*"));
+ assertEquals(Decision.ALLOW, evaluator.evaluate(List.of(policy), "s3:PutObject", "*"));
+ assertEquals(Decision.DENY, evaluator.evaluate(List.of(policy), "s3:DeleteObject", "*"));
+ }
+
+ @Test
+ void malformedPolicyDocumentIsSkipped() {
+ // Should not throw; malformed doc is silently ignored
+ assertEquals(Decision.DENY,
+ evaluator.evaluate(List.of("not-json"), "s3:GetObject", "*"));
+ }
+
+ // =========================================================================
+ // IamPolicyEvaluator.globMatches — unit tests
+ // =========================================================================
+
+ @Test
+ void globMatchesStar() {
+ assertTrue(IamPolicyEvaluator.globMatches("s3:*", "s3:GetObject"));
+ assertTrue(IamPolicyEvaluator.globMatches("*", "anything"));
+ assertFalse(IamPolicyEvaluator.globMatches("s3:*", "lambda:InvokeFunction"));
+ }
+
+ @Test
+ void globMatchesLiteral() {
+ assertTrue(IamPolicyEvaluator.globMatches("s3:GetObject", "s3:GetObject"));
+ assertFalse(IamPolicyEvaluator.globMatches("s3:GetObject", "s3:PutObject"));
+ }
+
+ @Test
+ void globMatchesQuestionMark() {
+ assertTrue(IamPolicyEvaluator.globMatches("s3:GetObjec?", "s3:GetObject"));
+ assertFalse(IamPolicyEvaluator.globMatches("s3:GetObjec?", "s3:GetObjects"));
+ }
+
+ @Test
+ void globMatchesCaseInsensitive() {
+ assertTrue(IamPolicyEvaluator.globMatches("S3:GetObject", "s3:getobject"));
+ }
+
+ @Test
+ void globMatchesArnWildcard() {
+ assertTrue(IamPolicyEvaluator.globMatches(
+ "arn:aws:s3:::my-bucket/*",
+ "arn:aws:s3:::my-bucket/sub/dir/file.txt"));
+ assertFalse(IamPolicyEvaluator.globMatches(
+ "arn:aws:s3:::my-bucket/*",
+ "arn:aws:s3:::other-bucket/file.txt"));
+ }
+}
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 f34f9d20d9..e98363f85c 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
@@ -30,6 +30,7 @@ class IamServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
"000000000000"
);
}
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java
index edf845b39d..fcbdf912bf 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java
@@ -22,6 +22,7 @@ public final class IamServiceTestHelper {
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
+ StorageBackend.class,
String.class
);
constructor.setAccessible(true);
@@ -36,6 +37,7 @@ public final class IamServiceTestHelper {
null,
accessKeys,
null,
+ null,
"123456789012"
);
} catch (ReflectiveOperationException e) {
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 5c7de8dade..23b36302a8 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -66,6 +66,7 @@ floci:
enabled: true
iam:
enabled: true
+ enforcement-enabled: false
elasticache:
enabled: true
proxy-base-port: 6379