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

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

Assumed-role temporary credentials (ASIA… keys) collapsed to the default
account: account resolution only recognised 12-digit access key IDs and had
no link to the STS session store. Cross-account "assume a role in account B,
then provision" flows therefore landed resources in account 000000000000
instead of B.

Add a SessionAccountLookup port in core.common, implemented by IamService,
mapping a temporary access key to its account — the account in the session's
role (or federated-user) ARN, or the caller account captured at mint time for
role-less GetSessionToken credentials. AccountContextFilter now resolves with
the precedence 12-digit AKID → session lookup → default, for both the
Authorization header and the presigned X-Amz-Credential parameter.

STS handlers record the caller account on every minted session, and
SessionCredential gains an originAccountId field. The session lookup is
account-independent, since sessions are keyed by a globally unique access key.

IamService is now @Startup so AWS-managed policies seed under the default
account at boot. Seeding is account-namespaced and AccountContextFilter now
instantiates IamService to resolve the request account, so lazy seeding would
otherwise bind managed policies to whichever account made the first request.

Tests: unit coverage for resolver/filter precedence and session lookup, plus
an integration test proving a table created with role-B credentials
materialises in account B and is invisible to account A.

* perf(iam): skip session-store scan for non-ASIA access keys

Account resolution runs on every request. Gating the session lookup on the
ASIA temporary-credential prefix keeps the common case (e.g. the 'test'
default credential) off the session-store scan, which would otherwise grow
with every issued session.

* chore: re-trigger CI

Unrelated flaky CodeBuildTest.batchGetBuilds_eventuallySucceeds; root-cause
fix in floci-io/floci#1577.
This commit is contained in:
Alex Banna authored and GitHub committed 2026-06-28 21:30:34 -05:00
1 parent 94468ba56f
commit f52b9209cf
12 files changed
+410 -19

No files matched your search

@@ -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);
@@ -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(""));
}
}
@@ -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";
}
}
@@ -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
// =========================================================================