Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(sts): reject AssumeRole for roles that do not exist (#4463)

Vũ Thế Huy436c15ca3855
diff --git a/compatibility-tests/sdk-test-awscli/test/sts.bats b/compatibility-tests/sdk-test-awscli/test/sts.bats
index 5e89d39088..393595eb18 100644
--- a/compatibility-tests/sdk-test-awscli/test/sts.bats
+++ b/compatibility-tests/sdk-test-awscli/test/sts.bats
@@ -3,6 +3,11 @@
setup() {
load 'test_helper/common-setup'
+ ROLE_NAME="bats-sts-role-$(unique_name)"
+}
+
+teardown() {
+ aws_cmd iam delete-role --role-name "$ROLE_NAME" >/dev/null 2>&1 || true
}
@test "STS: get caller identity" {
@@ -15,7 +20,10 @@ setup() {
}
@test "STS: assume role" {
- local role_arn="arn:aws:iam::000000000000:role/test-role"
+ local policy_doc='{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"}]}'
+ aws_cmd iam create-role --role-name "$ROLE_NAME" --assume-role-policy-document "$policy_doc" >/dev/null
+
+ local role_arn="arn:aws:iam::000000000000:role/$ROLE_NAME"
run aws_cmd sts assume-role \
--role-arn "$role_arn" \
@@ -24,3 +32,11 @@ setup() {
access_key=$(json_get "$output" '.Credentials.AccessKeyId')
[ -n "$access_key" ]
}
+
+@test "STS: assume nonexistent role is denied" {
+ run aws_cmd sts assume-role \
+ --role-arn "arn:aws:iam::000000000000:role/nonexistent-role-$(unique_name)" \
+ --role-session-name "bats-test-session"
+ assert_failure
+ assert_output --partial "AccessDenied"
+}
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java
index 0e0f0b8447..9e5cd75950 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsTest.java
@@ -11,6 +11,8 @@ import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.CreateRoleRequest;
import software.amazon.awssdk.services.iam.model.CreateSamlProviderRequest;
import software.amazon.awssdk.services.iam.model.CreateSamlProviderResponse;
+import software.amazon.awssdk.services.iam.model.DeleteRoleRequest;
+import software.amazon.awssdk.services.iam.model.NoSuchEntityException;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.*;
import org.w3c.dom.Document;
@@ -59,12 +61,31 @@ class StsTest {
private static String allowedRoleArn;
private static String allowedRoleName;
+ private static final String OPEN_TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}";
+
@BeforeAll
static void setup() throws Exception {
sts = TestFixtures.stsClient();
iam = TestFixtures.iamClient();
signingKeys = createSigningKeys();
+ iam.createRole(CreateRoleRequest.builder()
+ .roleName("sdk-test-assumed-role")
+ .assumeRolePolicyDocument(OPEN_TRUST_POLICY)
+ .build());
+ iam.createRole(CreateRoleRequest.builder()
+ .roleName("my-role")
+ .assumeRolePolicyDocument(OPEN_TRUST_POLICY)
+ .build());
+ iam.createRole(CreateRoleRequest.builder()
+ .roleName("short-lived-role")
+ .assumeRolePolicyDocument(OPEN_TRUST_POLICY)
+ .build());
+ iam.createRole(CreateRoleRequest.builder()
+ .roleName("web-identity-role")
+ .assumeRolePolicyDocument(OPEN_TRUST_POLICY)
+ .build());
+
String issuer = "https://sdk-test.example.test/saml";
String providerName = TestFixtures.uniqueName("sdk-saml");
String certificate = createCertificate(signingKeys);
@@ -88,6 +109,11 @@ class StsTest {
@AfterAll
static void cleanup() {
+ safeDeleteRole("sdk-test-assumed-role");
+ safeDeleteRole("my-role");
+ safeDeleteRole("short-lived-role");
+ safeDeleteRole("web-identity-role");
+ safeDeleteRole(allowedRoleName);
if (iam != null) {
iam.close();
}
@@ -96,6 +122,16 @@ class StsTest {
}
}
+ private static void safeDeleteRole(String roleName) {
+ if (iam != null && roleName != null) {
+ try {
+ iam.deleteRole(DeleteRoleRequest.builder().roleName(roleName).build());
+ } catch (NoSuchEntityException ignored) {
+ // Safe to ignore if the role was already cleaned up or never created.
+ }
+ }
+ }
+
@Test
void getCallerIdentity() {
GetCallerIdentityResponse response = sts.getCallerIdentity(
@@ -211,6 +247,31 @@ class StsTest {
.isEqualTo(400);
}
+ @Test
+ void assumeRoleNonExistentRoleThrows403() {
+ assertThatThrownBy(() -> sts.assumeRole(AssumeRoleRequest.builder()
+ .roleArn("arn:aws:iam::000000000000:role/non-existent-role-" + UUID.randomUUID())
+ .roleSessionName("sdk-test-session")
+ .build()))
+ .isInstanceOf(StsException.class)
+ .extracting(e -> ((StsException) e).statusCode())
+ .isEqualTo(403);
+ }
+
+ @Test
+ void assumeRoleWithWebIdentityNonExistentRoleThrows403() {
+ assertThatThrownBy(() -> sts.assumeRoleWithWebIdentity(
+ AssumeRoleWithWebIdentityRequest.builder()
+ .roleArn("arn:aws:iam::000000000000:role/non-existent-role-" + UUID.randomUUID())
+ .roleSessionName("sdk-test-session")
+ .webIdentityToken("eyJhbGciOiJSUzI1NiJ9.test-token")
+ .durationSeconds(3600)
+ .build()))
+ .isInstanceOf(StsException.class)
+ .extracting(e -> ((StsException) e).statusCode())
+ .isEqualTo(403);
+ }
+
@Test
void assumeRoleWithSaml() {
AssumeRoleWithSamlResponse response = validAssumeRoleWithSaml();
diff --git a/compatibility-tests/sdk-test-node/tests/sts.test.ts b/compatibility-tests/sdk-test-node/tests/sts.test.ts
index f4b5ac920d..69f3ca785d 100644
--- a/compatibility-tests/sdk-test-node/tests/sts.test.ts
+++ b/compatibility-tests/sdk-test-node/tests/sts.test.ts
@@ -2,15 +2,51 @@
* STS integration tests.
*/
-import { describe, it, expect, beforeAll } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { STSClient, GetCallerIdentityCommand, AssumeRoleCommand } from '@aws-sdk/client-sts';
+import { IAMClient, CreateRoleCommand, DeleteRoleCommand } from '@aws-sdk/client-iam';
import { makeClient, ACCOUNT } from './setup';
describe('STS', () => {
let sts: STSClient;
+ let iam: IAMClient;
+ const roleName = 'test-role';
- beforeAll(() => {
+ beforeAll(async () => {
sts = makeClient(STSClient);
+ iam = makeClient(IAMClient);
+ const trustPolicy = JSON.stringify({
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Effect: 'Allow',
+ Principal: { AWS: '*' },
+ Action: 'sts:AssumeRole',
+ },
+ ],
+ });
+ try {
+ await iam.send(
+ new CreateRoleCommand({
+ RoleName: roleName,
+ AssumeRolePolicyDocument: trustPolicy,
+ })
+ );
+ } catch (err: unknown) {
+ if ((err as { name?: string })?.name !== 'EntityAlreadyExistsException') {
+ throw err;
+ }
+ }
+ });
+
+ afterAll(async () => {
+ try {
+ await iam.send(new DeleteRoleCommand({ RoleName: roleName }));
+ } catch (err: unknown) {
+ if ((err as { name?: string })?.name !== 'NoSuchEntityException') {
+ throw err;
+ }
+ }
});
it('should get caller identity', async () => {
@@ -22,10 +58,21 @@ describe('STS', () => {
it('should assume role', async () => {
const response = await sts.send(
new AssumeRoleCommand({
- RoleArn: `arn:aws:iam::${ACCOUNT}:role/test-role`,
+ RoleArn: `arn:aws:iam::${ACCOUNT}:role/${roleName}`,
RoleSessionName: 'test-session',
})
);
expect(response.Credentials?.AccessKeyId).toBeTruthy();
});
+
+ it('should deny assume role for nonexistent role', async () => {
+ await expect(
+ sts.send(
+ new AssumeRoleCommand({
+ RoleArn: `arn:aws:iam::${ACCOUNT}:role/definitely-nonexistent-role`,
+ RoleSessionName: 'test-session',
+ })
+ )
+ ).rejects.toThrow();
+ });
});
diff --git a/compatibility-tests/sdk-test-python/tests/test_sts.py b/compatibility-tests/sdk-test-python/tests/test_sts.py
index 71fb7eeaa9..955a5e6a7f 100644
--- a/compatibility-tests/sdk-test-python/tests/test_sts.py
+++ b/compatibility-tests/sdk-test-python/tests/test_sts.py
@@ -23,6 +23,33 @@ class TestSTSIdentity:
class TestSTSAssumeRole:
"""Test STS assume role operations."""
+ @pytest.fixture(autouse=True)
+ def setup_roles(self, iam_client):
+ trust_policy = '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"}]}'
+ roles = ["pytest-assumed-role", "my-role", "web-identity-role"]
+ for role in roles:
+ try:
+ iam_client.create_role(
+ RoleName=role,
+ AssumeRolePolicyDocument=trust_policy,
+ )
+ except ClientError as e:
+ if e.response.get("Error", {}).get("Code") == "EntityAlreadyExists":
+ # Safe to ignore if the role already exists from a prior test run.
+ pass
+ else:
+ raise
+ yield
+ for role in roles:
+ try:
+ iam_client.delete_role(RoleName=role)
+ except ClientError as e:
+ if e.response.get("Error", {}).get("Code") == "NoSuchEntity":
+ # Safe to ignore if the role was already cleaned up or never created.
+ pass
+ else:
+ raise
+
def test_assume_role(self, sts_client):
"""Test AssumeRole returns temporary credentials."""
response = sts_client.assume_role(
@@ -43,6 +70,15 @@ class TestSTSAssumeRole:
)
assert "assumed-role/my-role/my-session" in response["AssumedRoleUser"]["Arn"]
+ def test_assume_role_nonexistent_role_denied(self, sts_client):
+ """Test AssumeRole returns 403 AccessDenied for nonexistent role."""
+ with pytest.raises(ClientError) as exc_info:
+ sts_client.assume_role(
+ RoleArn="arn:aws:iam::000000000000:role/nonexistent-role-xyz",
+ RoleSessionName="pytest-session",
+ )
+ assert exc_info.value.response["Error"]["Code"] == "AccessDenied"
+
def test_assume_role_with_web_identity(self, sts_client):
"""Test AssumeRoleWithWebIdentity returns credentials."""
response = sts_client.assume_role_with_web_identity(
@@ -58,6 +94,16 @@ class TestSTSAssumeRole:
in response["AssumedRoleUser"]["Arn"]
)
+ def test_assume_role_with_web_identity_nonexistent_role_denied(self, sts_client):
+ """Test AssumeRoleWithWebIdentity returns 403 AccessDenied for nonexistent role."""
+ with pytest.raises(ClientError) as exc_info:
+ sts_client.assume_role_with_web_identity(
+ RoleArn="arn:aws:iam::000000000000:role/nonexistent-role-xyz",
+ RoleSessionName="web-session",
+ WebIdentityToken="dummy-token",
+ )
+ assert exc_info.value.response["Error"]["Code"] == "AccessDenied"
+
def test_assume_role_missing_role_arn(self, sts_client):
"""Test AssumeRole validates required RoleArn parameter."""
with pytest.raises((ClientError, ParamValidationError)):
diff --git a/docs/services/sts.md b/docs/services/sts.md
index cfbf738fee..d3af514b6c 100644
--- a/docs/services/sts.md
+++ b/docs/services/sts.md
@@ -1,6 +1,6 @@
# STS
-**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
+**Protocol:** Query (XML), `POST http://localhost:4566/` with `Action=` parameter
## Supported Actions
@@ -22,13 +22,13 @@
## Trust Policy Enforcement
-By default `AssumeRole` succeeds for any caller. When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`,
-`AssumeRole` evaluates the target role's trust policy (`AssumeRolePolicyDocument`) against the caller
-and returns `AccessDenied` if it is not permitted. AWS principal forms are matched — `"*"`, an
-account id, an account-root ARN (`arn:aws:iam::<acct>:root`), and exact principal ARNs — and an
-explicit `Deny` always wins. Both `Action` and `NotAction` elements are honored when matching
-`sts:AssumeRole`. Roles that Floci has no record of stay permissive, so this only affects roles
-created through IAM with a real trust policy.
+`AssumeRole` and `AssumeRoleWithWebIdentity` require the target role to exist in IAM, returning `AccessDenied` (403)
+if it does not.
+
+When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, `AssumeRole` also evaluates the target role's trust policy
+(`AssumeRolePolicyDocument`) against the caller and returns `AccessDenied` if it is not permitted. AWS principal
+forms are matched: `"*"`, an account id, an account-root ARN (`arn:aws:iam::<acct>:root`), and exact principal ARNs;
+and an explicit `Deny` always wins. Both `Action` and `NotAction` elements are honored when matching `sts:AssumeRole`.
The caller is the account that owns the request's credentials, whether they sign the
`Authorization` header or a presigned query string: an IAM user's or a role session's access key
@@ -62,11 +62,11 @@ When the token's `iss` names a known Floci issuer, all of the following are enfo
- `iss` matches that issuer exactly
- `aud` contains `sts.amazonaws.com`
- `exp` / `nbf`, with 60s of clock-skew tolerance
-- the role's trust policy — `Principal.Federated` plus the `Condition` block, comparing `<oidcProvider>:sub` and `<oidcProvider>:aud` with exact, **case-sensitive** equality (`StringEquals`, `StringNotEquals`, `StringLike`, and `StringNotLike` are supported)
+- the role's trust policy: `Principal.Federated` plus the `Condition` block, comparing `<oidcProvider>:sub` and `<oidcProvider>:aud` with exact, **case-sensitive** equality (`StringEquals`, `StringNotEquals`, `StringLike`, and `StringNotLike` are supported)
-The response carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. A bad token returns `InvalidIdentityToken` (400), an expired one returns `ExpiredTokenException` (400), and a trust policy that does not permit the subject returns `AccessDenied` (403).
+The response carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. A bad token returns `InvalidIdentityToken` (400), an expired one returns `ExpiredTokenException` (400), and a role that does not exist or a trust policy that does not permit the subject returns `AccessDenied` (403).
-By default, tokens from an issuer Floci does not host, or tokens that are not parseable JWTs, are treated as opaque and accepted for compatibility with existing workflows. When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, those tokens return `InvalidIdentityToken` because Floci cannot verify a third-party provider's signature. See [EKS](eks.md) for the full IRSA walkthrough and the token-minting endpoint.
+By default, tokens from an issuer Floci does not host, or tokens that are not parseable JWTs, are treated as opaque and accepted for compatibility with existing workflows, provided the target role exists in IAM. When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, those tokens return `InvalidIdentityToken` because Floci cannot verify a third-party provider's signature. See [EKS](eks.md) for the full IRSA walkthrough and the token-minting endpoint.
## Examples
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 ba2a87a254..e4f89ecac0 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
@@ -2927,11 +2927,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return storage.scan(key -> true).stream();
}
- private static String normalizePath(String path) {
- if (path == null || path.isEmpty()) return "/";
+ static String normalizePath(String path) {
+ if (path == null || path.isEmpty()) {
+ return "/";
+ }
String p = path;
- if (!p.startsWith("/")) p = "/" + p;
- if (!p.endsWith("/")) p = p + "/";
+ if (!p.startsWith("/")) {
+ p = "/" + p;
+ }
+ if (!p.endsWith("/")) {
+ p = p + "/";
+ }
return p;
}
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 8c2d5fa2bd..42efacc2d0 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
@@ -131,7 +131,7 @@ public class StsQueryHandler {
return trustDenied;
}
- String sessionRoleArn = role != null ? role.getArn() : roleArn;
+ String sessionRoleArn = canonicalRoleArn(role, accountId, roleName);
String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
@@ -158,8 +158,8 @@ public class StsQueryHandler {
/**
* When IAM enforcement is enabled, denies AssumeRole if the target role's trust policy does not
- * permit the caller. Returns {@code null} to allow — enforcement disabled, the role is unknown
- * to Floci (permissive, backward-compatible), or the caller is permitted.
+ * permit the caller. Returns {@code null} to allow when enforcement is disabled or the caller is
+ * permitted. Roles absent from Floci are always denied.
*
* <p>The caller's account is the one the request was resolved to from its credentials, signed
* in the header or presigned in the query, which for an IAM user or a session is the account
@@ -170,9 +170,6 @@ public class StsQueryHandler {
*/
private Response enforceTrustPolicy(String roleArn, IamRole role, String roleAccountId,
MultivaluedMap<String, String> params) {
- if (!config.services().iam().enforcementEnabled() || role == null) {
- return null;
- }
String auth = IamEnforcementFilter.requestAuthorization(
headers == null ? null : headers.getHeaderString("Authorization"),
uriInfo == null ? null : uriInfo.getQueryParameters());
@@ -182,6 +179,16 @@ public class StsQueryHandler {
String callerArn = callerArns.map(IamService.CallerArns::callerArn)
.orElse(regionResolver.buildGlobalArn("iam", callerAccount, "root"));
String principalArn = callerArns.map(IamService.CallerArns::principalArn).orElse(callerArn);
+
+ if (role == null || !roleArnMatches(roleArn, role)) {
+ return AwsQueryResponse.error("AccessDenied",
+ "User: " + callerArn + " is not authorized to perform: sts:AssumeRole on resource: " + roleArn,
+ AwsNamespaces.STS, 403);
+ }
+ if (!config.services().iam().enforcementEnabled()) {
+ return null;
+ }
+
Map<String, List<String>> requestContext = IamConditionContextResolver.withGlobalContext(
null, roleArn, regionResolver.getRegion(), callerAccount, roleAccountId);
requestContext.put("sts:RoleSessionName", List.of(getParam(params, "RoleSessionName")));
@@ -198,6 +205,34 @@ public class StsQueryHandler {
AwsNamespaces.STS, 403);
}
+ private String canonicalRoleArn(IamRole role, String accountId, String roleName) {
+ if (role.getArn() != null && AwsArnUtils.isArn(role.getArn())) {
+ return role.getArn();
+ }
+ return regionResolver.buildGlobalArn("iam", accountId,
+ "role" + IamService.normalizePath(role.getPath()) + roleName);
+ }
+
+ static boolean roleArnMatches(String requestedRoleArn, IamRole role) {
+ if (requestedRoleArn == null || role == null || !AwsArnUtils.isArn(requestedRoleArn)) {
+ return false;
+ }
+ AwsArnUtils.Arn requested = AwsArnUtils.parse(requestedRoleArn);
+ if (!"iam".equals(requested.service())
+ || !requested.partition().matches(AwsArnUtils.PARTITION_REGEX)) {
+ return false;
+ }
+ String storedArn = role.getArn();
+ if (storedArn != null && AwsArnUtils.isArn(storedArn)) {
+ AwsArnUtils.Arn stored = AwsArnUtils.parse(storedArn);
+ return requested.accountId().equals(stored.accountId())
+ && requested.region().equals(stored.region())
+ && requested.resource().equals(stored.resource());
+ }
+ String expectedResource = "role" + IamService.normalizePath(role.getPath()) + role.getRoleName();
+ return requested.region().isEmpty() && requested.resource().equals(expectedResource);
+ }
+
private Response handleGetCallerIdentity(MultivaluedMap<String, String> params) {
String accountId = regionResolver.getAccountId();
String authorization = headers == null ? null : headers.getHeaderString("Authorization");
@@ -236,6 +271,10 @@ public class StsQueryHandler {
if (validation != null) {
return validation;
}
+ validation = validateIamRoleArn(getParam(params, "RoleArn"));
+ if (validation != null) {
+ return validation;
+ }
Response durationValidation = validateDurationSeconds(params, 900, 43200);
if (durationValidation != null) {
return durationValidation;
@@ -255,13 +294,20 @@ public class StsQueryHandler {
return outcome.denial();
}
VerifiedWebIdentity verified = outcome.verified();
+ IamRole role = outcome.role();
+ if (role == null) {
+ role = iamService.findRole(accountId, roleName).orElse(null);
+ if (role == null || !roleArnMatches(roleArn, role)) {
+ return accessDenied(roleArn);
+ }
+ }
String accessKeyId = "ASIA" + randomId(16);
String secretKey = randomSecret(40);
String sessionToken = randomSecret(200);
Instant expiration = Instant.now().plusSeconds(durationSeconds);
- String sessionRoleArn = iamService.findRole(accountId, roleName).map(IamRole::getArn).orElse(roleArn);
+ String sessionRoleArn = canonicalRoleArn(role, accountId, roleName);
String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
@@ -289,20 +335,39 @@ public class StsQueryHandler {
return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithWebIdentity", AwsNamespaces.STS, result)).build();
}
+ private Response validateIamRoleArn(String roleArn) {
+ if (!AwsArnUtils.isArn(roleArn)) {
+ return AwsQueryResponse.error("ValidationError", "RoleArn must be a valid IAM role ARN.",
+ AwsNamespaces.STS, 400);
+ }
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(roleArn);
+ boolean validRoleArn = arn.partition().matches(AwsArnUtils.PARTITION_REGEX)
+ && "iam".equals(arn.service())
+ && arn.region().isEmpty()
+ && arn.accountId().matches("[0-9]{12}")
+ && arn.resource().startsWith("role/")
+ && arn.resource().length() > "role/".length();
+ if (!validRoleArn) {
+ return AwsQueryResponse.error("ValidationError", "RoleArn must be a valid IAM role ARN.",
+ AwsNamespaces.STS, 400);
+ }
+ return null;
+ }
+
/** The claims of a token Floci issued and verified, used to fill the response accurately. */
private record VerifiedWebIdentity(String issuer, String subject, String audience) {}
- private record WebIdentityOutcome(VerifiedWebIdentity verified, Response denial) {
+ private record WebIdentityOutcome(VerifiedWebIdentity verified, IamRole role, Response denial) {
static WebIdentityOutcome unverifiable() {
- return new WebIdentityOutcome(null, null);
+ return new WebIdentityOutcome(null, null, null);
}
- static WebIdentityOutcome allow(VerifiedWebIdentity verified) {
- return new WebIdentityOutcome(verified, null);
+ static WebIdentityOutcome allow(VerifiedWebIdentity verified, IamRole role) {
+ return new WebIdentityOutcome(verified, role, null);
}
static WebIdentityOutcome deny(Response denial) {
- return new WebIdentityOutcome(null, denial);
+ return new WebIdentityOutcome(null, null, denial);
}
}
@@ -340,7 +405,7 @@ public class StsQueryHandler {
}
Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);
- if (role.isEmpty()) {
+ if (role.isEmpty() || !roleArnMatches(roleArn, role.get())) {
return WebIdentityOutcome.deny(accessDenied(roleArn));
}
@@ -362,7 +427,7 @@ public class StsQueryHandler {
// verify() already required the audience list to contain STS_AUDIENCE.
return WebIdentityOutcome.allow(
- new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE));
+ new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE), role.get());
}
/**
@@ -445,10 +510,11 @@ public class StsQueryHandler {
String accessKeyId = "ASIA" + randomId(16);
String secretKey = randomSecret(40);
String sessionToken = randomSecret(200);
- String assumedRoleArn = assumedRoleArn(role.getArn(), accountId, roleName, sessionName);
+ String sessionRoleArn = canonicalRoleArn(role, accountId, roleName);
+ String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
- iamService.registerSession(accessKeyId, secretKey, sessionToken, role.getArn(), expiration, null,
+ iamService.registerSession(accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, null,
callerAccountId, sessionName, assumedRoleId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
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
index a50869a7fd..03289ec781 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/AssumedRoleAccountRoutingIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AssumedRoleAccountRoutingIntegrationTest.java
@@ -39,6 +39,17 @@ class AssumedRoleAccountRoutingIntegrationTest {
void assumedRoleCredentialsRouteResourcesToTargetAccount() {
String tableName = "routing-" + UUID.randomUUID().toString().substring(0, 8);
+ given()
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", "CrossAccountAccess")
+ .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::" + ACCOUNT_A + ":root\"},\"Action\":\"sts:AssumeRole\"}]}")
+ .header("Authorization", auth(ACCOUNT_B, "iam"))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
// 1. Account A assumes a role in account B and receives temporary credentials.
String tempAccessKeyId = given()
.formParam("Action", "AssumeRole")
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAccountOwnershipIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAccountOwnershipIntegrationTest.java
index ac6c66c3e5..a373fd334f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAccountOwnershipIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAccountOwnershipIntegrationTest.java
@@ -110,6 +110,16 @@ class CloudFormationAccountOwnershipIntegrationTest {
createStack(ACCOUNT_1, US_EAST_1, "cfn-management-stack",
"{\"Resources\":{\"ManagementBucket\":{\"Type\":\"AWS::S3::Bucket\"}}}");
+ given()
+ .header("Authorization", auth(ACCOUNT_2, US_EAST_1, "iam"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", "cfn-member-deploy-role")
+ .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::" + ACCOUNT_1 + ":root\"},\"Action\":\"sts:AssumeRole\"}]}")
+ .when().post("/").then()
+ .statusCode(200);
+
String memberAccessKeyId = given()
.header("Authorization", auth(ACCOUNT_1, US_EAST_1, "sts"))
.contentType("application/x-www-form-urlencoded")
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java
index 06ded0a07c..e8d32936ad 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java
@@ -14,7 +14,7 @@ import static org.hamcrest.Matchers.startsWith;
/**
* Verifies that, with {@code iam.enforcement-enabled=true}, STS AssumeRole honors the target role's
* trust policy: a caller the trust policy permits succeeds; one it does not is denied; and a role
- * Floci does not know about stays permissive (backward-compatible).
+ * that does not exist is denied.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
@@ -34,12 +34,16 @@ class AssumeRoleTrustPolicyIntegrationTest {
}
private static void createRoleInB(String roleName) {
+ createRole(ACCOUNT_B, roleName, TRUST_ALLOW_A);
+ }
+
+ private static void createRole(String accountId, String roleName, String trustPolicyDocument) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
- .formParam("AssumeRolePolicyDocument", TRUST_ALLOW_A)
- .header("Authorization", auth(ACCOUNT_B, "iam"))
+ .formParam("AssumeRolePolicyDocument", trustPolicyDocument)
+ .header("Authorization", auth(accountId, "iam"))
.when().post("/")
.then().statusCode(200);
}
@@ -60,6 +64,70 @@ class AssumeRoleTrustPolicyIntegrationTest {
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA"));
}
+ @Test
+ void alternatePartitionArnKeepsTheStoredRolePartitionInSessionIdentity() {
+ String role = "trust-partition-" + UUID.randomUUID().toString().substring(0, 8);
+ createRoleInB(role);
+
+ String accessKeyId = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "AssumeRole")
+ .formParam("RoleArn", "arn:aws-cn:iam::" + ACCOUNT_B + ":role/" + role)
+ .formParam("RoleSessionName", "s")
+ .header("Authorization", auth(ACCOUNT_A, "sts"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA"))
+ .body("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn",
+ containsString("arn:aws:sts::" + ACCOUNT_B + ":assumed-role/" + role + "/s"))
+ .extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetCallerIdentity")
+ .header("Authorization", auth(accessKeyId, "sts"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",
+ containsString("arn:aws:sts::" + ACCOUNT_B + ":assumed-role/" + role + "/s"));
+ }
+
+ @Test
+ void requestedPartitionCannotChangeCallerPrincipalForLaterTrustChecks() {
+ String firstRole = "trust-source-" + UUID.randomUUID().toString().substring(0, 8);
+ String protectedRole = "trust-target-" + UUID.randomUUID().toString().substring(0, 8);
+ String sessionName = "partition-spoof";
+ createRoleInB(firstRole);
+
+ String forgedPrincipal = "arn:aws-cn:sts::" + ACCOUNT_B + ":assumed-role/" + firstRole + "/" + sessionName;
+ String targetTrust = "{\"Version\":\"2012-10-17\",\"Statement\":[{"
+ + "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"" + forgedPrincipal + "\"},"
+ + "\"Action\":\"sts:AssumeRole\"}]}";
+ createRole(ACCOUNT_C, protectedRole, targetTrust);
+
+ String accessKeyId = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "AssumeRole")
+ .formParam("RoleArn", "arn:aws-cn:iam::" + ACCOUNT_B + ":role/" + firstRole)
+ .formParam("RoleSessionName", sessionName)
+ .header("Authorization", auth(ACCOUNT_A, "sts"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn",
+ containsString("arn:aws:sts::" + ACCOUNT_B + ":assumed-role/" + firstRole + "/" + sessionName))
+ .extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "AssumeRole")
+ .formParam("RoleArn", "arn:aws:iam::" + ACCOUNT_C + ":role/" + protectedRole)
+ .formParam("RoleSessionName", "second-session")
+ .header("Authorization", auth(accessKeyId, "sts"))
+ .when().post("/")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
@Test
void unauthorizedCallerIsDenied() {
String role = "trust-deny-" + UUID.randomUUID().toString().substring(0, 8);
@@ -81,17 +149,18 @@ class AssumeRoleTrustPolicyIntegrationTest {
}
@Test
- void unknownRoleStaysPermissive() {
- // No role created — enforcement must not block roles Floci has never seen.
+ void unknownRoleIsDenied() {
+ String roleArn = "arn:aws:iam::" + ACCOUNT_B + ":role/never-created-"
+ + UUID.randomUUID().toString().substring(0, 8);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "AssumeRole")
- .formParam("RoleArn", "arn:aws:iam::" + ACCOUNT_B + ":role/never-created-"
- + UUID.randomUUID().toString().substring(0, 8))
+ .formParam("RoleArn", roleArn)
.formParam("RoleSessionName", "s")
.header("Authorization", auth(ACCOUNT_C, "sts"))
.when().post("/")
- .then().statusCode(200)
- .body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA"));
+ .then().statusCode(403)
+ .body(containsString("<Code>AccessDenied</Code>"))
+ .body(containsString("is not authorized to perform: sts:AssumeRole on resource: " + roleArn));
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
index 8418bcaf15..0a3569c34c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
@@ -25,6 +25,19 @@ class IamIntegrationTest {
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
+ private static void createRoleForAssume(String accessKeyId, String roleName) {
+ given()
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", roleName)
+ .formParam("AssumeRolePolicyDocument", TRUST_POLICY)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
private static final String POLICY_DOCUMENT =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
@@ -77,9 +90,10 @@ class IamIntegrationTest {
@Test
@Order(3)
void stsAssumeRole() {
+ createRoleForAssume("test", "StsAssumeTestRole");
given()
.formParam("Action", "AssumeRole")
- .formParam("RoleArn", "arn:aws:iam::000000000000:role/TestRole")
+ .formParam("RoleArn", "arn:aws:iam::000000000000:role/StsAssumeTestRole")
.formParam("RoleSessionName", "test-session")
.formParam("DurationSeconds", "3600")
.header("Authorization",
@@ -94,12 +108,13 @@ class IamIntegrationTest {
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken", notNullValue())
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.Expiration", notNullValue())
.body("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn",
- containsString("assumed-role/TestRole/test-session"));
+ containsString("assumed-role/StsAssumeTestRole/test-session"));
}
@Test
@Order(4)
void stsAssumeRoleHonoursTwelveDigitAccessKey() {
+ createRoleForAssume("123456789012", "TestRole");
given()
.formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::123456789012:role/TestRole")
@@ -118,6 +133,7 @@ class IamIntegrationTest {
@Test
@Order(6)
void stsAssumeRoleUsesAccountFromRoleArnForCrossAccount() {
+ createRoleForAssume("222222222222", "CrossAccountRole");
given()
.formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::222222222222:role/CrossAccountRole")
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 3ed58fc574..f9abab7e08 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
@@ -138,6 +138,20 @@ class IamServiceTest {
assertEquals(restored.getAssumedRoleId(), service.resolveCallerUserId(accessKeyId).orElseThrow());
}
+ @Test
+ void resolveCallerArnPreservesPartitionFromRoleArn() {
+ String accessKeyId = "ASIACHINASESSION";
+ InMemoryStorage<String, SessionCredential> sessions = new InMemoryStorage<>();
+ IamService service = iamService(false, new InMemoryStorage<>(), sessions);
+ service.registerSession(accessKeyId, "secret", "token",
+ "arn:aws-cn:iam::123456789012:role/ChinaRole", Instant.now().plusSeconds(3600),
+ null, "123456789012", "china-session",
+ "AROAEXAMPLE:china-session");
+
+ assertEquals("arn:aws-cn:sts::123456789012:assumed-role/ChinaRole/china-session",
+ service.resolveCallerArn(accessKeyId).orElseThrow());
+ }
+
@Test
void aSessionsCallerAndPrincipalArnsComeFromOneLookup() {
IamService service = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>());
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java
index ca9efba1a3..97f1af02bd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java
@@ -24,6 +24,7 @@ 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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -45,10 +46,21 @@ class StsQueryHandlerTest {
private static final Pattern ARN = Pattern.compile("<Arn>([^<]+)</Arn>");
private static StsQueryHandler newHandler() {
- return newHandler(new RegionResolver(REGION, "000000000000"));
+ IamRole role = new IamRole();
+ role.setRoleName("TestRole");
+ role.setArn("arn:aws:iam::000000000000:role/TestRole");
+ return newHandler(role);
+ }
+
+ private static StsQueryHandler newHandler(IamRole role) {
+ return newHandler(role, new RegionResolver(REGION, "000000000000"));
}
- private static StsQueryHandler newHandler(RegionResolver regionResolver) {
+ private static StsQueryHandler newHandlerForRegion(RegionResolver regionResolver) {
+ return newHandler(null, regionResolver);
+ }
+
+ private static StsQueryHandler newHandler(IamRole role, RegionResolver regionResolver) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
@@ -56,8 +68,11 @@ class StsQueryHandlerTest {
when(services.iam()).thenReturn(iam);
when(iam.enforcementEnabled()).thenReturn(false);
+ IamService iamService = mock(IamService.class);
+ when(iamService.findRole(anyString(), anyString())).thenReturn(Optional.ofNullable(role));
+
return new StsQueryHandler(
- mock(IamService.class),
+ iamService,
mock(AccountResolver.class),
regionResolver,
config,
@@ -92,6 +107,96 @@ class StsQueryHandlerTest {
assertNotEquals(extract(SESSION_TOKEN, firstBody), extract(SESSION_TOKEN, secondBody));
}
+ @Test
+ void assumeRoleDeniesRoleThatDoesNotExist() {
+ StsQueryHandler handler = newHandler(null);
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/definitely-does-not-exist");
+ params.putSingle("RoleSessionName", "test-session");
+
+ Response response = handler.handle("AssumeRole", params);
+
+ assertEquals(403, response.getStatus());
+ assertTrue(((String) response.getEntity()).contains("<Code>AccessDenied</Code>"));
+ }
+
+ @Test
+ void assumeRoleDeniesRoleWhenPathDiffers() {
+ IamRole role = new IamRole();
+ role.setRoleName("TestRole");
+ role.setPath("/team/");
+ role.setArn("arn:aws:iam::000000000000:role/team/TestRole");
+ StsQueryHandler handler = newHandler(role);
+
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/other/TestRole");
+ params.putSingle("RoleSessionName", "test-session");
+
+ Response response = handler.handle("AssumeRole", params);
+
+ assertEquals(403, response.getStatus());
+ assertTrue(((String) response.getEntity()).contains("<Code>AccessDenied</Code>"));
+ }
+
+ @Test
+ void assumeRoleAllowsPartitionCorrectRoleArn() {
+ IamRole role = new IamRole();
+ role.setRoleName("TestRole");
+ role.setPath("/");
+ role.setArn("arn:aws:iam::000000000000:role/TestRole");
+ StsQueryHandler handler = newHandler(role);
+
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws-cn:iam::000000000000:role/TestRole");
+ params.putSingle("RoleSessionName", "test-session");
+
+ Response response = handler.handle("AssumeRole", params);
+
+ assertEquals(200, response.getStatus(), (String) response.getEntity());
+ String body = (String) response.getEntity();
+ assertTrue(body.contains("<Arn>arn:aws:sts::000000000000:assumed-role/TestRole/test-session</Arn>"),
+ "AssumedRoleUser Arn must use the stored role's partition");
+ }
+
+ @Test
+ void assumeRoleAllowsGovCloudPartitionRoleArn() {
+ IamRole role = new IamRole();
+ role.setRoleName("TestRole");
+ role.setPath("/");
+ role.setArn("arn:aws:iam::000000000000:role/TestRole");
+ StsQueryHandler handler = newHandler(role);
+
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws-us-gov:iam::000000000000:role/TestRole");
+ params.putSingle("RoleSessionName", "test-session");
+
+ Response response = handler.handle("AssumeRole", params);
+
+ assertEquals(200, response.getStatus(), (String) response.getEntity());
+ String body = (String) response.getEntity();
+ assertTrue(body.contains("<Arn>arn:aws:sts::000000000000:assumed-role/TestRole/test-session</Arn>"),
+ "AssumedRoleUser Arn must use the stored role's partition");
+ }
+
+ @Test
+ void roleArnMatchesValidatesPartitionsAndPaths() {
+ IamRole role = new IamRole();
+ role.setRoleName("TestRole");
+ role.setPath("/team/");
+ role.setArn("arn:aws:iam::000000000000:role/team/TestRole");
+
+ assertTrue(StsQueryHandler.roleArnMatches("arn:aws:iam::000000000000:role/team/TestRole", role));
+ assertTrue(StsQueryHandler.roleArnMatches("arn:aws-cn:iam::000000000000:role/team/TestRole", role));
+ assertTrue(StsQueryHandler.roleArnMatches("arn:aws-us-gov:iam::000000000000:role/team/TestRole", role));
+
+ assertFalse(StsQueryHandler.roleArnMatches("arn:aws:iam::000000000000:role/other/TestRole", role));
+ assertFalse(StsQueryHandler.roleArnMatches("arn:aws:iam::111111111111:role/team/TestRole", role));
+ assertFalse(StsQueryHandler.roleArnMatches("arn:aws:iam:us-east-1:000000000000:role/team/TestRole", role));
+ assertFalse(StsQueryHandler.roleArnMatches("arn:aws:s3:::bucket", role));
+ assertFalse(StsQueryHandler.roleArnMatches("not-an-arn", role));
+ assertFalse(StsQueryHandler.roleArnMatches(null, role));
+ }
+
@ParameterizedTest
@ValueSource(strings = {"900", "43200"})
void assumeRoleAcceptsDurationSecondsAtTheLimits(String durationSeconds) {
@@ -228,6 +333,64 @@ class StsQueryHandlerTest {
assertTrue(body.contains("greater than or equal to 900"), body);
}
+ @Test
+ void assumeRoleWithWebIdentityRejectsMalformedRoleArnWhenTokenCannotBeVerified() {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "not-an-arn");
+ params.putSingle("RoleSessionName", "test-session");
+ params.putSingle("WebIdentityToken", "opaque-token");
+
+ Response response = newHandler(null).handle("AssumeRoleWithWebIdentity", params);
+
+ assertEquals(400, response.getStatus());
+ assertTrue(((String) response.getEntity()).contains("<Code>ValidationError</Code>"));
+ }
+
+ @Test
+ void assumeRoleWithWebIdentityRejectsNonexistentRoleWhenTokenCannotBeVerified() {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/NonexistentRole");
+ params.putSingle("RoleSessionName", "test-session");
+ params.putSingle("WebIdentityToken", "opaque-token");
+
+ Response response = newHandler(null).handle("AssumeRoleWithWebIdentity", params);
+
+ assertEquals(403, response.getStatus());
+ String body = (String) response.getEntity();
+ assertTrue(body.contains("<Code>AccessDenied</Code>"), body);
+ assertTrue(body.contains("Not authorized to perform sts:AssumeRoleWithWebIdentity on resource: "
+ + "arn:aws:iam::000000000000:role/NonexistentRole"), body);
+ }
+
+ @Test
+ void assumeRoleWithWebIdentitySucceedsWhenRoleExistsAndTokenCannotBeVerified() {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/TestRole");
+ params.putSingle("RoleSessionName", "test-session");
+ params.putSingle("WebIdentityToken", "opaque-token");
+
+ Response response = newHandler().handle("AssumeRoleWithWebIdentity", params);
+
+ assertEquals(200, response.getStatus());
+ String body = (String) response.getEntity();
+ assertTrue(body.contains("<AssumeRoleWithWebIdentityResult>"), body);
+ assertTrue(body.contains("<Arn>arn:aws:sts::000000000000:assumed-role/TestRole/test-session</Arn>"), body);
+ }
+
+ @Test
+ void assumeRoleWithWebIdentityRejectsRoleMismatchWhenTokenCannotBeVerified() {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws:iam::111111111111:role/TestRole");
+ params.putSingle("RoleSessionName", "test-session");
+ params.putSingle("WebIdentityToken", "opaque-token");
+
+ Response response = newHandler().handle("AssumeRoleWithWebIdentity", params);
+
+ assertEquals(403, response.getStatus());
+ String body = (String) response.getEntity();
+ assertTrue(body.contains("<Code>AccessDenied</Code>"), body);
+ }
+
@Test
void assumeRoleWithSAMLRejectsDurationSecondsBelowMinimum() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
@@ -248,7 +411,7 @@ class StsQueryHandlerTest {
@ParameterizedTest
@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
void getCallerIdentityMintsTheRootArnInTheDeploymentsPartition(PartitionCase partitionCase) {
- Response response = newHandler(PartitionMatrix.regionResolver(partitionCase))
+ Response response = newHandlerForRegion(PartitionMatrix.regionResolver(partitionCase))
.handle("GetCallerIdentity", new MultivaluedHashMap<>());
assertEquals(200, response.getStatus());
@@ -263,7 +426,7 @@ class StsQueryHandlerTest {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("Name", "bob");
- Response response = newHandler(PartitionMatrix.regionResolver(partitionCase))
+ Response response = newHandlerForRegion(PartitionMatrix.regionResolver(partitionCase))
.handle("GetFederationToken", params);
assertEquals(200, response.getStatus());
@@ -327,8 +490,11 @@ class StsQueryHandlerTest {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/commercial-role");
params.putSingle("RoleSessionName", "s");
+ IamRole role = new IamRole();
+ role.setRoleName("commercial-role");
+ role.setArn("arn:aws:iam::000000000000:role/commercial-role");
- Response response = newHandler(new RegionResolver("cn-north-1", "000000000000"))
+ Response response = newHandler(role, new RegionResolver("cn-north-1", "000000000000"))
.handle("AssumeRole", params);
assertEquals(200, response.getStatus());