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. + * + *
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 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 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 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 before 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 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
// =========================================================================