fix(sts): evaluate GetSessionToken and GetFederationToken sessions as the user that minted them (#5081)

Under IAM enforcement, credentials from the two STS operations that mint a
session from a long-term key were evaluated as the wrong identity:

- A GetSessionToken session was stored with no role ARN, which
  resolveCallerContext answered with null, and the enforcement filter lets a
  known credential it cannot map to policies through. A user allowed only
  sts:GetSessionToken got credentials that passed every check, IAM calls
  included, and since the session had no caller ARN, AssumeRole took it for
  the account root and let it assume any role whose trust policy names the
  account. AppSync's IAM authorization and RDS IAM database authentication
  also read a null context as allowed, so they let these sessions through too.
- A GetFederationToken session was stored with the federated user's ARN where a
  role session keeps its role's, and its permissions were read from the role
  whose name followed the last slash. A user allowed only
  sts:GetFederationToken that federated under an existing role's name got that
  role's permissions; any other name got none, even with a session policy.

The STS API Reference says GetSessionToken credentials "have the same
permissions as the IAM user", and that a GetFederationToken session with no
session policy "has no permissions", and otherwise the intersection of "the IAM
user policies and the session policies". Both handlers now record the identity
whose key signed the request. An active key of a user in the request's account
names that user, by ARN and unique ID. A key no account holds, the legacy test
key or the account id among them, names the account root, which is how Floci
already treats such a key.

A GetSessionToken session is evaluated as that user, policies and boundary
included, or as the root, whose context the filter still bounds by the
account's service control policies. A federated session is evaluated as that
user intersected with its session policy. Without one it has no permissions of
its own, but keeps the Deny statements of its user's policies and boundary: a
resource policy naming the federated user grants to the session past implicit
denies, not past explicit ones (IAM User Guide, "Resource-based policies for AWS
STS federated user principal sessions"). Whatever its policies allow, a
federated session cannot call any IAM operation, nor any STS operation except
GetCallerIdentity (STS API Reference, GetFederationToken), so its context
always carries an explicit Deny for iam:* and sts:*; the filter answers
GetCallerIdentity before reading any policy.

A session whose issuer is gone is no credential at all, refused like an unknown
access key, so neither a resource policy nor S3's fallback to the account root
acts on its behalf. That covers a session minted with any other key IAM holds
(another session's, which AWS does not accept here, or an inactive key or
another account's, which account routing can land in the default account), a
session whose user was deleted and recreated under the same name, and one
stored before the issuer was recorded.

The caller identity follows: a GetSessionToken session's caller and principal
ARN are its user's, and a federated session's are its federated-user ARN, with
account:name as its user ID, as GetCallerIdentity reports for a federated user.

The unit test that pinned the GetSessionToken bypass now checks that a session
stored without an issuer is no credential; unit tests cover each kind of
issuer, the deny-only context of a federated session without a policy, and
that the issuer survives persistence. Integration tests (IAM and S3
enforcement, real SigV4) cover the role-name federation, the intersection, the
no-policy session, the GetSessionToken session and its AssumeRole, a
bucket-policy Deny keyed on the user's aws:PrincipalArn, both kinds of session
staying within the user's permissions boundary, a session of a recreated user
under a bucket policy granting everyone, and a bucket policy naming a federated
user against its user's explicit Deny, and a federated session refused IAM
and AssumeRole although both its user and session policy allow them; the SCP integration test now also checks
a root-minted session. All of them fail on main. Tests that built an STS
session credential as a role-less session with no issuer, a shape Floci no
longer creates, now build one the account root minted, or a presigned-URL
session, as production does.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-05 17:12:00 -05:00
1 parent 583de3010c
commit a3118eb42b
11 files changed
+838 -41

No files matched your search

@@ -116,10 +116,10 @@ class IamServicePersistenceTest {
void expiredTemporarySessionsAreRemovedAfterRestart(@TempDir Path dir) {
Instant now = Instant.now();
IamService first = newService(dir);
first.registerSessionForAccount("000000000000", "ASIAEXPIREDPRESIGN", "expired-secret",
"expired-token", null, now.minusSeconds(1), null);
first.registerSessionForAccount("000000000000", "ASIAVALIDPRESIGN", "valid-secret",
"valid-token", null, now.plusSeconds(3600), null);
first.registerPresignedUrlSession("000000000000", "ASIAEXPIREDPRESIGN", "expired-secret",
"expired-token", now.minusSeconds(1), null, "s3:GetObject", "arn:aws:s3:::bucket/key");
first.registerPresignedUrlSession("000000000000", "ASIAVALIDPRESIGN", "valid-secret",
"valid-token", now.plusSeconds(3600), null, "s3:GetObject", "arn:aws:s3:::bucket/key");
IamService restarted = newService(dir);
assertEquals(1, restarted.sweepExpiredSessions(now));
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -15,10 +16,10 @@ import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.LoginProfile;
import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
@@ -174,6 +175,213 @@ class IamServiceTest {
assertTrue(service.resolveCallerArns("ASIAEXPIREDSESSION").isEmpty());
}
private static final String READ_S3 = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""";
private static final String ALL_S3 = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}""";
/** The Deny every federated session carries: no IAM operation, and no STS operation but GetCallerIdentity. */
private static void assertFederatedUserLimits(String policy) throws Exception {
JsonNode statement = new ObjectMapper().readTree(policy).path("Statement").get(0);
assertEquals("Deny", statement.path("Effect").asText());
assertEquals("[\"iam:*\",\"sts:*\"]", statement.path("Action").toString());
}
/** A session that is no credential at all: unknown to every lookup, so nothing can act on its behalf. */
private static void assertNotACredential(IamService service, String accessKeyId) {
assertFalse(service.isKnownAccessKey(accessKeyId));
assertNull(service.resolveCallerContext(accessKeyId));
assertTrue(service.resolveCallerArns(accessKeyId).isEmpty());
assertTrue(service.findSecretKey(accessKeyId, "token").isEmpty());
}
@Test
void aSessionTokenActsAsTheUserWhoseKeyMintedIt() {
IamService service = iamService(false);
IamUser alice = service.createUser("alice", "/team/");
service.putUserPolicy("alice", "read", READ_S3);
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
service.registerIssuedSession("ASIASESSIONTOKEN", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000", aliceKey);
CallerContext context = service.resolveCallerContext("ASIASESSIONTOKEN");
assertEquals(List.of(READ_S3), context.identityPolicies());
assertNull(context.sessionPolicyDocument());
assertEquals(new IamService.CallerArns(alice.getArn(), alice.getArn()),
service.resolveCallerArns("ASIASESSIONTOKEN").orElseThrow());
assertEquals(alice.getUserId(), service.resolveCallerUserId("ASIASESSIONTOKEN", "token").orElseThrow());
}
@Test
void aSessionTokenTheAccountRootMintedActsAsTheRoot() {
IamService service = iamService(false);
service.registerIssuedSession("ASIAROOTSESSION", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000", "000000000000");
// Allowed everything, as the root is, but through a context the filter bounds by the
// account's SCPs, rather than the null that lets a credential through unevaluated.
CallerContext context = service.resolveCallerContext("ASIAROOTSESSION");
assertEquals(1, context.identityPolicies().size());
assertEquals(new IamService.CallerArns("arn:aws:iam::000000000000:root", "arn:aws:iam::000000000000:root"),
service.resolveCallerArns("ASIAROOTSESSION").orElseThrow());
}
@Test
void aSessionTokenMintedWithAKeyIamDoesNotKnowActsAsTheRoot() {
IamService service = iamService(false);
service.registerIssuedSession("ASIAFROMUNKNOWNKEY", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000", "AKIAIOSFODNN7EXAMPLE");
// Floci treats a key IAM does not know as the account root, and the session it mints the same.
assertNull(service.resolveCallerContext("AKIAIOSFODNN7EXAMPLE"));
assertEquals(1, service.resolveCallerContext("ASIAFROMUNKNOWNKEY").identityPolicies().size());
assertEquals("arn:aws:iam::000000000000:root",
service.resolveCallerArns("ASIAFROMUNKNOWNKEY").orElseThrow().callerArn());
}
@Test
void aSessionTokenMintedWithAnotherSessionsKeyIsNoCredential() {
IamService service = iamService(false);
service.createRole("Worker", "/", "{}", null, 3600, null);
service.putRolePolicy("Worker", "all", ALL_S3);
service.registerSession("ASIAROLESESSION", "secret", "token",
"arn:aws:iam::000000000000:role/Worker", Instant.now().plusSeconds(3600), null,
"000000000000", "s", "AROAWORKER:s");
// GetSessionToken and GetFederationToken take long-term credentials only.
service.registerIssuedSession("ASIAFROMSESSION", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000", "ASIAROLESESSION");
assertNotACredential(service, "ASIAFROMSESSION");
}
@Test
void aSessionTokenMintedWithADeactivatedKeyIsNoCredential() {
IamService service = iamService(false);
service.createUser("alice", "/");
service.putUserPolicy("alice", "all", ALL_S3);
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
service.updateAccessKey("alice", aliceKey, "Inactive");
service.registerIssuedSession("ASIAFROMINACTIVEKEY", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000", aliceKey);
assertNotACredential(service, "ASIAFROMINACTIVEKEY");
}
@Test
void aSessionTokenMintedWithAnotherAccountsKeyIsNoCredential() {
// A key IAM holds in another account is not one it does not know: it does not stand for this
// account's root, the way a key no account holds does.
AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), null, "000000000000");
accessKeys.putForAccount("111122223333", "AKIAFOREIGNEXAMPLE",
new AccessKey("AKIAFOREIGNEXAMPLE", "secret", "worker"));
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
service.registerIssuedSession("ASIAFROMFOREIGNKEY", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000", "AKIAFOREIGNEXAMPLE");
assertNotACredential(service, "ASIAFROMFOREIGNKEY");
}
@Test
void aSessionsIssuerSurvivesPersistence() throws Exception {
SessionCredential session = new SessionCredential("ASIAPERSISTED", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000");
session.setIssuerArn("arn:aws:iam::000000000000:user/alice");
session.setIssuerUserId("AIDAALICE");
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
SessionCredential restored = mapper.readValue(mapper.writeValueAsBytes(session), SessionCredential.class);
assertEquals("arn:aws:iam::000000000000:user/alice", restored.getIssuerArn());
assertEquals("AIDAALICE", restored.getIssuerUserId());
}
@Test
void aSessionTokenOfAUserRecreatedUnderTheSameNameIsNoCredential() {
IamService service = iamService(false);
service.createUser("alice", "/");
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
service.registerIssuedSession("ASIASESSIONTOKEN", "secret", "token", null,
Instant.now().plusSeconds(3600), null, "000000000000", aliceKey);
service.deleteAccessKey("alice", aliceKey);
service.deleteUser("alice");
service.createUser("alice", "/");
service.putUserPolicy("alice", "all", ALL_S3);
assertNotACredential(service, "ASIASESSIONTOKEN");
}
@Test
void aFederatedSessionGetsItsUsersPermissionsOnlyThroughItsSessionPolicyAndNeverARoles() throws Exception {
IamService service = iamService(false);
service.createUser("alice", "/");
service.putUserPolicy("alice", "read", READ_S3);
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
// A role with the federated user's name is not the federated user.
service.createRole("Bob", "/", "{}", null, 3600, null);
service.putRolePolicy("Bob", "all", ALL_S3);
String federatedArn = "arn:aws:sts::000000000000:federated-user/Bob";
service.registerIssuedSession("ASIAWITHPOLICY", "secret", "token", federatedArn,
Instant.now().plusSeconds(3600), ALL_S3, "000000000000", aliceKey);
CallerContext withPolicy = service.resolveCallerContext("ASIAWITHPOLICY");
assertEquals(2, withPolicy.identityPolicies().size());
assertEquals(READ_S3, withPolicy.identityPolicies().getFirst());
assertFederatedUserLimits(withPolicy.identityPolicies().getLast());
assertEquals(ALL_S3, withPolicy.sessionPolicyDocument());
assertEquals(new IamService.CallerArns(federatedArn, federatedArn),
service.resolveCallerArns("ASIAWITHPOLICY").orElseThrow());
assertEquals("000000000000:Bob", service.resolveCallerUserId("ASIAWITHPOLICY", "token").orElseThrow());
}
@Test
void aFederatedSessionWithoutASessionPolicyKeepsOnlyItsUsersExplicitDenies() throws Exception {
IamService service = iamService(false);
service.createUser("alice", "/");
service.putUserPolicy("alice", "mixed", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:*","Resource":"*"},
{"Effect":"Deny","Action":"s3:DeleteObject","Resource":"*"}]}""");
String boundaryArn = service.createPolicy("bound", "/", null, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:*","Resource":"*"},
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}]}""", null).getArn();
service.putUserPermissionsBoundary("alice", boundaryArn);
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
service.registerIssuedSession("ASIAWITHOUTPOLICY", "secret", "token",
"arn:aws:sts::000000000000:federated-user/Bob", Instant.now().plusSeconds(3600), null,
"000000000000", aliceKey);
// No permissions of its own (STS API Reference, GetFederationToken), but its user's explicit
// denies, from its policies and its boundary, still apply to what a resource policy grants it.
CallerContext context = service.resolveCallerContext("ASIAWITHOUTPOLICY");
assertEquals(2, context.identityPolicies().size());
assertFederatedUserLimits(context.identityPolicies().getLast());
JsonNode statements = new ObjectMapper().readTree(context.identityPolicies().getFirst()).path("Statement");
assertEquals(2, statements.size());
for (JsonNode statement : statements) {
assertEquals("Deny", statement.path("Effect").asText());
}
assertEquals("s3:DeleteObject", statements.get(0).path("Action").asText());
assertEquals("s3:PutObject", statements.get(1).path("Action").asText());
assertNull(context.sessionPolicyDocument());
assertNull(context.boundaryPolicyDocument());
}
@Test
void aFederatedSessionStoredWithoutItsIssuerIsNoCredential() {
IamService service = iamService(false);
service.createRole("Bob", "/", "{}", null, 3600, null);
service.putRolePolicy("Bob", "all", ALL_S3);
// How sessions were stored before the issuer was recorded.
service.registerSession("ASIALEGACYFEDERATED", "secret", "token",
"arn:aws:sts::000000000000:federated-user/Bob", Instant.now().plusSeconds(3600), ALL_S3,
"000000000000");
assertNotACredential(service, "ASIALEGACYFEDERATED");
}
@Test
void ec2SessionMarkerSurvivesPersistenceAndExpiredCredentialsCannotAuthenticate() throws Exception {
SessionCredential expired = new SessionCredential("ASIAEXPIREDEC2", "secret", "token",
@@ -1212,7 +1420,9 @@ class IamServiceTest {
}
@Test
void getSessionTokenStyleSessionBypassesEnforcementResolution() {
void aSessionWithNoRoleAndNoRecordedIssuerIsNoCredential() {
// How GetSessionToken stored its sessions before it recorded the key that minted them. Such
// a session used to bypass enforcement altogether.
iamService.registerSession(
"ASIAIOSFODNN7EXAMPLE",
"temporary-secret",
@@ -1221,6 +1431,7 @@ class IamServiceTest {
null
);
assertFalse(iamService.isKnownAccessKey("ASIAIOSFODNN7EXAMPLE"));
assertNull(iamService.resolveCallerContext("ASIAIOSFODNN7EXAMPLE"));
assertNull(iamService.resolveCallerPolicies("ASIAIOSFODNN7EXAMPLE"));
}
@@ -1228,13 +1439,15 @@ class IamServiceTest {
@Test
void findSecretKeyRequiresTheTemporaryCredentialSessionToken() {
String accessKeyId = "ASIASESSIONTOKENMATCH";
iamService.registerSession(
iamService.registerIssuedSession(
accessKeyId,
"temporary-secret",
"session-token",
null,
Instant.now().plusSeconds(3600),
null
null,
"000000000000",
"000000000000"
);
assertEquals("temporary-secret", iamService.findSecretKey(accessKeyId, "session-token").orElseThrow());
@@ -1263,12 +1476,15 @@ class IamServiceTest {
@Test
void resolveAccountIdFallsBackToOriginAccountWhenNoRoleArn() {
iamService.registerSession(
// A GetSessionToken session the account's root minted.
iamService.registerIssuedSession(
"ASIASESSIONTOKEN",
"temp-secret",
"token",
null,
Instant.now().plusSeconds(3600),
null,
"111122223333",
"111122223333"
);
@@ -86,6 +86,21 @@ class ScpEnforcementLeaveOrganizationIntegrationTest {
org(memberId, "DescribeOrganization", "{}")
.then()
.statusCode(200);
// A GetSessionToken session the member's root minted is bounded by the same SCP.
String sessionKey = given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + memberId + "/20260629/" + REGION
+ "/sts/aws4_request, SignedHeaders=host, Signature=abc")
.formParam("Action", "GetSessionToken")
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId");
org(sessionKey, "LeaveOrganization", "{}")
.then()
.statusCode(400)
.body(containsString("AccessDeniedException"));
}
private static Response org(String account, String action, String body) {
@@ -0,0 +1,325 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.S3IamEnforcementProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Under IAM enforcement, credentials from GetSessionToken and GetFederationToken carry the
* permissions of the IAM user whose key minted them (STS API Reference, GetSessionToken and
* GetFederationToken, "Permissions"): never a role's, and never more than the user's own.
*/
@QuarkusTest
@TestProfile(S3IamEnforcementProfile.class)
class StsIssuedSessionEnforcementIntegrationTest {
private static final String ACCOUNT = "222233334444";
private static final String ALL_S3 = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}""";
@Test
void aFederatedUserNamedLikeARoleDoesNotGetTheRolesPermissions() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = bucketWithObject("sts-fed-role-" + suffix);
String role = "Admin" + suffix;
iam("CreateRole", "RoleName", role, "AssumeRolePolicyDocument", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""");
iam("PutRolePolicy", "RoleName", role, "PolicyName", "s3", "PolicyDocument", ALL_S3);
S3RequestSigner user = userWithPolicy("broker-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"sts:GetFederationToken","Resource":"*"}]}""");
// The user may not read the object, so neither may a session it mints, whatever its name.
readObject(user, bucket, 403);
readObject(federate(user, role, null), bucket, 403);
readObject(federate(user, role, ALL_S3), bucket, 403);
}
@Test
void aFederatedSessionGetsTheIntersectionOfItsUserAndItsSessionPolicy() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = bucketWithObject("sts-fed-scope-" + suffix);
S3RequestSigner user = userWithPolicy("reader-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","sts:GetFederationToken"],"Resource":"*"}]}""");
S3RequestSigner scoped = federate(user, "Bob" + suffix, ALL_S3);
readObject(scoped, bucket, 200);
// The session policy allows s3:PutObject, the user does not.
writeObject(scoped, bucket, 403);
// Without a session policy the session has no permissions.
readObject(federate(user, "Carol" + suffix, null), bucket, 403);
given().filter(scoped).formParam("Action", "GetCallerIdentity").when().post("/")
.then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",
equalTo("arn:aws:sts::" + ACCOUNT + ":federated-user/Bob" + suffix))
.body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId",
equalTo(ACCOUNT + ":Bob" + suffix));
}
@Test
void sessionTokenCredentialsActAsTheUserThatMintedThem() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = bucketWithObject("sts-session-" + suffix);
S3RequestSigner tokenOnly = userWithPolicy("token-only-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"sts:GetSessionToken","Resource":"*"}]}""");
S3RequestSigner reader = userWithPolicy("token-reader-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","sts:GetSessionToken"],"Resource":"*"}]}""");
// A session of a user allowed nothing else is allowed nothing else.
S3RequestSigner tokenOnlySession = sessionToken(tokenOnly);
readObject(tokenOnlySession, bucket, 403);
writeObject(tokenOnlySession, bucket, 403);
given().filter(tokenOnlySession).formParam("Action", "CreateUser").formParam("UserName", "made-" + suffix)
.when().post("/").then().statusCode(403);
// Nor can it assume a role the user may not assume, even one whose trust policy names the account.
String role = "Target" + suffix;
iam("CreateRole", "RoleName", role, "AssumeRolePolicyDocument", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}""".formatted(ACCOUNT));
iam("PutRolePolicy", "RoleName", role, "PolicyName", "s3", "PolicyDocument", ALL_S3);
given().filter(tokenOnlySession).formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::" + ACCOUNT + ":role/" + role).formParam("RoleSessionName", "s")
.when().post("/").then().statusCode(403);
S3RequestSigner readerSession = sessionToken(reader);
readObject(readerSession, bucket, 200);
writeObject(readerSession, bucket, 403);
given().filter(readerSession).formParam("Action", "GetCallerIdentity").when().post("/")
.then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",
equalTo("arn:aws:iam::" + ACCOUNT + ":user/token-reader-" + suffix));
}
@Test
void bothKindsOfSessionStayWithinTheUsersPermissionsBoundary() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = bucketWithObject("sts-boundary-" + suffix);
String userName = "bounded-" + suffix;
S3RequestSigner user = userWithPolicy(userName, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:*","sts:*"],"Resource":"*"}]}""");
String boundaryArn = given().formParam("Action", "CreatePolicy").formParam("PolicyName", "read-only-" + suffix)
.formParam("PolicyDocument", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["s3:GetObject","sts:GetSessionToken","sts:GetFederationToken"],"Resource":"*"}]}""")
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/")
.then().statusCode(200).extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
iam("PutUserPermissionsBoundary", "UserName", userName, "PermissionsBoundary", boundaryArn);
// The boundary allows reading, not writing, so neither the user nor its sessions may write.
writeObject(user, bucket, 403);
S3RequestSigner session = sessionToken(user);
readObject(session, bucket, 200);
writeObject(session, bucket, 403);
S3RequestSigner federated = federate(user, "Dana" + suffix, ALL_S3);
readObject(federated, bucket, 200);
writeObject(federated, bucket, 403);
}
@Test
void aSessionTokensPrincipalArnIsItsUsersArn() {
// A bucket-policy Deny keyed on the user's aws:PrincipalArn applies to its sessions too.
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "sts-session-arn-" + suffix;
S3RequestSigner admin = userWithPolicy("admin-" + bucket, ALL_S3);
given().filter(admin).when().put("/" + bucket).then().statusCode(200);
given().filter(admin).contentType("text/plain").body("payload")
.when().put("/" + bucket + "/o.txt").then().statusCode(200);
String userName = "denied-reader-" + suffix;
S3RequestSigner user = userWithPolicy(userName, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","sts:GetSessionToken"],"Resource":"*"}]}""");
S3RequestSigner session = sessionToken(user);
readObject(session, bucket, 200);
given().filter(admin).contentType("application/json").body("""
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::%s/*",
"Condition":{"ArnEquals":{"aws:PrincipalArn":"arn:aws:iam::%s:user/%s"}}}]}"""
.formatted(bucket, ACCOUNT, userName))
.when().put("/" + bucket + "?policy").then().statusCode(200);
readObject(user, bucket, 403);
readObject(session, bucket, 403);
}
@Test
void aSessionWhoseUserWasRecreatedIsNoCredential() {
// A session of a user deleted and recreated under its name is not that user's, and is no
// credential at all: not even a bucket policy granting everyone lets it in as a principal.
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "sts-orphan-" + suffix;
S3RequestSigner admin = userWithPolicy("admin-" + bucket, ALL_S3);
given().filter(admin).when().put("/" + bucket).then().statusCode(200);
given().filter(admin).contentType("text/plain").body("payload")
.when().put("/" + bucket + "/o.txt").then().statusCode(200);
String userName = "recreated-" + suffix;
iam("CreateUser", "UserName", userName);
iam("PutUserPolicy", "UserName", userName, "PolicyName", "inline", "PolicyDocument", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:GetSessionToken","Resource":"*"}]}""");
ExtractableResponse<Response> key = given().formParam("Action", "CreateAccessKey").formParam("UserName", userName)
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200).extract();
String accessKeyId = key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
S3RequestSigner session = sessionToken(S3RequestSigner.signedAs(accessKeyId,
key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey")));
iam("DeleteAccessKey", "UserName", userName, "AccessKeyId", accessKeyId);
iam("DeleteUserPolicy", "UserName", userName, "PolicyName", "inline");
iam("DeleteUser", "UserName", userName);
iam("CreateUser", "UserName", userName);
given().filter(admin).contentType("application/json").body("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*",
"Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}""".formatted(bucket))
.when().put("/" + bucket + "?policy").then().statusCode(200);
given().when().get("/" + bucket + "/o.txt").then().statusCode(200);
readObject(session, bucket, 403);
}
@Test
void aBucketPolicyNamingAFederatedUserCannotOverrideItsUsersExplicitDeny() {
// A grant naming the federated user reaches a session with no session policy, past implicit
// denies, but an explicit Deny in its user's policies still wins (IAM User Guide,
// "Resource-based policies for AWS STS federated user principal sessions").
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "sts-fed-deny-" + suffix;
S3RequestSigner admin = userWithPolicy("admin-" + bucket, ALL_S3);
given().filter(admin).when().put("/" + bucket).then().statusCode(200);
given().filter(admin).contentType("text/plain").body("payload")
.when().put("/" + bucket + "/o.txt").then().statusCode(200);
S3RequestSigner broker = userWithPolicy("broker-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"sts:GetFederationToken","Resource":"*"}]}""");
S3RequestSigner denier = userWithPolicy("denier-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"sts:GetFederationToken","Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject","Resource":"*"}]}""");
given().filter(admin).contentType("application/json").body("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"AWS":["arn:aws:sts::%1$s:federated-user/Granted%2$s",
"arn:aws:sts::%1$s:federated-user/Denied%2$s"]},
"Action":"s3:GetObject","Resource":"arn:aws:s3:::%3$s/*"}]}""".formatted(ACCOUNT, suffix, bucket))
.when().put("/" + bucket + "?policy").then().statusCode(200);
readObject(federate(broker, "Granted" + suffix, null), bucket, 200);
readObject(federate(denier, "Denied" + suffix, null), bucket, 403);
}
@Test
void aFederatedSessionCannotCallIamOrStsWhateverItsPoliciesAllow() {
// GetFederationToken credentials cannot call any IAM operation, nor any STS operation except
// GetCallerIdentity (STS API Reference, GetFederationToken).
String suffix = UUID.randomUUID().toString().substring(0, 8);
String iamAndSts = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["iam:*","sts:*"],"Resource":"*"}]}""";
S3RequestSigner admin = userWithPolicy("iam-admin-" + suffix, iamAndSts);
String role = "Trusting" + suffix;
iam("CreateRole", "RoleName", role, "AssumeRolePolicyDocument", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"AWS":["arn:aws:iam::%1$s:root","arn:aws:sts::%1$s:federated-user/Named%2$s"]},
"Action":"sts:AssumeRole"}]}""".formatted(ACCOUNT, suffix));
S3RequestSigner scoped = federate(admin, "Scoped" + suffix, iamAndSts);
createUser(scoped, "by-session-" + suffix, 403);
assumeRole(scoped, role, 403);
// Nor does a trust policy naming the federated user let it assume the role.
assumeRole(federate(admin, "Named" + suffix, null), role, 403);
given().filter(scoped).formParam("Action", "GetCallerIdentity").when().post("/").then().statusCode(200);
// The user that minted the sessions keeps its own IAM and STS access.
createUser(admin, "by-user-" + suffix, 200);
assumeRole(admin, role, 200);
}
/** A bucket in the test account holding {@code o.txt}, created by an administrator there. */
private static String bucketWithObject(String bucket) {
S3RequestSigner admin = userWithPolicy("admin-" + bucket, ALL_S3);
given().filter(admin).when().put("/" + bucket).then().statusCode(200);
given().filter(admin).contentType("text/plain").body("payload")
.when().put("/" + bucket + "/o.txt").then().statusCode(200);
return bucket;
}
private static void readObject(S3RequestSigner caller, String bucket, int status) {
given().filter(caller).when().get("/" + bucket + "/o.txt").then().statusCode(status);
}
private static void writeObject(S3RequestSigner caller, String bucket, int status) {
given().filter(caller).contentType("text/plain").body("written")
.when().put("/" + bucket + "/" + UUID.randomUUID() + ".txt").then().statusCode(status);
}
private static void createUser(S3RequestSigner caller, String userName, int status) {
given().filter(caller).formParam("Action", "CreateUser").formParam("UserName", userName)
.when().post("/").then().statusCode(status);
}
private static void assumeRole(S3RequestSigner caller, String role, int status) {
given().filter(caller).formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::" + ACCOUNT + ":role/" + role).formParam("RoleSessionName", "s")
.when().post("/").then().statusCode(status);
}
private static S3RequestSigner userWithPolicy(String userName, String policy) {
iam("CreateUser", "UserName", userName);
iam("PutUserPolicy", "UserName", userName, "PolicyName", "inline", "PolicyDocument", policy);
ExtractableResponse<Response> key = given().formParam("Action", "CreateAccessKey")
.formParam("UserName", userName)
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/")
.then().statusCode(200).extract();
return S3RequestSigner.signedAs(
key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"),
key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey"));
}
private static S3RequestSigner federate(S3RequestSigner user, String name, String sessionPolicy) {
RequestSpecification request = given().filter(user)
.formParam("Action", "GetFederationToken").formParam("Name", name);
if (sessionPolicy != null) {
request = request.formParam("Policy", sessionPolicy);
}
ExtractableResponse<Response> issued = request.when().post("/").then().statusCode(200).extract();
return S3RequestSigner.signedAs(
issued.path("GetFederationTokenResponse.GetFederationTokenResult.Credentials.AccessKeyId"),
issued.path("GetFederationTokenResponse.GetFederationTokenResult.Credentials.SecretAccessKey"),
issued.path("GetFederationTokenResponse.GetFederationTokenResult.Credentials.SessionToken"));
}
private static S3RequestSigner sessionToken(S3RequestSigner user) {
ExtractableResponse<Response> issued = given().filter(user).formParam("Action", "GetSessionToken")
.when().post("/").then().statusCode(200).extract();
return S3RequestSigner.signedAs(
issued.path("GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId"),
issued.path("GetSessionTokenResponse.GetSessionTokenResult.Credentials.SecretAccessKey"),
issued.path("GetSessionTokenResponse.GetSessionTokenResult.Credentials.SessionToken"));
}
private static void iam(String action, String... params) {
RequestSpecification request = given().formParam("Action", action)
.header("Authorization", auth(ACCOUNT, "iam"));
for (int i = 0; i < params.length; i += 2) {
request = request.formParam(params[i], params[i + 1]);
}
request.when().post("/").then().statusCode(200);
}
private static String auth(String accessKeyId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261002/us-east-1/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -3,9 +3,9 @@ package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.restassured.specification.RequestSpecification;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -29,9 +29,9 @@ import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
@QuarkusTest
@@ -1573,13 +1573,16 @@ class S3AuthEnforcementIntegrationTest {
void signedRequestWithTemporaryCredentialRequiresIssuedSessionToken() {
String accessKeyId = "ASIAS3NORMALREQUEST";
String sessionToken = "issued-session-token";
iamService.registerSession(
// A GetSessionToken session the account root minted.
iamService.registerIssuedSession(
accessKeyId,
"temp-key-material",
sessionToken,
null,
Instant.now().plusSeconds(3600),
null);
null,
"000000000000",
"000000000000");
String path = "/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY;
given().filter(S3RequestSigner.signedAs(accessKeyId, "temp-key-material", sessionToken))
@@ -160,6 +160,8 @@ public final class IamServiceTestHelper {
InMemoryStorage<String, SessionCredential> sessions = new InMemoryStorage<>();
SessionCredential cred = new SessionCredential(
accessKeyId, secretAccessKey, sessionToken, null, expiration, null);
// A GetSessionToken session the account root minted: one with no issuer is no credential.
cred.setIssuerArn("arn:aws:iam::123456789012:root");
sessions.put(accessKeyId, cred);
return constructor.newInstance(