Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(iam): route assumed-role credentials to the target account (#1549)

Alex Bannaf52b9209cf74
diff --git a/README.md b/README.md
index aa5daa6c2d..3eaa4938ce 100644
--- a/README.md
+++ b/README.md
@@ -380,6 +380,8 @@ AWS_ACCESS_KEY_ID=222222222222 aws sqs create-queue --queue-name orders
Any other key format, such as `test` or `AKIA...`, causes Floci to fall back to `FLOCI_DEFAULT_ACCOUNT_ID`, which defaults to `000000000000`.
+STS temporary credentials are routed too: credentials from `AssumeRole` resolve to the assumed role's account, so the cross-account assume-role-then-provision pattern works locally. Resolution precedence is 12-digit AKID → temporary-session lookup → `FLOCI_DEFAULT_ACCOUNT_ID`.
+
See the [Multi-Account Isolation docs](https://floci.io/floci/configuration/multi-account/).
## SDK Integration
diff --git a/docs/configuration/multi-account.md b/docs/configuration/multi-account.md
index ebd23817ec..135f676f31 100644
--- a/docs/configuration/multi-account.md
+++ b/docs/configuration/multi-account.md
@@ -20,6 +20,21 @@ Once the account ID is determined, every storage read and write is transparently
!!! note "Same convention as LocalStack"
This 12-digit AKID → account ID rule matches LocalStack's multi-account behavior, so existing multi-account test setups work without changes.
+## Temporary Credentials (AssumeRole)
+
+STS temporary credentials are also routed to the correct account. When you call `AssumeRole` (or `AssumeRoleWithWebIdentity`, `AssumeRoleWithSAML`, `GetFederationToken`), Floci issues a temporary `ASIA…` access key and remembers which account it belongs to:
+
+- **`AssumeRole` / web-identity / SAML / federation** → the account in the role (or federated-user) ARN. Assuming `arn:aws:iam::222222222222:role/Deployer` from account `111111111111` yields credentials that resolve to **`222222222222`**, so resources created with them land in account B's namespace.
+- **`GetSessionToken`** → the caller's account (these credentials carry no role), so they stay in the same account.
+
+```
+Account 111111111111 ──AssumeRole arn:aws:iam::222222222222:role/Deployer──▶ ASIA… temp key
+ │
+ASIA… temp key ──CreateTable orders──▶ stored as 222222222222/...::orders ◀──┘
+```
+
+This makes the cross-account `AssumeRole`-then-provision pattern (e.g. CloudFormation deploying into a target account) work locally exactly as it does in AWS. Resolution precedence is: **12-digit AKID → temporary-session lookup → `FLOCI_DEFAULT_ACCOUNT_ID`.**
+
## Default Behavior (Single Account)
If you use any non-12-digit credentials (e.g. `test`, `AKIA…`), all requests resolve to the default account ID:
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
index 3e74164eea..3010d66ddf 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
@@ -8,11 +8,18 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.ext.Provider;
+import java.util.Optional;
+
/**
* Populates {@link RequestContext} with the account ID and region derived from
* the incoming AWS Authorization header or, for presigned URL requests, the
* X-Amz-Credential query parameter. Runs at AUTHENTICATION priority so that
* downstream filters (e.g. IAM enforcement) can rely on the context being set.
+ *
+ * <p>Account resolution precedence: a 12-digit access key ID is used directly as
+ * the account; otherwise temporary credentials (e.g. assumed-role {@code ASIA...}
+ * keys) are looked up in the session store via {@link SessionAccountLookup}; if
+ * neither matches, the configured default account applies.
*/
@Provider
@ApplicationScoped
@@ -22,26 +29,32 @@ public class AccountContextFilter implements ContainerRequestFilter {
private final AccountResolver accountResolver;
private final RegionResolver regionResolver;
private final RequestContext requestContext;
+ private final SessionAccountLookup sessionAccountLookup;
@Inject
public AccountContextFilter(AccountResolver accountResolver,
RegionResolver regionResolver,
- RequestContext requestContext) {
+ RequestContext requestContext,
+ SessionAccountLookup sessionAccountLookup) {
this.accountResolver = accountResolver;
this.regionResolver = regionResolver;
this.requestContext = requestContext;
+ this.sessionAccountLookup = sessionAccountLookup;
}
@Override
public void filter(ContainerRequestContext ctx) {
String auth = ctx.getHeaderString("Authorization");
if (auth != null && !auth.isEmpty()) {
- requestContext.setAccountId(accountResolver.resolve(auth));
+ String akid = accountResolver.extractAccessKeyId(auth);
+ requestContext.setAccountId(resolveAccount(akid, accountResolver.resolve(auth)));
requestContext.setRegion(regionResolver.resolveRegionFromAuth(auth));
} else {
String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
if (credential != null && !credential.isEmpty()) {
- requestContext.setAccountId(accountResolver.resolveFromPresignedCredential(credential));
+ String akid = accountResolver.extractPresignedAccessKeyId(credential);
+ requestContext.setAccountId(
+ resolveAccount(akid, accountResolver.resolveFromPresignedCredential(credential)));
requestContext.setRegion(regionResolver.resolveRegionFromPresignedCredential(credential));
} else {
requestContext.setAccountId(accountResolver.resolve(null));
@@ -49,4 +62,19 @@ public class AccountContextFilter implements ContainerRequestFilter {
}
}
}
+
+ /**
+ * Applies the account-resolution precedence. A 12-digit AKID is already reflected in
+ * {@code resolvedDefault} (the account or default returned by {@link AccountResolver});
+ * for any other key shape, a live session lookup takes precedence before falling back.
+ */
+ private String resolveAccount(String akid, String resolvedDefault) {
+ if (akid != null && !akid.matches("\\d{12}")) {
+ Optional<String> sessionAccount = sessionAccountLookup.resolveAccountId(akid);
+ if (sessionAccount.isPresent()) {
+ return sessionAccount.get();
+ }
+ }
+ return resolvedDefault;
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountResolver.java
index c80777f7af..31fce38b17 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AccountResolver.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountResolver.java
@@ -62,11 +62,22 @@ public class AccountResolver {
if (credentialValue == null || credentialValue.isEmpty()) {
return defaultAccountId;
}
- String[] parts = credentialValue.split("/");
- String akid = parts[0];
- if (akid.matches("\\d{12}")) {
+ String akid = extractPresignedAccessKeyId(credentialValue);
+ if (akid != null && akid.matches("\\d{12}")) {
return akid;
}
return defaultAccountId;
}
+
+ /**
+ * Extracts the access key ID from an X-Amz-Credential value
+ * ({@code accessKeyID/date/region/service/aws4_request}), or returns null when
+ * the value is absent or empty.
+ */
+ public String extractPresignedAccessKeyId(String credentialValue) {
+ if (credentialValue == null || credentialValue.isEmpty()) {
+ return null;
+ }
+ return credentialValue.split("/", 2)[0];
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SessionAccountLookup.java b/src/main/java/io/github/hectorvent/floci/core/common/SessionAccountLookup.java
new file mode 100644
index 0000000000..47ce083747
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/SessionAccountLookup.java
@@ -0,0 +1,21 @@
+package io.github.hectorvent.floci.core.common;
+
+import java.util.Optional;
+
+/**
+ * Port that maps an STS temporary access key ID (e.g. {@code ASIA...}) to the AWS
+ * account the request should resolve to.
+ *
+ * <p>Declared in {@code core.common} so {@link AccountContextFilter} can route
+ * assumed-role and other temporary credentials to the correct account without
+ * {@code core} depending on the {@code services.iam} package (which owns the
+ * session store) — keeping the dependency direction services → core.
+ */
+public interface SessionAccountLookup {
+
+ /**
+ * Returns the account ID associated with the given temporary access key ID,
+ * or {@link Optional#empty()} if it is not a known, live session.
+ */
+ Optional<String> resolveAccountId(String accessKeyId);
+}
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 a412b46652..4ee2335df1 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
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.SessionAccountLookup;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
@@ -16,6 +18,7 @@ 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 io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -32,9 +35,16 @@ import java.util.Map;
/**
* Core IAM business logic — users, groups, roles, policies, access keys, instance profiles.
* IAM is a global service: resources are not region-scoped and storage keys have no region prefix.
+ *
+ * <p>Eagerly initialized at startup so AWS-managed policies (and the optional deployer principal)
+ * are seeded under the default account before any request runs. Seeding is account-namespaced via
+ * the request context, so deferring it to the first request would otherwise bind the seed data to
+ * whichever account happened to make that call — a real hazard now that {@code AccountContextFilter}
+ * resolves the request account through this service.
*/
+@Startup
@ApplicationScoped
-public class IamService {
+public class IamService implements SessionAccountLookup {
private static final Logger LOG = Logger.getLogger(IamService.class);
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@@ -945,6 +955,59 @@ public class IamService {
new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration, sessionPolicyDocument));
}
+ /**
+ * Stores an assumed-role session and records {@code originAccountId} — the account of the
+ * caller that minted it. The origin lets {@link #resolveAccountId(String)} route temporary
+ * credentials that carry no role ARN (e.g. GetSessionToken) back to the caller's account.
+ */
+ public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,
+ java.time.Instant expiration, String sessionPolicyDocument,
+ String originAccountId) {
+ sessions.put(sessionAccessKeyId,
+ new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration,
+ sessionPolicyDocument, originAccountId));
+ }
+
+ /**
+ * Resolves the account a temporary access key belongs to: the account encoded in the
+ * session's role (or federated-user) ARN when present, otherwise the caller account captured
+ * at mint time. Returns empty for unknown or expired sessions so callers fall back to the
+ * default account.
+ */
+ @Override
+ public Optional<String> resolveAccountId(String accessKeyId) {
+ // STS issues only ASIA-prefixed temporary keys, so anything else cannot be a session.
+ // Short-circuit here to keep the per-request hot path off the session-store scan below.
+ if (accessKeyId == null || !accessKeyId.startsWith("ASIA")) {
+ return Optional.empty();
+ }
+ Optional<SessionCredential> sessionOpt = findSessionAnyAccount(accessKeyId);
+ if (sessionOpt.isEmpty()) {
+ return Optional.empty();
+ }
+ SessionCredential session = sessionOpt.get();
+ if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
+ return Optional.empty();
+ }
+ String account = AwsArnUtils.accountOrDefault(session.getRoleArn(), session.getOriginAccountId());
+ return account == null || account.isBlank() ? Optional.empty() : Optional.of(account);
+ }
+
+ /**
+ * Looks up a session by its temporary access key ID independent of the request's account.
+ *
+ * <p>Sessions are keyed by a globally-unique access key (e.g. {@code ASIA...}) but stored in
+ * the minting account's namespace. Account routing must resolve the session <em>before</em> the
+ * request's account is known, so a normal account-scoped {@code get} would miss it. This scans
+ * across all accounts; the access key's global uniqueness keeps the result unambiguous.
+ */
+ private Optional<SessionCredential> findSessionAnyAccount(String accessKeyId) {
+ if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
+ return Optional.ofNullable(aware.scanAllAccountsAsMap().get(accessKeyId));
+ }
+ return sessions.get(accessKeyId);
+ }
+
/**
* Resolves the full caller context for the given access key, including identity policies,
* optional session policy, and optional permission boundary.
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 e8fae85dbf..c6997647a7 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
@@ -77,14 +77,16 @@ public class StsQueryHandler {
String roleName = roleArn != null && roleArn.contains("/")
? roleArn.substring(roleArn.lastIndexOf('/') + 1)
: "UnknownRole";
- String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
+ String callerAccountId = regionResolver.getAccountId();
+ String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
- // Register session so IAM enforcement can resolve the role's policies and so that
- // RDS/ElastiCache IAM token validation can find the temporary secret key.
+ // Register session so IAM enforcement can resolve the role's policies, RDS/ElastiCache
+ // IAM token validation can find the temporary secret key, and account routing can map
+ // these temporary credentials to the assumed role's account.
String sessionPolicy = getParam(params, "Policy");
- iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy);
+ iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -119,7 +121,8 @@ public class StsQueryHandler {
Instant expiration = Instant.now().plusSeconds(durationSeconds);
String result = credentialsXml(accessKeyId, secretKey, sessionToken, expiration);
- iamService.registerSession(accessKeyId, secretKey, null, expiration, null);
+ // No role ARN — route these credentials back to the caller's account.
+ iamService.registerSession(accessKeyId, secretKey, null, expiration, null, regionResolver.getAccountId());
return Response.ok(AwsQueryResponse.envelope("GetSessionToken", AwsNamespaces.STS, result)).build();
}
@@ -139,13 +142,14 @@ public class StsQueryHandler {
Instant expiration = Instant.now().plusSeconds(durationSeconds);
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
- String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
+ String callerAccountId = regionResolver.getAccountId();
+ String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
String provider = providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com";
String sessionPolicy = getParam(params, "Policy");
- iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy);
+ iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -176,11 +180,12 @@ public class StsQueryHandler {
Instant expiration = Instant.now().plusSeconds(durationSeconds);
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
- String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
+ String callerAccountId = regionResolver.getAccountId();
+ String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
- iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, null);
+ iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, null, callerAccountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -215,8 +220,9 @@ public class StsQueryHandler {
String federatedUserArn = AwsArnUtils.Arn.of("sts", "", accountId, "federated-user/" + name).toString();
String sessionPolicy = getParam(params, "Policy");
- // Register federation token so enforcement can scope its policies via session policy
- iamService.registerSession(accessKeyId, secretKey, federatedUserArn, expiration, sessionPolicy);
+ // Register federation token so enforcement can scope its policies via session policy.
+ // The federated-user ARN already carries the caller's account, so reuse it as the origin.
+ iamService.registerSession(accessKeyId, secretKey, federatedUserArn, expiration, sessionPolicy, accountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
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
index 9e2c0d4db9..5513f51457 100644
--- 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
@@ -15,6 +15,11 @@ public class SessionCredential {
private Instant expiration;
/** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */
private String sessionPolicyDocument;
+ /**
+ * Account of the caller that minted this session, captured at mint time. Used to route
+ * temporary credentials that carry no role ARN (e.g. GetSessionToken) back to the caller.
+ */
+ private String originAccountId;
public SessionCredential() {}
@@ -40,6 +45,16 @@ public class SessionCredential {
this.sessionPolicyDocument = sessionPolicyDocument;
}
+ public SessionCredential(String accessKeyId, String secretAccessKey, String roleArn, Instant expiration,
+ String sessionPolicyDocument, String originAccountId) {
+ this.accessKeyId = accessKeyId;
+ this.secretAccessKey = secretAccessKey;
+ this.roleArn = roleArn;
+ this.expiration = expiration;
+ this.sessionPolicyDocument = sessionPolicyDocument;
+ this.originAccountId = originAccountId;
+ }
+
public String getAccessKeyId() { return accessKeyId; }
public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; }
@@ -54,4 +69,7 @@ public class SessionCredential {
public String getSessionPolicyDocument() { return sessionPolicyDocument; }
public void setSessionPolicyDocument(String sessionPolicyDocument) { this.sessionPolicyDocument = sessionPolicyDocument; }
+
+ public String getOriginAccountId() { return originAccountId; }
+ public void setOriginAccountId(String originAccountId) { this.originAccountId = originAccountId; }
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java
index b973a21099..428912542f 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java
@@ -7,6 +7,9 @@ import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import java.util.Map;
+import java.util.Optional;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -19,6 +22,7 @@ class AccountContextFilterTest {
private AccountResolver accountResolver;
private RegionResolver regionResolver;
private RequestContext requestContext;
+ private Map<String, String> sessionAccounts;
private AccountContextFilter filter;
@BeforeEach
@@ -26,7 +30,9 @@ class AccountContextFilterTest {
accountResolver = new AccountResolver(DEFAULT_ACCOUNT);
regionResolver = new RegionResolver(DEFAULT_REGION, DEFAULT_ACCOUNT);
requestContext = new RequestContext();
- filter = new AccountContextFilter(accountResolver, regionResolver, requestContext);
+ sessionAccounts = new java.util.HashMap<>();
+ SessionAccountLookup sessionLookup = akid -> Optional.ofNullable(sessionAccounts.get(akid));
+ filter = new AccountContextFilter(accountResolver, regionResolver, requestContext, sessionLookup);
}
@Test
@@ -85,6 +91,52 @@ class AccountContextFilterTest {
assertEquals(DEFAULT_REGION, requestContext.getRegion());
}
+ @Test
+ void resolvesAssumedRoleSessionKeyToSessionAccount() {
+ sessionAccounts.put("ASIAEXAMPLESESSIONKEY", "222233334444");
+ ContainerRequestContext ctx = mockContext(
+ "AWS4-HMAC-SHA256 Credential=ASIAEXAMPLESESSIONKEY/20260617/us-west-2/dynamodb/aws4_request, "
+ + "SignedHeaders=host, Signature=abc",
+ null
+ );
+ filter.filter(ctx);
+ assertEquals("222233334444", requestContext.getAccountId());
+ assertEquals("us-west-2", requestContext.getRegion());
+ }
+
+ @Test
+ void twelveDigitAkidWinsOverSessionLookup() {
+ sessionAccounts.put("000000000001", "999999999999");
+ ContainerRequestContext ctx = mockContext(
+ "AWS4-HMAC-SHA256 Credential=000000000001/20260617/us-west-2/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=abc",
+ null
+ );
+ filter.filter(ctx);
+ assertEquals("000000000001", requestContext.getAccountId());
+ }
+
+ @Test
+ void unknownSessionKeyFallsBackToDefault() {
+ ContainerRequestContext ctx = mockContext(
+ "AWS4-HMAC-SHA256 Credential=ASIAUNKNOWNKEY/20260617/us-west-2/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=abc",
+ null
+ );
+ filter.filter(ctx);
+ assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
+ }
+
+ @Test
+ void resolvesSessionKeyFromPresignedCredential() {
+ sessionAccounts.put("ASIAPRESIGNEDKEY", "555566667777");
+ ContainerRequestContext ctx = mockContext(null,
+ "ASIAPRESIGNEDKEY/20260617/eu-west-1/s3/aws4_request");
+ filter.filter(ctx);
+ assertEquals("555566667777", requestContext.getAccountId());
+ assertEquals("eu-west-1", requestContext.getRegion());
+ }
+
private ContainerRequestContext mockContext(String authHeader, String xAmzCredential) {
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
when(ctx.getHeaderString("Authorization")).thenReturn(authHeader);
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AccountResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AccountResolverTest.java
index e4b21d50f0..2b0f8384c7 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/AccountResolverTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AccountResolverTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
class AccountResolverTest {
@@ -56,4 +57,18 @@ class AccountResolverTest {
void fallsBackToDefaultWhenPresignedCredentialEmpty() {
assertEquals(DEFAULT_ACCOUNT, resolver.resolveFromPresignedCredential(""));
}
+
+ // --- extractPresignedAccessKeyId(String credentialValue) tests ---
+
+ @Test
+ void extractsAccessKeyIdFromPresignedCredential() {
+ assertEquals("ASIAEXAMPLE",
+ resolver.extractPresignedAccessKeyId("ASIAEXAMPLE/20260617/us-east-1/s3/aws4_request"));
+ }
+
+ @Test
+ void extractPresignedAccessKeyIdReturnsNullWhenAbsent() {
+ assertNull(resolver.extractPresignedAccessKeyId(null));
+ assertNull(resolver.extractPresignedAccessKeyId(""));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AssumedRoleAccountRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AssumedRoleAccountRoutingIntegrationTest.java
new file mode 100644
index 0000000000..5f3204a6cc
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AssumedRoleAccountRoutingIntegrationTest.java
@@ -0,0 +1,108 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.startsWith;
+
+/**
+ * End-to-end proof that assumed-role temporary credentials are routed to the role's account.
+ *
+ * <p>Scenario: account A ({@code 111122223333}) assumes a role in account B
+ * ({@code 222233334444}); the returned temporary credentials are then used to create a DynamoDB
+ * table. The table must materialize in account B's namespace — visible to B, invisible to A —
+ * rather than collapsing to the default account.
+ */
+@QuarkusTest
+class AssumedRoleAccountRoutingIntegrationTest {
+
+ private static final String ACCOUNT_A = "111122223333";
+ private static final String ACCOUNT_B = "222233334444";
+ private static final String REGION = "us-east-1";
+ private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void assumedRoleCredentialsRouteResourcesToTargetAccount() {
+ String tableName = "routing-" + UUID.randomUUID().toString().substring(0, 8);
+
+ // 1. Account A assumes a role in account B and receives temporary credentials.
+ String tempAccessKeyId = given()
+ .formParam("Action", "AssumeRole")
+ .formParam("RoleArn", "arn:aws:iam::" + ACCOUNT_B + ":role/CrossAccountAccess")
+ .formParam("RoleSessionName", "routing-session")
+ .header("Authorization", auth(ACCOUNT_A, "sts"))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA"))
+ .extract()
+ .path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
+
+ // 2. GetCallerIdentity with the temporary credentials resolves to account B.
+ given()
+ .formParam("Action", "GetCallerIdentity")
+ .header("Authorization", auth(tempAccessKeyId, "sts"))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(ACCOUNT_B));
+
+ // 3. Create a DynamoDB table using the temporary credentials. Its ARN must carry account B.
+ given()
+ .header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
+ .header("Authorization", auth(tempAccessKeyId, "dynamodb"))
+ .contentType(DYNAMODB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "BillingMode": "PAY_PER_REQUEST"
+ }
+ """.formatted(tableName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("TableDescription.TableArn",
+ equalTo("arn:aws:dynamodb:" + REGION + ":" + ACCOUNT_B + ":table/" + tableName));
+
+ // 4. Account B sees the table.
+ listTables(ACCOUNT_B).body("TableNames", hasItem(tableName));
+
+ // 5. Account A does not — the resource is isolated to account B.
+ listTables(ACCOUNT_A).body("TableNames", not(hasItem(tableName)));
+ }
+
+ private static io.restassured.response.ValidatableResponse listTables(String account) {
+ return given()
+ .header("X-Amz-Target", "DynamoDB_20120810.ListTables")
+ .header("Authorization", auth(account, "dynamodb"))
+ .contentType(DYNAMODB_CONTENT_TYPE)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static String auth(String accessKeyId, String service) {
+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260215/" + REGION + "/" + service
+ + "/aws4_request, SignedHeaders=host, Signature=abc";
+ }
+}
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 0d2ceb21e9..d18181e2c7 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
@@ -415,6 +415,58 @@ class IamServiceTest {
assertNull(iamService.resolveCallerPolicies("ASIAIOSFODNN7EXAMPLE"));
}
+ // =========================================================================
+ // Session account routing (SessionAccountLookup)
+ // =========================================================================
+
+ @Test
+ void resolveAccountIdUsesRoleArnAccount() {
+ iamService.registerSession(
+ "ASIACROSSACCOUNT",
+ "temp-secret",
+ "arn:aws:iam::222233334444:role/CrossAccountAccess",
+ Instant.now().plusSeconds(3600),
+ null,
+ "111122223333"
+ );
+
+ assertEquals("222233334444", iamService.resolveAccountId("ASIACROSSACCOUNT").orElseThrow());
+ }
+
+ @Test
+ void resolveAccountIdFallsBackToOriginAccountWhenNoRoleArn() {
+ iamService.registerSession(
+ "ASIASESSIONTOKEN",
+ "temp-secret",
+ null,
+ Instant.now().plusSeconds(3600),
+ null,
+ "111122223333"
+ );
+
+ assertEquals("111122223333", iamService.resolveAccountId("ASIASESSIONTOKEN").orElseThrow());
+ }
+
+ @Test
+ void resolveAccountIdEmptyForUnknownKey() {
+ assertTrue(iamService.resolveAccountId("ASIANOTREGISTERED").isEmpty());
+ assertTrue(iamService.resolveAccountId(null).isEmpty());
+ }
+
+ @Test
+ void resolveAccountIdEmptyForExpiredSession() {
+ iamService.registerSession(
+ "ASIAEXPIRED",
+ "temp-secret",
+ "arn:aws:iam::222233334444:role/CrossAccountAccess",
+ Instant.now().minusSeconds(60),
+ null,
+ "111122223333"
+ );
+
+ assertTrue(iamService.resolveAccountId("ASIAEXPIRED").isEmpty());
+ }
+
// =========================================================================
// Instance Profiles
// =========================================================================