mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(sts): mint global STS and IAM ARNs per partition and add a strict partition mode (#4743)
* fix(sts): mint global STS and IAM ARNs per partition and add a strict partition mode GetCallerIdentity's root fallback, the AssumeRole family's session ARNs, the OIDC provider ARN and GetFederationToken built their ARNs with an empty region, which falls back to the commercial partition, so they carried arn:aws: whatever partition the request signed. They now go through RegionResolver.buildGlobalArn. GetAccountSummary reports GlobalEndpointTokenVersion only where the partition publishes a global STS host, which is aws alone. floci.partitions.strict (FLOCI_PARTITIONS_STRICT, default false) refuses a request signed for a service AWS publishes in another partition but not in the request's one (CloudFront in GovCloud, IAM in aws-eusc) with the unknown-service guard's 404, mirroring the host that never resolves on AWS. endpoints.json omits the services that ship only an endpoint ruleset, so a service the data lists nowhere is served everywhere. Credential scopes carry signing names, and 46 of them differ from the endpoints.json keys they cover (73 keys, such as ecr for api.ecr); regen_partitions.py vendors that map as signingNames and AwsPartition.offersSigningName joins it. Part of #4272 * fix(core): read the gzipped botocore models the pip package ships when collecting signing names The botocore wheel ships each service model as service-2.json.gz, while the checkout under local/aws/botocore ships it plain. collect_signing_names looked only for the plain file, so in CI, which resolves botocore to the installed package, it found no models, generated an empty signingNames and failed aws-data-check against the committed map. It now reads either form, as regen_dynamodb_shapes.py already does. * fix(sts): keep an assumed-role session in its role's partition, and answer strict-mode Query requests in XML GetCallerIdentity rebuilt an assumed-role session's ARN with an empty region, which falls back to the commercial partition, so a session AssumeRole issued as arn:aws-cn:sts:: came back as arn:aws:sts::, and a chained AssumeRole was then refused by a China trust policy as a caller from another partition. The session ARN now takes the partition its role ARN names. Strict partition mode refused a form-encoded Query request (IAM in aws-eusc) with a JSON body; it now returns the Query XML error the unknown-region guard beside it already returns for such requests. * fix(iam): mint IAM resource ARNs in the request's partition and keep them there CreateUser, CreateGroup, CreateRole, CreatePolicy, CreateInstanceProfile and CreateOpenIDConnectProvider minted arn:aws: whatever partition the request signed, while STS now followed the request. Under China that denied AssumeRoleWithWebIdentity (the trust policy names the arn:aws: provider ARN CreateOpenIDConnectProvider returned, matched against arn:aws-cn:), and AssumeRole reported the request's partition while GetCallerIdentity reported the role's. An IAM resource is now created in the request's partition and keeps it: UpdateUser and UpdateGroup re-mint in the stored ARN's partition. Anything derived from a stored role follows the role: all three AssumeRole handlers, resolveCallerArn and the web identity OIDC provider ARN take the role ARN's partition through AwsArnUtils.partitionOrDefault. The credential report's root row takes the request's partition. * fix(sts): mint a session from the stored role, and keep one credential report per partition AssumeRole, AssumeRoleWithWebIdentity and AssumeRoleWithSAML find the role by account and name, but minted the session ARN from the RoleArn the request named. A China role assumed with an arn:aws: RoleArn therefore came back as an arn:aws:sts:: session, while AssumeRole registered the session under the stored role's ARN, so GetCallerIdentity reported aws-cn. All three handlers now mint the session from the stored role's ARN when the role exists and register it under the same ARN. The credential report was cached once per account, so a report generated for one partition was handed to a caller in another for four hours, with the wrong partition's root row. It is now kept per partition.
This commit is contained in:
1 parent
865dd1d658
commit
0bc85f3ef8
24 files changed
+1086
-37
No files matched your search
@@ -32,6 +32,7 @@ class AccountContextFilterTest {
|
||||
private RequestContext requestContext;
|
||||
private Map<String, String> sessionAccounts;
|
||||
private boolean allowUnknownRegions;
|
||||
private boolean strictPartitions;
|
||||
private AccountContextFilter filter;
|
||||
|
||||
@BeforeEach
|
||||
@@ -41,6 +42,7 @@ class AccountContextFilterTest {
|
||||
requestContext = new RequestContext();
|
||||
sessionAccounts = new java.util.HashMap<>();
|
||||
allowUnknownRegions = false;
|
||||
strictPartitions = false;
|
||||
SessionAccountLookup sessionLookup = akid -> Optional.ofNullable(sessionAccounts.get(akid));
|
||||
filter = new AccountContextFilter(accountResolver, regionResolver, requestContext, sessionLookup,
|
||||
this::config);
|
||||
@@ -49,6 +51,7 @@ class AccountContextFilterTest {
|
||||
private EmulatorConfig config() {
|
||||
EmulatorConfig.PartitionsConfig partitions = mock(EmulatorConfig.PartitionsConfig.class);
|
||||
when(partitions.allowUnknownRegions()).thenReturn(allowUnknownRegions);
|
||||
when(partitions.strict()).thenReturn(strictPartitions);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.partitions()).thenReturn(partitions);
|
||||
return config;
|
||||
@@ -200,6 +203,70 @@ class AccountContextFilterTest {
|
||||
assertEquals("polygondwanaland-west-1", requestContext.getRegion());
|
||||
}
|
||||
|
||||
/** Strict mode: a service AWS publishes nowhere in the request's partition is refused as a 404. */
|
||||
@Test
|
||||
void strictModeRejectsAServiceThePartitionDoesNotPublish() {
|
||||
strictPartitions = true;
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260617/us-gov-west-1/cloudfront/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc",
|
||||
null);
|
||||
filter.filter(ctx);
|
||||
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
|
||||
verify(ctx).abortWith(aborted.capture());
|
||||
assertEquals(404, aborted.getValue().getStatus());
|
||||
assertEquals("UnknownOperationException", aborted.getValue().getHeaderString("X-Amzn-Errortype"));
|
||||
String body = aborted.getValue().getEntity().toString();
|
||||
assertTrue(body.contains("aws-us-gov"), body);
|
||||
assertEquals("aws-us-gov", requestContext.getPartition());
|
||||
}
|
||||
|
||||
/** The signing name is checked, not the endpoint key: ECR signs {@code ecr} for {@code api.ecr}. */
|
||||
@Test
|
||||
void strictModeAcceptsAServiceThePartitionPublishesUnderAnotherEndpointPrefix() {
|
||||
strictPartitions = true;
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260617/cn-north-1/ecr/aws4_request, SignedHeaders=host, Signature=abc",
|
||||
null);
|
||||
filter.filter(ctx);
|
||||
verify(ctx, never()).abortWith(any());
|
||||
filter.filter(mockContext(null, "AKID/20260617/us-gov-west-1/iam/aws4_request"));
|
||||
}
|
||||
|
||||
/** endpoints.json omits the ruleset-only services; silence there is not absence. */
|
||||
@Test
|
||||
void strictModeServesAServiceThePublishedDataDoesNotListAnywhere() {
|
||||
strictPartitions = true;
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260617/us-gov-west-1/fis/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc",
|
||||
null);
|
||||
filter.filter(ctx);
|
||||
verify(ctx, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void strictModeAlsoCoversPresignedCredentials() {
|
||||
strictPartitions = true;
|
||||
ContainerRequestContext ctx = mockContext(null, "AKID/20260617/eusc-de-east-1/iam/aws4_request");
|
||||
filter.filter(ctx);
|
||||
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
|
||||
verify(ctx).abortWith(aborted.capture());
|
||||
assertEquals(404, aborted.getValue().getStatus());
|
||||
}
|
||||
|
||||
/** The default serves every service everywhere: the catalog is consulted only when strict. */
|
||||
@Test
|
||||
void lenientModeServesAPartitionAbsentService() {
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260617/us-gov-west-1/cloudfront/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc",
|
||||
null);
|
||||
filter.filter(ctx);
|
||||
verify(ctx, never()).abortWith(any());
|
||||
assertEquals("aws-us-gov", requestContext.getPartition());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyAuthHeaderFallsBackToPresignedCredential() {
|
||||
ContainerRequestContext ctx = mockContext("",
|
||||
|
||||
@@ -144,6 +144,29 @@ class AwsPartitionsTest {
|
||||
assertFalse(AwsPartitions.commercial().offers(null));
|
||||
}
|
||||
|
||||
/** A credential scope carries the signing name, which for some services is not the endpoint key. */
|
||||
@Test
|
||||
void signingNamesJoinTheEndpointPrefixesTheyCover() {
|
||||
assertEquals(Set.of("api.ecr"), AwsPartitions.endpointPrefixes("ecr"));
|
||||
assertTrue(AwsPartitions.endpointPrefixes("bedrock").contains("bedrock-runtime"));
|
||||
assertEquals(Set.of(), AwsPartitions.endpointPrefixes("sqs"));
|
||||
assertEquals(Set.of(), AwsPartitions.endpointPrefixes(null));
|
||||
|
||||
assertTrue(AwsPartitions.commercial().offersSigningName("ecr"));
|
||||
assertTrue(AwsPartitions.byId("aws-cn").offersSigningName("ecr"));
|
||||
assertTrue(AwsPartitions.byId("aws-cn").offersSigningName("sqs"));
|
||||
assertFalse(AwsPartitions.byId("aws-us-gov").offersSigningName("cloudfront"));
|
||||
assertFalse(AwsPartitions.byId("aws-eusc").offersSigningName("iam"));
|
||||
assertFalse(AwsPartitions.commercial().offersSigningName("no-such-service"));
|
||||
assertFalse(AwsPartitions.commercial().offersSigningName(null));
|
||||
|
||||
assertTrue(AwsPartitions.publishesSomewhere("cloudfront"));
|
||||
assertTrue(AwsPartitions.publishesSomewhere("ecr"), "a signing name whose endpoint prefix is published");
|
||||
assertFalse(AwsPartitions.publishesSomewhere("fis"), "endpoints.json omits the ruleset-only services");
|
||||
assertFalse(AwsPartitions.publishesSomewhere("no-such-service"));
|
||||
assertFalse(AwsPartitions.publishesSomewhere(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void optInAndWebsiteFormFlagsComeFromTheCdkRules() {
|
||||
AwsPartition aws = AwsPartitions.commercial();
|
||||
|
||||
+26
@@ -15,6 +15,7 @@ import java.util.List;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -186,4 +187,29 @@ class PartitionRegionGatesIntegrationTest {
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("regions", hasSize(4));
|
||||
}
|
||||
|
||||
/** GetCallerIdentity's root fallback and GetAccountSummary follow the request's partition. */
|
||||
@Test
|
||||
void stsAndIamGlobalAnswersFollowTheRequestsPartition() {
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "sts"))
|
||||
.formParam("Action", "GetCallerIdentity")
|
||||
.formParam("Version", "2011-06-15")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Arn>arn:aws-cn:iam::000000000000:root</Arn>"));
|
||||
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "iam"))
|
||||
.formParam("Action", "GetAccountSummary")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<key>Users</key>"))
|
||||
.body(not(containsString("GlobalEndpointTokenVersion")));
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "iam"))
|
||||
.formParam("Action", "GetAccountSummary")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<key>GlobalEndpointTokenVersion</key>"));
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* {@code floci.partitions.strict=true}: a request signed for a service AWS does not publish in
|
||||
* the request's partition is refused the way the SDKs experience it on AWS, where the host
|
||||
* never resolves. Everything the partition does publish keeps working.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(PartitionStrictModeIntegrationTest.StrictPartitionsProfile.class)
|
||||
class PartitionStrictModeIntegrationTest {
|
||||
|
||||
@Inject
|
||||
ResolvedServiceCatalog catalog;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudFrontIsRefusedInGovCloud() {
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("us-gov-west-1", "cloudfront"))
|
||||
.when().get("/2020-05-31/distribution").then().statusCode(404)
|
||||
.header("X-Amzn-Errortype", "UnknownOperationException")
|
||||
.body("__type", equalTo("UnknownOperationException"))
|
||||
.body("message", containsString("cloudfront has no endpoint in partition aws-us-gov"));
|
||||
}
|
||||
|
||||
/** IAM speaks the Query protocol, so the refusal is the Query XML error a Query client parses. */
|
||||
@Test
|
||||
void iamIsRefusedInEuscWithAQueryError() {
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("eusc-de-east-1", "iam"))
|
||||
.formParam("Action", "ListRoles")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.when().post("/").then().statusCode(404)
|
||||
.contentType(containsString("xml"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("UnknownOperationException"))
|
||||
.body("ErrorResponse.Error.Message", containsString("iam has no endpoint in partition aws-eusc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishedServicesStillAnswer() {
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "s3"))
|
||||
.when().get("/").then().statusCode(200);
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "iam"))
|
||||
.formParam("Action", "ListRoles")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.when().post("/").then().statusCode(200);
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "cloudfront"))
|
||||
.when().get("/2020-05-31/distribution").then().statusCode(200);
|
||||
}
|
||||
|
||||
/** A service the published data lists nowhere (FIS ships only an endpoint ruleset) is served everywhere. */
|
||||
@Test
|
||||
void servicesThePublishedDataDoesNotListAreServedEverywhere() {
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth("us-gov-west-1", "fis"))
|
||||
.when().get("/experimentTemplates").then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict mode can only refuse what AWS refuses: every signing name Floci answers to that
|
||||
* the published data knows at all must be one the commercial partition publishes, directly
|
||||
* or through the endpoint prefixes the signing name covers, or strict mode would 404 a
|
||||
* route that works.
|
||||
*/
|
||||
@Test
|
||||
void everyCatalogCredentialScopeThePublishedDataKnowsIsInTheCommercialPartition() {
|
||||
TreeSet<String> unpublished = new TreeSet<>();
|
||||
for (ServiceDescriptor descriptor : catalog.all()) {
|
||||
for (String scope : descriptor.credentialScopes()) {
|
||||
if (AwsPartitions.publishesSomewhere(scope) && !AwsPartitions.commercial().offersSigningName(scope)) {
|
||||
unpublished.add(descriptor.externalKey() + ":" + scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(unpublished.isEmpty(),
|
||||
"credential scopes the commercial partition does not publish: " + unpublished);
|
||||
}
|
||||
|
||||
public static final class StrictPartitionsProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.partitions.strict", "true");
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -302,6 +302,8 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
public Optional<String> id() { return Optional.empty(); }
|
||||
@Override
|
||||
public boolean allowUnknownRegions() { return false; }
|
||||
@Override
|
||||
public boolean strict() { return false; }
|
||||
};
|
||||
}
|
||||
@Override
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* IAM resources are minted in the partition of the request that creates them, and keep it: a
|
||||
* rename signed for another partition does not move a resource.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IamPartitionArnIntegrationTest {
|
||||
|
||||
private static final String TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
|
||||
private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
|
||||
void createdResourcesCarryTheRequestsPartition(PartitionCase partitionCase) {
|
||||
String region = partitionCase.region();
|
||||
String suffix = partitionCase.partition() + "-" + Long.toString(System.nanoTime(), 36);
|
||||
|
||||
String userName = "partition-user-" + suffix;
|
||||
String userArn = iam(region, "CreateUser", "UserName", userName)
|
||||
.then().statusCode(200).extract().path("CreateUserResponse.CreateUserResult.User.Arn");
|
||||
cleanup.register(() -> iam(region, "DeleteUser", "UserName", userName));
|
||||
assertIamArn(partitionCase, "user/" + userName, userArn);
|
||||
|
||||
String groupName = "partition-group-" + suffix;
|
||||
String groupArn = iam(region, "CreateGroup", "GroupName", groupName)
|
||||
.then().statusCode(200).extract().path("CreateGroupResponse.CreateGroupResult.Group.Arn");
|
||||
cleanup.register(() -> iam(region, "DeleteGroup", "GroupName", groupName));
|
||||
assertIamArn(partitionCase, "group/" + groupName, groupArn);
|
||||
|
||||
String roleName = "partition-role-" + suffix;
|
||||
String roleArn = iam(region, "CreateRole", "RoleName", roleName, "AssumeRolePolicyDocument", TRUST_POLICY)
|
||||
.then().statusCode(200).extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
|
||||
cleanup.register(() -> iam(region, "DeleteRole", "RoleName", roleName));
|
||||
assertIamArn(partitionCase, "role/" + roleName, roleArn);
|
||||
|
||||
String policyName = "partition-policy-" + suffix;
|
||||
String policyArn = iam(region, "CreatePolicy", "PolicyName", policyName, "PolicyDocument", POLICY)
|
||||
.then().statusCode(200).extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
|
||||
cleanup.register(() -> iam(region, "DeletePolicy", "PolicyArn", policyArn));
|
||||
assertIamArn(partitionCase, "policy/" + policyName, policyArn);
|
||||
|
||||
String profileName = "partition-profile-" + suffix;
|
||||
String profileArn = iam(region, "CreateInstanceProfile", "InstanceProfileName", profileName)
|
||||
.then().statusCode(200)
|
||||
.extract().path("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
|
||||
cleanup.register(() -> iam(region, "DeleteInstanceProfile", "InstanceProfileName", profileName));
|
||||
assertIamArn(partitionCase, "instance-profile/" + profileName, profileArn);
|
||||
|
||||
String providerHost = "oidc-" + suffix + ".example.com";
|
||||
String providerArn = iam(region, "CreateOpenIDConnectProvider", "Url", "https://" + providerHost,
|
||||
"ThumbprintList.member.1", "9e99a48a9960b14926bb7f3b02e22da2b0ab7280")
|
||||
.then().statusCode(200)
|
||||
.extract().path("CreateOpenIDConnectProviderResponse.CreateOpenIDConnectProviderResult"
|
||||
+ ".OpenIDConnectProviderArn");
|
||||
cleanup.register(() -> iam(region, "DeleteOpenIDConnectProvider", "OpenIDConnectProviderArn", providerArn));
|
||||
assertIamArn(partitionCase, "oidc-provider/" + providerHost, providerArn);
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameSignedForAnotherPartitionKeepsTheUsersPartition() {
|
||||
String userName = "partition-rename-" + Long.toString(System.nanoTime(), 36);
|
||||
String renamed = userName + "-renamed";
|
||||
iam("cn-north-1", "CreateUser", "UserName", userName).then().statusCode(200);
|
||||
cleanup.register(() -> iam("cn-north-1", "DeleteUser", "UserName", renamed));
|
||||
|
||||
iam("us-east-1", "UpdateUser", "UserName", userName, "NewUserName", renamed).then().statusCode(200);
|
||||
|
||||
String arn = iam("us-east-1", "GetUser", "UserName", renamed)
|
||||
.then().statusCode(200).extract().path("GetUserResponse.GetUserResult.User.Arn");
|
||||
assertEquals("arn:aws-cn:iam::" + PartitionMatrix.ACCOUNT + ":user/" + renamed, arn);
|
||||
}
|
||||
|
||||
/** A report generated for one partition is never handed to a caller in another. */
|
||||
@Test
|
||||
void eachPartitionGetsItsOwnCredentialReport() {
|
||||
assertEquals("arn:aws-iso-f:iam::" + PartitionMatrix.ACCOUNT + ":root",
|
||||
credentialReportRootArn("us-isof-south-1"));
|
||||
assertEquals("arn:aws-iso-e:iam::" + PartitionMatrix.ACCOUNT + ":root",
|
||||
credentialReportRootArn("eu-isoe-west-1"));
|
||||
}
|
||||
|
||||
private static String credentialReportRootArn(String region) {
|
||||
iam(region, "GenerateCredentialReport").then().statusCode(200);
|
||||
String content = iam(region, "GetCredentialReport").then().statusCode(200)
|
||||
.extract().path("GetCredentialReportResponse.GetCredentialReportResult.Content");
|
||||
String report = new String(Base64.getDecoder().decode(content), StandardCharsets.UTF_8);
|
||||
return report.lines().filter(line -> line.startsWith("<root_account>,")).findFirst()
|
||||
.orElseThrow().split(",")[1];
|
||||
}
|
||||
|
||||
private static void assertIamArn(PartitionCase partitionCase, String resource, String arn) {
|
||||
assertEquals("arn:" + partitionCase.partition() + ":iam::" + PartitionMatrix.ACCOUNT + ":" + resource, arn);
|
||||
}
|
||||
|
||||
private static Response iam(String region, String action, String... params) {
|
||||
RequestSpecification request = given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(region, "iam"))
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-05-08");
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
request.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
return request.when().post("/");
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
@@ -50,6 +51,12 @@ class IamServiceTest {
|
||||
|
||||
private static IamService iamService(boolean seedDeployerPrincipal, StorageBackend<String, AccessKey> accessKeys,
|
||||
StorageBackend<String, SessionCredential> sessions) {
|
||||
return iamService(seedDeployerPrincipal, accessKeys, sessions, new RegionResolver("us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
private static IamService iamService(boolean seedDeployerPrincipal, StorageBackend<String, AccessKey> accessKeys,
|
||||
StorageBackend<String, SessionCredential> sessions,
|
||||
RegionResolver regionResolver) {
|
||||
return new IamService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
@@ -58,11 +65,33 @@ class IamServiceTest {
|
||||
accessKeys,
|
||||
new InMemoryStorage<>(),
|
||||
sessions,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
regionResolver,
|
||||
seedDeployerPrincipal
|
||||
);
|
||||
}
|
||||
|
||||
/** The STS global endpoint, and so the token version it reports, exists only in the commercial partition. */
|
||||
@Test
|
||||
void accountSummaryReportsTheGlobalEndpointTokenVersionOnlyWhereStsHasAGlobalHost() {
|
||||
assertEquals(1L, iamService.getAccountSummary().get("GlobalEndpointTokenVersion"));
|
||||
|
||||
IamService china = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver("cn-north-1", "000000000000"));
|
||||
assertFalse(china.getAccountSummary().containsKey("GlobalEndpointTokenVersion"));
|
||||
assertEquals(0L, china.getAccountSummary().get("Users"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void credentialReportRootRowCarriesThePartition() {
|
||||
IamService china = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver("cn-north-1", "000000000000"));
|
||||
china.generateCredentialReport();
|
||||
|
||||
String report = new String(Base64.getDecoder().decode(china.getCredentialReport().base64Content()),
|
||||
StandardCharsets.UTF_8);
|
||||
assertTrue(report.contains("<root_account>,arn:aws-cn:iam::000000000000:root,"), report);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2SessionUsesInstanceIdentityTokenAndOwningAccount() {
|
||||
SessionCredential session = new SessionCredential("ASIAEC2SESSION", "secret", "token",
|
||||
@@ -2199,7 +2228,7 @@ class IamServiceTest {
|
||||
@Test
|
||||
void getCredentialReportOnAnExpiredReportThrowsReportExpired() {
|
||||
StorageBackend<String, CredentialReport> credentialReports = new InMemoryStorage<>();
|
||||
credentialReports.put("credential-report",
|
||||
credentialReports.put("credential-report/aws",
|
||||
new CredentialReport("dGVzdA==", Instant.now().minus(Duration.ofHours(5))));
|
||||
IamService withExpiredReport = new IamService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
@@ -2216,7 +2245,7 @@ class IamServiceTest {
|
||||
@Test
|
||||
void generateCredentialReportOnAnExpiredReportStartsANewOne() {
|
||||
StorageBackend<String, CredentialReport> credentialReports = new InMemoryStorage<>();
|
||||
credentialReports.put("credential-report",
|
||||
credentialReports.put("credential-report/aws",
|
||||
new CredentialReport("dGVzdA==", Instant.now().minus(Duration.ofHours(5))));
|
||||
IamService withExpiredReport = new IamService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
|
||||
@@ -4,21 +4,34 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AccountResolver;
|
||||
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.WebIdentityToken;
|
||||
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class StsQueryHandlerTest {
|
||||
@@ -29,7 +42,13 @@ class StsQueryHandlerTest {
|
||||
private static final Pattern SESSION_TOKEN =
|
||||
Pattern.compile("<SessionToken>([^<]+)</SessionToken>");
|
||||
|
||||
private static final Pattern ARN = Pattern.compile("<Arn>([^<]+)</Arn>");
|
||||
|
||||
private static StsQueryHandler newHandler() {
|
||||
return newHandler(new RegionResolver(REGION, "000000000000"));
|
||||
}
|
||||
|
||||
private static StsQueryHandler newHandler(RegionResolver regionResolver) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
|
||||
@@ -40,7 +59,7 @@ class StsQueryHandlerTest {
|
||||
return new StsQueryHandler(
|
||||
mock(IamService.class),
|
||||
mock(AccountResolver.class),
|
||||
new RegionResolver(REGION, "000000000000"),
|
||||
regionResolver,
|
||||
config,
|
||||
mock(AssumeRolePolicyEvaluator.class),
|
||||
mock(WebIdentityTrustPolicyEvaluator.class),
|
||||
@@ -225,6 +244,98 @@ class StsQueryHandlerTest {
|
||||
assertTrue(body.contains("greater than or equal to 900"), body);
|
||||
}
|
||||
|
||||
/** The root ARN GetCallerIdentity falls back to carries the deployment's partition, not {@code aws}. */
|
||||
@ParameterizedTest
|
||||
@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
|
||||
void getCallerIdentityMintsTheRootArnInTheDeploymentsPartition(PartitionCase partitionCase) {
|
||||
Response response = newHandler(PartitionMatrix.regionResolver(partitionCase))
|
||||
.handle("GetCallerIdentity", new MultivaluedHashMap<>());
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String arn = extract(ARN, (String) response.getEntity());
|
||||
assertEquals("arn:" + partitionCase.partition() + ":iam::" + PartitionMatrix.ACCOUNT + ":root", arn);
|
||||
PartitionMatrix.assertGlobalArnIn(partitionCase, arn);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
|
||||
void getFederationTokenMintsTheFederatedUserArnInTheDeploymentsPartition(PartitionCase partitionCase) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Name", "bob");
|
||||
|
||||
Response response = newHandler(PartitionMatrix.regionResolver(partitionCase))
|
||||
.handle("GetFederationToken", params);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String arn = extract(ARN, (String) response.getEntity());
|
||||
assertEquals("arn:" + partitionCase.partition() + ":sts::" + PartitionMatrix.ACCOUNT
|
||||
+ ":federated-user/bob", arn);
|
||||
}
|
||||
|
||||
/**
|
||||
* A role and its account's OIDC provider are IAM resources of one partition, so a trust policy
|
||||
* naming the provider ARN CreateOpenIDConnectProvider returned keeps matching and the session
|
||||
* lands in the stored role's partition, whatever region AssumeRoleWithWebIdentity is signed for
|
||||
* and whichever partition its RoleArn names.
|
||||
*/
|
||||
@Test
|
||||
void webIdentityMatchesTheProviderAndMintsTheSessionInTheRolesPartition() throws Exception {
|
||||
String issuer = "https://oidc.example.com/id/ABC";
|
||||
String roleArn = "arn:aws-cn:iam::000000000000:role/web-role";
|
||||
String requestedRoleArn = "arn:aws:iam::000000000000:role/web-role";
|
||||
String providerArn = "arn:aws-cn:iam::000000000000:oidc-provider/oidc.example.com/id/ABC";
|
||||
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.iam()).thenReturn(iam);
|
||||
IamService iamService = mock(IamService.class);
|
||||
IamRole role = new IamRole();
|
||||
role.setArn(roleArn);
|
||||
role.setAssumeRolePolicyDocument("{}");
|
||||
when(iamService.findRole("000000000000", "web-role")).thenReturn(Optional.of(role));
|
||||
WebIdentityTokenVerifier verifier = mock(WebIdentityTokenVerifier.class);
|
||||
when(verifier.peekIssuer("jwt")).thenReturn(Optional.of(issuer));
|
||||
when(verifier.verify(eq("jwt"), any(), eq(issuer), anyString()))
|
||||
.thenReturn(new WebIdentityToken(issuer, "system:serviceaccount:default:app",
|
||||
List.of("sts.amazonaws.com")));
|
||||
OidcIssuerKeyLookup keys = mock(OidcIssuerKeyLookup.class);
|
||||
when(keys.findVerificationKey(issuer)).thenReturn(Optional.of(mock(RSAPublicKey.class)));
|
||||
WebIdentityTrustPolicyEvaluator trust = mock(WebIdentityTrustPolicyEvaluator.class);
|
||||
when(trust.allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap())).thenReturn(true);
|
||||
|
||||
StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class),
|
||||
new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class),
|
||||
trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class));
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("RoleArn", requestedRoleArn);
|
||||
params.putSingle("RoleSessionName", "app");
|
||||
params.putSingle("WebIdentityToken", "jwt");
|
||||
|
||||
Response response = handler.handle("AssumeRoleWithWebIdentity", params);
|
||||
|
||||
assertEquals(200, response.getStatus(), (String) response.getEntity());
|
||||
verify(trust).allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap());
|
||||
assertEquals("arn:aws-cn:sts::000000000000:assumed-role/web-role/app",
|
||||
extract(ARN, (String) response.getEntity()));
|
||||
}
|
||||
|
||||
/** A session keeps its role's partition even when AssumeRole is signed for another one. */
|
||||
@Test
|
||||
void assumeRoleMintsTheSessionInTheRolesPartition() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/commercial-role");
|
||||
params.putSingle("RoleSessionName", "s");
|
||||
|
||||
Response response = newHandler(new RegionResolver("cn-north-1", "000000000000"))
|
||||
.handle("AssumeRole", params);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("arn:aws:sts::000000000000:assumed-role/commercial-role/s",
|
||||
extract(ARN, (String) response.getEntity()));
|
||||
}
|
||||
|
||||
private static String extract(Pattern pattern, String body) {
|
||||
Matcher matcher = pattern.matcher(body);
|
||||
assertTrue(matcher.find(), "expected " + pattern + " in " + body);
|
||||
|
||||
+125
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class StsSessionIdentityIntegrationTest {
|
||||
@@ -18,6 +19,9 @@ class StsSessionIdentityIntegrationTest {
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260925/us-east-1/iam/aws4_request";
|
||||
private static final String STS_AUTHORIZATION =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260925/us-east-1/sts/aws4_request";
|
||||
private static final String CHINA_ROLE_NAME = "sts-session-identity-china-role";
|
||||
private static final String CHINA_IAM_AUTHORIZATION =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260925/cn-north-1/iam/aws4_request";
|
||||
|
||||
@AfterEach
|
||||
void deleteRole() {
|
||||
@@ -26,6 +30,11 @@ class StsSessionIdentityIntegrationTest {
|
||||
.formParam("RoleName", ROLE_NAME)
|
||||
.header("Authorization", AUTHORIZATION)
|
||||
.when().post("/");
|
||||
given()
|
||||
.formParam("Action", "DeleteRole")
|
||||
.formParam("RoleName", CHINA_ROLE_NAME)
|
||||
.header("Authorization", CHINA_IAM_AUTHORIZATION)
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -65,4 +74,120 @@ class StsSessionIdentityIntegrationTest {
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn))
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(assumedRoleId));
|
||||
}
|
||||
|
||||
/** The session keeps its role's partition: GetCallerIdentity reports the ARN AssumeRole issued. */
|
||||
@Test
|
||||
void callerIdentityKeepsTheChinaPartitionOfTheAssumedRoleSession() {
|
||||
String roleArn = given()
|
||||
.formParam("Action", "CreateRole")
|
||||
.formParam("RoleName", CHINA_ROLE_NAME)
|
||||
.formParam("AssumeRolePolicyDocument",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"arn:aws-cn:iam::000000000000:root\"},"
|
||||
+ "\"Action\":\"sts:AssumeRole\"}]}")
|
||||
.header("Authorization", CHINA_IAM_AUTHORIZATION)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
|
||||
assertEquals("arn:aws-cn:iam::000000000000:role/" + CHINA_ROLE_NAME, roleArn);
|
||||
|
||||
ValidatableResponse assumed = given()
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", SESSION_NAME)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260925/cn-north-1/sts/aws4_request")
|
||||
.when().post("/").then().statusCode(200);
|
||||
String accessKeyId = assumed.extract().path(
|
||||
"AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
|
||||
String sessionToken = assumed.extract().path(
|
||||
"AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken");
|
||||
String assumedRoleArn = assumed.extract().path(
|
||||
"AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
|
||||
assertEquals("arn:aws-cn:sts::000000000000:assumed-role/" + CHINA_ROLE_NAME + "/" + SESSION_NAME,
|
||||
assumedRoleArn);
|
||||
|
||||
given()
|
||||
.formParam("Action", "GetCallerIdentity")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=" + accessKeyId
|
||||
+ "/20260925/cn-north-1/sts/aws4_request")
|
||||
.header("X-Amz-Security-Token", sessionToken)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn));
|
||||
}
|
||||
|
||||
/**
|
||||
* A role created in the commercial partition and assumed with a call signed for China: the
|
||||
* session stays in the role's partition, and AssumeRole and GetCallerIdentity agree on it.
|
||||
*/
|
||||
@Test
|
||||
void assumeRoleAndCallerIdentityAgreeWhenSignedForAnotherPartition() {
|
||||
String roleArn = given()
|
||||
.formParam("Action", "CreateRole")
|
||||
.formParam("RoleName", ROLE_NAME)
|
||||
.formParam("AssumeRolePolicyDocument",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}")
|
||||
.header("Authorization", AUTHORIZATION)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
|
||||
|
||||
ValidatableResponse assumed = given()
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", SESSION_NAME)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260925/cn-north-1/sts/aws4_request")
|
||||
.when().post("/").then().statusCode(200);
|
||||
String assumedRoleArn = assumed.extract().path(
|
||||
"AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
|
||||
assertEquals("arn:aws:sts::000000000000:assumed-role/" + ROLE_NAME + "/" + SESSION_NAME, assumedRoleArn);
|
||||
|
||||
given()
|
||||
.formParam("Action", "GetCallerIdentity")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential="
|
||||
+ assumed.extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId")
|
||||
+ "/20260925/cn-north-1/sts/aws4_request")
|
||||
.header("X-Amz-Security-Token", (String) assumed.extract().path(
|
||||
"AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"))
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn));
|
||||
}
|
||||
|
||||
/**
|
||||
* A RoleArn naming another partition still finds the role (Floci keys IAM by account and
|
||||
* name), but the session belongs to the stored role, so it keeps the role's China partition.
|
||||
*/
|
||||
@Test
|
||||
void sessionFollowsTheStoredRoleWhenTheRoleArnNamesAnotherPartition() {
|
||||
given()
|
||||
.formParam("Action", "CreateRole")
|
||||
.formParam("RoleName", CHINA_ROLE_NAME)
|
||||
.formParam("AssumeRolePolicyDocument",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}")
|
||||
.header("Authorization", CHINA_IAM_AUTHORIZATION)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
ValidatableResponse assumed = given()
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", "arn:aws:iam::000000000000:role/" + CHINA_ROLE_NAME)
|
||||
.formParam("RoleSessionName", SESSION_NAME)
|
||||
.header("Authorization", STS_AUTHORIZATION)
|
||||
.when().post("/").then().statusCode(200);
|
||||
String assumedRoleArn = assumed.extract().path(
|
||||
"AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
|
||||
assertEquals("arn:aws-cn:sts::000000000000:assumed-role/" + CHINA_ROLE_NAME + "/" + SESSION_NAME,
|
||||
assumedRoleArn);
|
||||
|
||||
given()
|
||||
.formParam("Action", "GetCallerIdentity")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential="
|
||||
+ assumed.extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId")
|
||||
+ "/20260925/us-east-1/sts/aws4_request")
|
||||
.header("X-Amz-Security-Token", (String) assumed.extract().path(
|
||||
"AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"))
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user