Skip to content

armgit / floci

Public Imported from GitHub
0

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

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

Priamo Germosena3118eb42b5e
diff --git a/docs/services/sts.md b/docs/services/sts.md
index d3af514b6c..9e62c43c7e 100644
--- a/docs/services/sts.md
+++ b/docs/services/sts.md
@@ -20,6 +20,25 @@
|---|---|---|
| `FLOCI_SERVICES_STS_ENABLED` | `true` | Enable or disable the service |
+## Session Token and Federation Token Permissions
+
+When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, credentials from `GetSessionToken` and `GetFederationToken`
+are evaluated as the identity whose long-term key signed the call, as on AWS:
+
+- `GetSessionToken` credentials have the permissions of that IAM user, or of the account root when its key minted them,
+ still bounded by the account's service control policies.
+- `GetFederationToken` credentials have no permissions without a session policy (`Policy`). With one, they have the
+ intersection of that policy and the permissions of the IAM user that minted them, never those of a role that shares
+ the federated user's name. A resource policy naming the federated user's ARN can grant access on its own, but not
+ past an explicit `Deny` in the user's policies or permissions boundary. Whatever their policies allow, they cannot
+ call any IAM operation, nor any STS operation except `GetCallerIdentity`.
+ Managed session policies (`PolicyArns`) are not supported yet.
+
+A session minted with another session's temporary credentials, which AWS does not accept here, with an inactive access
+key or one that belongs to another account, or by an IAM user since deleted and recreated under the same name, is not
+a valid credential: it is refused like an unknown access key. A key IAM does not know anywhere mints sessions that act
+as the account root, as the key itself does.
+
## Trust Policy Enforcement
`AssumeRole` and `AssumeRoleWithWebIdentity` require the target role to exist in IAM, returning `AccessDenied` (403)
@@ -89,5 +108,7 @@ aws sts get-session-token --endpoint-url $AWS_ENDPOINT_URL
`GetCallerIdentity` is commonly used in CI pipelines and integration tests as a quick connectivity check before running more complex tests.
For temporary credentials returned by an assumed-role action, its `Arn` and `UserId` match
the `AssumedRoleUser.Arn` and `AssumedRoleUser.AssumedRoleId` returned when the session was created.
+For `GetSessionToken` credentials they are those of the IAM user that minted them, and for `GetFederationToken`
+credentials the `FederatedUser.Arn` and `FederatedUser.FederatedUserId` (`<account>:<name>`).
When `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL=true`, requests signed with the seeded `floci` access key return `arn:aws:iam::000000000000:user/floci-deployer`. Other unknown local credentials continue to return the account root ARN for backward compatibility.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index d69560d4bb..2a2c8b74ba 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -322,8 +322,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
accountRootPrincipal = true;
} else if (iamService.isKnownAccessKey(akid)) {
- // A real credential this filter cannot map to policies, such as a session with no
- // role ARN. Denying it would reject an authenticated caller, so it stays allowed.
+ // A real credential this filter cannot map to policies, such as a session Floci mints
+ // for its own presigned URLs with no policy to scope it. Denying it would reject an
+ // authenticated caller.
return;
} else {
// No such credential anywhere. Enforcement is on and the caller is unauthenticated,
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 7d3d5743ce..90ec9646f1 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
@@ -1,5 +1,11 @@
package io.github.hectorvent.floci.services.iam;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -21,6 +27,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.AccountPasswordPolicy;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.CredentialReport;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
@@ -31,13 +38,11 @@ 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.PolicyVersion;
-import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import io.github.hectorvent.floci.services.iam.model.SigningCertificate;
import io.github.hectorvent.floci.services.iam.model.SshPublicKey;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
-import com.fasterxml.jackson.core.type.TypeReference;
import io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
@@ -54,21 +59,21 @@ import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ThreadLocalRandom;
-import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@@ -90,8 +95,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final Logger LOG = Logger.getLogger(IamService.class);
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final String TEMPORARY_ACCESS_KEY_PREFIX = "ASIA";
+ private static final String FEDERATED_USER_PREFIX = "federated-user/";
+ private static final ObjectMapper POLICY_MAPPER = new ObjectMapper();
private static final String SCOPED_IDENTITY_SESSION_BASE_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
+ /**
+ * GetFederationToken credentials cannot call any IAM operation, nor any STS operation except
+ * GetCallerIdentity, whatever their policies allow. The enforcement filter answers
+ * GetCallerIdentity before reading any policy, so denying all of {@code sts:*} leaves it callable.
+ */
+ private static final String FEDERATED_USER_SESSION_LIMITS =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":[\"iam:*\",\"sts:*\"],\"Resource\":\"*\"}]}";
private static final String DEFAULT_DEPLOYER_USER = "floci-deployer";
private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci";
private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci";
@@ -3358,6 +3372,36 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
sessions.put(sessionAccessKeyId, session);
}
+ /**
+ * Stores a session GetSessionToken or GetFederationToken minted, with the identity whose
+ * long-term key minted it. An active access key of a user in this account names that user. A
+ * key IAM holds nowhere, the legacy {@code test} key or the account id among them, names the
+ * account root, which is how Floci treats such a key itself. Any other key IAM holds, such as
+ * another session's (both operations take long-term credentials only) or an inactive or
+ * foreign access key, leaves the issuer unset, and {@link #resolveCallerContext} then grants
+ * the session nothing.
+ *
+ * @param federatedUserArn the federated user's ARN for GetFederationToken, null for
+ * GetSessionToken
+ */
+ public void registerIssuedSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,
+ String federatedUserArn, Instant expiration, String sessionPolicyDocument,
+ String originAccountId, String issuingAccessKeyId) {
+ SessionCredential session = new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken,
+ federatedUserArn, expiration, sessionPolicyDocument, originAccountId);
+ Optional<IamUser> issuingUser = issuingAccessKeyId == null ? Optional.empty()
+ : accessKeys.get(issuingAccessKeyId)
+ .filter(accessKey -> "Active".equals(accessKey.getStatus()))
+ .flatMap(accessKey -> users.get(accessKey.getUserName()));
+ if (issuingUser.isPresent()) {
+ session.setIssuerArn(issuingUser.get().getArn());
+ session.setIssuerUserId(issuingUser.get().getUserId());
+ } else if (issuingAccessKeyId == null || !holdsKey(issuingAccessKeyId)) {
+ session.setIssuerArn(regionResolver.buildGlobalArn("iam", originAccountId, "root"));
+ }
+ sessions.put(sessionAccessKeyId, session);
+ }
+
/** Stores a temporary session in an explicit account namespace. */
public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,
String roleArn, Instant expiration,
@@ -3586,6 +3630,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* lookup spans all accounts; the access key's global uniqueness keeps the result unambiguous.
*/
private Optional<SessionCredential> findSessionAnyAccount(String accessKeyId) {
+ return storedSessionAnyAccount(accessKeyId).filter(session -> !isOrphanedIssuedSession(session));
+ }
+
+ /** The stored session with this key in any account, including an orphaned issued session. */
+ private Optional<SessionCredential> storedSessionAnyAccount(String accessKeyId) {
if (!isTemporaryAccessKey(accessKeyId)) {
return Optional.empty();
}
@@ -3595,6 +3644,130 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return sessions.get(accessKeyId);
}
+ /** Whether IAM holds this key at all: any account's access key, or any stored session. */
+ private boolean holdsKey(String accessKeyId) {
+ return isKnownAccessKey(accessKeyId) || sessions.get(accessKeyId).isPresent()
+ || storedSessionAnyAccount(accessKeyId).isPresent();
+ }
+
+ /**
+ * A GetSessionToken or GetFederationToken session whose issuer is gone: none was recorded (it was
+ * minted with another session's key, an inactive or another account's key, or stored before the
+ * issuer was recorded), or its user has since been deleted or recreated under the same name.
+ * Such a session is no credential at all, so that neither a resource policy nor a fallback to the
+ * account root can act on its behalf.
+ */
+ private boolean isOrphanedIssuedSession(SessionCredential session) {
+ boolean issued = isFederatedUserSession(session)
+ || (session.getRoleArn() == null && session.getPresignedAction() == null);
+ return issued && !issuedByRoot(session) && issuingUser(session).isEmpty();
+ }
+
+ /** A session GetFederationToken minted: its role ARN slot holds the federated user's ARN. */
+ private static boolean isFederatedUserSession(SessionCredential session) {
+ String arn = session.getRoleArn();
+ return AwsArnUtils.isArnFor(arn, "sts") && AwsArnUtils.parse(arn).resource().startsWith(FEDERATED_USER_PREFIX);
+ }
+
+ private static boolean issuedByRoot(SessionCredential session) {
+ String issuerArn = session.getIssuerArn();
+ return issuerArn != null && "root".equals(AwsArnUtils.parse(issuerArn).resource());
+ }
+
+ /** The IAM user whose key minted the session, while it is still that user rather than a same-named one. */
+ private Optional<IamUser> issuingUser(SessionCredential session) {
+ String issuerArn = session.getIssuerArn();
+ String issuerUserId = session.getIssuerUserId();
+ if (issuerArn == null || issuerUserId == null) {
+ return Optional.empty();
+ }
+ String userName = issuerArn.substring(issuerArn.lastIndexOf('/') + 1);
+ Optional<IamUser> user = users instanceof AccountAwareStorageBackend<IamUser> aware
+ ? aware.getForAccount(AwsArnUtils.parse(issuerArn).accountId(), userName)
+ : users.get(userName);
+ return user.filter(candidate -> issuerUserId.equals(candidate.getUserId()));
+ }
+
+ /**
+ * GetSessionToken credentials have the permissions of the identity that minted them: an IAM
+ * user's own policies and boundary, or the account root's, which the enforcement filter still
+ * bounds by the account's service control policies.
+ */
+ private CallerContext sessionTokenContext(SessionCredential session) {
+ if (issuedByRoot(session)) {
+ return CallerContext.of(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY));
+ }
+ return issuingUser(session)
+ .map(user -> new CallerContext(collectUserPolicies(user.getUserName()), null,
+ resolveUserBoundaryDocument(user.getUserName())))
+ .orElse(CallerContext.of(List.of()));
+ }
+
+ /**
+ * GetFederationToken credentials grant nothing without a session policy. With one, they grant
+ * the intersection of that policy and the permissions of the identity that minted them, never
+ * those of a role.
+ *
+ * <p>Without one, the session still answers to its issuer's explicit denies. A resource policy
+ * that names the federated user grants to the session directly, past any implicit deny in an
+ * identity policy, boundary or session policy, but not past an explicit one (IAM User Guide,
+ * "Resource-based policies for AWS STS federated user principal sessions"). So the session
+ * carries only the Deny statements of its user's policies and boundary.
+ */
+ private CallerContext federatedUserContext(SessionCredential session) {
+ String sessionPolicy = session.getSessionPolicyDocument();
+ if (sessionPolicy == null || sessionPolicy.isBlank()) {
+ return issuingUser(session)
+ .map(user -> CallerContext.of(List.of(denyStatementsOf(user.getUserName()))))
+ .orElse(CallerContext.of(List.of()));
+ }
+ if (issuedByRoot(session)) {
+ return new CallerContext(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY), sessionPolicy, null);
+ }
+ return issuingUser(session)
+ .map(user -> new CallerContext(collectUserPolicies(user.getUserName()), sessionPolicy,
+ resolveUserBoundaryDocument(user.getUserName())))
+ .orElse(CallerContext.of(List.of()));
+ }
+
+ /** Adds the IAM and STS limits that bind a federated session on top of whatever it is granted. */
+ private static CallerContext withFederatedUserLimits(CallerContext context) {
+ List<String> identityPolicies = context.identityPolicies() == null
+ ? new ArrayList<>() : new ArrayList<>(context.identityPolicies());
+ identityPolicies.add(FEDERATED_USER_SESSION_LIMITS);
+ return new CallerContext(identityPolicies, context.sessionPolicyDocument(), context.boundaryPolicyDocument());
+ }
+
+ /** One policy document holding only the Deny statements of a user's policies and boundary. */
+ private String denyStatementsOf(String userName) {
+ List<String> documents = new ArrayList<>();
+ List<String> userPolicies = collectUserPolicies(userName);
+ if (userPolicies != null) {
+ documents.addAll(userPolicies);
+ }
+ String boundary = resolveUserBoundaryDocument(userName);
+ if (boundary != null) {
+ documents.add(boundary);
+ }
+ ArrayNode denies = POLICY_MAPPER.createArrayNode();
+ for (String document : documents) {
+ try {
+ JsonNode statements = POLICY_MAPPER.readTree(document).path("Statement");
+ for (JsonNode statement : statements.isArray() ? statements : List.of(statements)) {
+ if ("Deny".equalsIgnoreCase(statement.path("Effect").asText())) {
+ denies.add(statement);
+ }
+ }
+ } catch (JsonProcessingException e) {
+ LOG.warnv("Skipping an unparseable policy of user {0}: {1}", userName, e.getMessage());
+ }
+ }
+ ObjectNode policy = POLICY_MAPPER.createObjectNode();
+ policy.put("Version", "2012-10-17");
+ policy.set("Statement", denies);
+ return policy.toString();
+ }
+
/**
* Resolves the full caller context for the given access key, including identity policies,
* optional session policy, and optional permission boundary.
@@ -3621,12 +3794,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return null; // expired — unknown key → bypass
}
+ if (isFederatedUserSession(session)) {
+ return withFederatedUserLimits(federatedUserContext(session));
+ }
if (session.getRoleArn() == null) {
- // A locally minted identity session can carry a restrictive session policy.
- // Unscoped GetSessionToken credentials retain the historical bypass.
- return session.getPresignedAction() == null || session.getSessionPolicyDocument() == null ? null
- : new CallerContext(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY),
- session.getSessionPolicyDocument(), null);
+ if (session.getPresignedAction() != null) {
+ // A locally minted identity session can carry a restrictive session policy.
+ return session.getSessionPolicyDocument() == null ? null
+ : new CallerContext(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY),
+ session.getSessionPolicyDocument(), null);
+ }
+ return sessionTokenContext(session);
}
List<String> identityPolicies = collectRolePolicies(session.getRoleArn());
String boundaryDoc = resolveRoleBoundaryDocument(session.getRoleArn());
@@ -3667,7 +3845,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
Optional<SessionCredential> session = sessions.get(accessKeyId);
if (session.isPresent()) {
- return session;
+ return session.filter(stored -> !isOrphanedIssuedSession(stored));
}
if (!isTemporaryAccessKey(accessKeyId)) {
return Optional.empty();
@@ -3725,9 +3903,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
deleteSession(accessKeyId, session);
return Optional.empty();
}
+ if (isFederatedUserSession(session)) {
+ return Optional.of(new CallerArns(session.getRoleArn(), session.getRoleArn()));
+ }
String roleArn = session.getRoleArn();
if (roleArn == null) {
- return Optional.empty();
+ // GetSessionToken credentials act as the identity that minted them.
+ if (issuedByRoot(session)) {
+ return Optional.of(new CallerArns(session.getIssuerArn(), session.getIssuerArn()));
+ }
+ return issuingUser(session).map(user -> new CallerArns(user.getArn(), user.getArn()));
}
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
@@ -3785,6 +3970,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
&& !hasMatchingSessionToken(session, sessionToken)) {
return Optional.empty();
}
+ if (isFederatedUserSession(session)) {
+ // account:caller-specified-name, the aws:userid of a federated user.
+ AwsArnUtils.Arn federatedUser = AwsArnUtils.parse(session.getRoleArn());
+ return Optional.of(federatedUser.accountId() + ":"
+ + federatedUser.resource().substring(FEDERATED_USER_PREFIX.length()));
+ }
+ if (session.getRoleArn() == null) {
+ Optional<IamUser> issuingUser = issuingUser(session);
+ if (issuingUser.isPresent()) {
+ return Optional.of(issuingUser.get().getUserId());
+ }
+ }
if (session.getAssumedRoleId() != null) {
return Optional.of(session.getAssumedRoleId());
} else if (session.getEc2RoleId() != null && session.getEc2InstanceId() != null) {
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 8f16295cd5..c5d7b7dd83 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
@@ -171,12 +171,8 @@ public class StsQueryHandler {
*/
private Response enforceTrustPolicy(String roleArn, IamRole role, String roleAccountId,
MultivaluedMap<String, String> params) {
- String auth = IamEnforcementFilter.requestAuthorization(
- headers == null ? null : headers.getHeaderString("Authorization"),
- uriInfo == null ? null : uriInfo.getQueryParameters());
String callerAccount = regionResolver.getAccountId();
- String accessKeyId = auth == null ? null : accountResolver.extractAccessKeyId(auth);
- Optional<IamService.CallerArns> callerArns = iamService.resolveCallerArns(accessKeyId);
+ Optional<IamService.CallerArns> callerArns = iamService.resolveCallerArns(callerAccessKeyId());
String callerArn = callerArns.map(IamService.CallerArns::callerArn)
.orElse(regionResolver.buildGlobalArn("iam", callerAccount, "root"));
String principalArn = callerArns.map(IamService.CallerArns::principalArn).orElse(callerArn);
@@ -265,9 +261,9 @@ public class StsQueryHandler {
Instant expiration = Instant.now().plusSeconds(durationSeconds);
String result = credentialsXml(accessKeyId, secretKey, sessionToken, expiration);
- // No role ARN — route these credentials back to the caller's account.
- iamService.registerSession(
- accessKeyId, secretKey, sessionToken, null, expiration, null, regionResolver.getAccountId());
+ // No role ARN: the credentials route back to the caller's account and act as the caller.
+ iamService.registerIssuedSession(accessKeyId, secretKey, sessionToken, null, expiration, null,
+ regionResolver.getAccountId(), callerAccessKeyId());
return Response.ok(AwsQueryResponse.envelope("GetSessionToken", AwsNamespaces.STS, result)).build();
}
@@ -529,6 +525,14 @@ public class StsQueryHandler {
return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithSAML", AwsNamespaces.STS, result)).build();
}
+ /** The access key that signed this request, in the header or presigned in the query. */
+ private String callerAccessKeyId() {
+ String auth = IamEnforcementFilter.requestAuthorization(
+ headers == null ? null : headers.getHeaderString("Authorization"),
+ uriInfo == null ? null : uriInfo.getQueryParameters());
+ return auth == null ? null : accountResolver.extractAccessKeyId(auth);
+ }
+
private Response handleGetFederationToken(MultivaluedMap<String, String> params) {
Response validation = validateRequired(params, "Name");
if (validation != null) {
@@ -550,10 +554,10 @@ public class StsQueryHandler {
String federatedUserArn = regionResolver.buildGlobalArn("sts", accountId, "federated-user/" + name);
String sessionPolicy = getParam(params, "Policy");
- // Register federation token so enforcement can scope its policies via session policy.
- // The federated-user ARN already carries the caller's account, so reuse it as the origin.
- iamService.registerSession(
- accessKeyId, secretKey, sessionToken, federatedUserArn, expiration, sessionPolicy, accountId);
+ // The session is scoped by its session policy within the permissions of the caller that
+ // minted it, so the caller is recorded with it.
+ iamService.registerIssuedSession(accessKeyId, secretKey, sessionToken, federatedUserArn, expiration,
+ sessionPolicy, accountId, callerAccessKeyId());
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java
index ac0846deaf..4cac009af0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java
@@ -32,6 +32,13 @@ public class SessionCredential {
/** Exact object action and ARN for an internally generated S3 presigned URL. */
private String presignedAction;
private String presignedResourceArn;
+ /**
+ * The long-term identity whose key minted this session through GetSessionToken or
+ * GetFederationToken: an IAM user's ARN, or the account root's. Null for every other session.
+ */
+ private String issuerArn;
+ /** The unique ID of the IAM user named by {@link #issuerArn}, so a same-named replacement is not it. */
+ private String issuerUserId;
public SessionCredential() {}
@@ -123,4 +130,10 @@ public class SessionCredential {
public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }
public void setLambdaExecutionRole(boolean lambdaExecutionRole) { this.lambdaExecutionRole = lambdaExecutionRole; }
+
+ public String getIssuerArn() { return issuerArn; }
+ public void setIssuerArn(String issuerArn) { this.issuerArn = issuerArn; }
+
+ public String getIssuerUserId() { return issuerUserId; }
+ public void setIssuerUserId(String issuerUserId) { this.issuerUserId = issuerUserId; }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java
index 8abcb2507a..1ab9b07020 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java
@@ -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));
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 ec85aa1633..e3ba76b87e 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
@@ -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"
);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ScpEnforcementLeaveOrganizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ScpEnforcementLeaveOrganizationIntegrationTest.java
index 2509797f8b..bb19c3d0b8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ScpEnforcementLeaveOrganizationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ScpEnforcementLeaveOrganizationIntegrationTest.java
@@ -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) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsIssuedSessionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsIssuedSessionEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..d11ebc10c0
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsIssuedSessionEnforcementIntegrationTest.java
@@ -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";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java
index c142738d9c..47616cbfa1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java
@@ -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))
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java
index 18425f332a..f7a7f18e0a 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java
@@ -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(