Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(iam): populate aws:username, aws:userid and aws:PrincipalType (#5568)

Priamo Germosen287d683da727
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 086588669c..fc7f3a76c0 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1322,6 +1322,26 @@ floci populates:
`assumed-role` session ARN, as AWS reports it ("For IAM roles, the request context returns the
ARN of the role"); a condition naming the session ARN does not match. It is **absent** only for
unknown keys, where nothing about the caller can be resolved.
+- `aws:PrincipalType` and `aws:userid`: resolved from the same lookup as `aws:PrincipalArn`, so
+ they always describe the same credential. The values follow the user guide's principal key
+ values list: `Account` with the account id for the account-root principal and for a session
+ token it minted, `User` with the user's own id for an IAM user access key and for a session
+ token that user minted, `FederatedUser` with `account:name` for a `GetFederationToken` session,
+ and `AssumedRole` with `role-id:session-name` for a role session, which for a role assigned to
+ an EC2 instance is `role-id:instance-id`. The guide renders the role-session type both as
+ `AssumedRole` and as "Assumed role"; floci uses the unspaced form, which is the one that fits
+ the vocabulary of every other value in that list and the one AWS publishes machine-side. The
+ guide's fifth value, `Anonymous`, is **not** populated: it applies to unsigned callers on S3,
+ SQS and SNS, which reach a resource policy through its own evaluation path rather than through
+ the enforcement filter, so a bucket policy conditioned on `aws:PrincipalType` being `Anonymous`
+ does not match an unsigned request.
+- `aws:username`: the IAM user's name, and **only** for an IAM user, whether it signed with its
+ own access key or with a session token it minted. The guide is explicit that it is "always
+ included in the request context for IAM users" while "anonymous requests and requests that are
+ made using the AWS account root user or IAM roles do not include this key", so for a role
+ session, a federated user or the account root it is absent, and a statement that matches on it
+ cannot match: an absent key has no equal or like value. That absence is the enforcement rather
+ than a gap in it.
- `aws:TagKeys`: the case-sensitive requested tag keys for EC2 `RunInstances` and
`CreateTags`, and S3 `PutBucketTagging`. `ForAllValues:StringEquals` can restrict the
complete requested set without a `Null` guard; no tags still means absent context.
@@ -1351,6 +1371,13 @@ being bounded by SCPs (below): both forms of root enforcement now agree. A negat
absent key cannot equal what the policy names, so the condition holds, and a `Deny` written
that way applies when the key is missing.
+The keys that say who is calling are written onto every context a request is evaluated against:
+the one the enforcement filter builds, one per resource the request names, one per transaction
+item, and the one S3 builds when it evaluates a bucket policy itself under `s3.enforce-auth`. A
+role trust policy is the exception: `sts:AssumeRole` evaluates its conditions with
+`aws:PrincipalArn` alone, so a trust policy keyed on `aws:userid`, `aws:PrincipalType` or
+`aws:username` does not match yet.
+
Transactions check each item as `PutItem`, `UpdateItem`, `DeleteItem`, `GetItem`, or
`ConditionCheckItem` before executing the request. Each item uses its own table, leading key
and requested attributes. `dynamodb:EnclosingOperation` identifies `TransactWriteItems` or
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 497edddba3..cb85dc0436 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
@@ -472,13 +472,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (callerArns.isPresent()) {
caller = caller.withPrincipalArn(callerArns.get().callerArn());
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
- putPrincipalKeys(conditionContext, callerArns.get());
+ callerArns.get().putPrincipalKeys(conditionContext);
}
List<Map<String, List<String>>> targetContexts = new ArrayList<>();
targetContexts.add(conditionContext);
for (Map<String, List<String>> target : remainingTargets) {
Map<String, List<String>> targetContext = new HashMap<>(target);
- callerArns.ifPresent(arns -> putPrincipalKeys(targetContext, arns));
+ callerArns.ifPresent(arns -> arns.putPrincipalKeys(targetContext));
targetContexts.add(targetContext);
}
@@ -490,7 +490,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (!transactionItems.isEmpty()) {
for (IamConditionContextResolver.DynamoDbTransactionItem item : transactionItems) {
Map<String, List<String>> itemContext = new HashMap<>(item.context());
- callerArns.ifPresent(arns -> putPrincipalKeys(itemContext, arns));
+ callerArns.ifPresent(arns -> arns.putPrincipalKeys(itemContext));
if (abortIfDenied(ctx, caller, principal, item.action(), credentialScope,
resolveResourceArns(credentialScope, List.of(item.resource())), List.of(itemContext),
region, accountId, akid)) {
@@ -677,14 +677,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private record ResolvedAuthorization(String credentialScope, String action) {
}
- private static void putPrincipalKeys(Map<String, List<String>> context, CallerArns arns) {
- context.put("aws:PrincipalArn", List.of(arns.principalArn()));
- }
-
/** Floci's account-root principal, which is both the caller and the request's aws:PrincipalArn. */
private CallerArns accountRootArns(String accountId) {
String rootArn = AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString();
- return new CallerArns(rootArn, rootArn);
+ return new CallerArns(rootArn, rootArn, CallerArns.TYPE_ACCOUNT, accountId, null);
}
/**
@@ -946,7 +942,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (callerArns.isPresent()) {
caller = caller.withPrincipalArn(callerArns.get().callerArn());
conditionContext = new HashMap<>();
- putPrincipalKeys(conditionContext, callerArns.get());
+ callerArns.get().putPrincipalKeys(conditionContext);
}
ResourcePolicyDecision effectiveDecision = resourcePolicyDecision;
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 fb48863f8e..73ecf17d5f 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
@@ -5079,12 +5079,76 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/**
* The two ARNs a caller's access key stands for, read from one lookup of the key.
*
- * @param callerArn the identity the caller acts as: the user's ARN, or for a role session its
- * {@code assumed-role} session ARN, as {@link #resolveCallerArn} returns it
- * @param principalArn the request's {@code aws:PrincipalArn}: the user's ARN, or for a role
- * session the ARN of the role that was assumed, path included
+ * @param callerArn the identity the caller acts as: the user's ARN, or for a role session
+ * its {@code assumed-role} session ARN, as {@link #resolveCallerArn}
+ * returns it
+ * @param principalArn the request's {@code aws:PrincipalArn}: the user's ARN, or for a role
+ * session the ARN of the role that was assumed, path included
+ * @param principalType the request's {@code aws:PrincipalType}
+ * @param userId the request's {@code aws:userid}, in the shape the guide gives for this
+ * kind of principal, or null when it publishes none
+ * @param userName the request's {@code aws:username}, which only an IAM user has
*/
- public record CallerArns(String callerArn, String principalArn) {}
+ public record CallerArns(String callerArn, String principalArn, String principalType,
+ String userId, String userName) {
+
+ /**
+ * The {@code aws:PrincipalType} values, from the IAM User Guide's principal key values
+ * list. The guide renders the role-session value both as {@code AssumedRole} and, twice,
+ * as "Assumed role"; the unspaced form is the one that fits the vocabulary the rest of the
+ * list uses, every other value there being a single word or CamelCase, and it is the form
+ * AWS publishes machine-side, as CloudTrail's {@code userIdentity.type} does.
+ */
+ public static final String TYPE_ACCOUNT = "Account";
+ public static final String TYPE_USER = "User";
+ public static final String TYPE_FEDERATED_USER = "FederatedUser";
+ public static final String TYPE_ASSUMED_ROLE = "AssumedRole";
+
+ /** The two ARNs alone, for a caller whose principal keys the site cannot derive. */
+ public CallerArns(String callerArn, String principalArn) {
+ this(callerArn, principalArn, null, null, null);
+ }
+
+ /**
+ * Writes the condition keys that say who is calling onto a request context, so every
+ * context a request is evaluated against sees the same principal: the enforcement
+ * filter's, one per resource the request names, and the one S3 builds when it evaluates a
+ * bucket policy itself.
+ *
+ * <p>{@code aws:PrincipalType} and {@code aws:userid} are published for every principal,
+ * the guide saying both are "included in the request context for all requests, including
+ * anonymous requests". {@code aws:username} is not: it is "always included in the request
+ * context for IAM users" while "requests that are made using the AWS account root user or
+ * IAM roles do not include this key", so it is only put here when the caller is a user. A
+ * key left absent is what makes a policy that matches on it fail to match, which is the
+ * behaviour AWS documents for a key with no value, so omitting it is the enforcement, not
+ * a gap in it.
+ */
+ public void putPrincipalKeys(Map<String, List<String>> context) {
+ context.put("aws:PrincipalArn", List.of(principalArn));
+ if (principalType != null) {
+ context.put("aws:PrincipalType", List.of(principalType));
+ }
+ if (userId != null) {
+ context.put("aws:userid", List.of(userId));
+ }
+ if (userName != null) {
+ context.put("aws:username", List.of(userName));
+ }
+ }
+ }
+
+ /**
+ * An IAM user acting as itself, whether it signed with its own access key or with a session
+ * token it minted: the guide gives this principal, and only this one, an
+ * {@code aws:username}, and its {@code aws:userid} is the user's own unique id rather than
+ * anything derivable from the ARN.
+ */
+ private static CallerArns callerForUser(IamUser user) {
+ return new CallerArns(user.getArn(), user.getArn(), CallerArns.TYPE_USER,
+ user.getUserId(), user.getUserName());
+ }
+
/**
* Both of the caller's ARNs from a single lookup, so they always describe the same credential:
@@ -5097,8 +5161,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);
if (akOpt.isPresent()) {
- String userName = akOpt.get().getUserName();
- return users.get(userName).map(IamUser::getArn).map(arn -> new CallerArns(arn, arn));
+ return users.get(akOpt.get().getUserName()).map(IamService::callerForUser);
}
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
@@ -5109,15 +5172,25 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return Optional.empty();
}
if (isFederatedUserSession(session)) {
- return Optional.of(new CallerArns(session.getRoleArn(), session.getRoleArn()));
+ // A federated user has no aws:username at all, only the account:name userid.
+ String federatedArn = session.getRoleArn();
+ return Optional.of(new CallerArns(federatedArn, federatedArn,
+ CallerArns.TYPE_FEDERATED_USER,
+ sessionUserId(session).orElse(null), null));
}
String roleArn = session.getRoleArn();
if (roleArn == null) {
// GetSessionToken credentials act as the identity that minted them.
if (issuedByRoot(session)) {
- return Optional.of(new CallerArns(session.getIssuerArn(), session.getIssuerArn()));
+ // The account root's aws:userid is the account id, and it has no
+ // aws:username: the guide lists it as not present for this principal.
+ String issuerArn = session.getIssuerArn();
+ return Optional.of(new CallerArns(issuerArn, issuerArn,
+ CallerArns.TYPE_ACCOUNT,
+ AwsArnUtils.accountOrDefault(issuerArn, regionResolver.getAccountId()),
+ null));
}
- return issuingUser(session).map(user -> new CallerArns(user.getArn(), user.getArn()));
+ return issuingUser(session).map(IamService::callerForUser);
}
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
@@ -5131,7 +5204,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String partition = AwsArnUtils.partitionOrDefault(roleArn, regionResolver.getPartition());
String sessionArn = AwsArnUtils.Arn.global(partition, "sts", accountId,
"assumed-role/" + roleName + "/" + sessionName).toString();
- return Optional.of(new CallerArns(sessionArn, roleArn));
+ return Optional.of(new CallerArns(sessionArn, roleArn, CallerArns.TYPE_ASSUMED_ROLE,
+ sessionUserId(session).orElse(null), null));
}
return Optional.empty();
@@ -5175,43 +5249,55 @@ 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());
- }
+ return sessionUserId(session);
+ }
+
+ return Optional.empty();
+ }
+
+ /**
+ * The {@code aws:userid} of a session, in the shape the IAM User Guide's principal key values
+ * list gives the kind of principal that holds it. Shared with {@link #resolveCallerArns}, which
+ * reports the same key for the same credential and must not derive it a second way.
+ */
+ private Optional<String> sessionUserId(SessionCredential session) {
+ 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) {
- return Optional.of(session.getEc2RoleId() + ":" + session.getEc2InstanceId());
- } else if (session.getRoleArn() != null) {
- String roleArn = session.getRoleArn();
- String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
- String accountId = AwsArnUtils.accountOrDefault(roleArn,
- session.getOriginAccountId() != null ? session.getOriginAccountId() : regionResolver.getAccountId());
- Optional<IamRole> roleOpt = findRole(accountId, roleName);
- String roleId = roleOpt.map(IamRole::getRoleId).filter(id -> !id.isBlank()).orElse(null);
- if (roleId != null) {
- String sessionName = session.getRoleSessionName();
- if (sessionName == null || sessionName.isBlank()) {
- if (session.getEc2InstanceId() != null) {
- sessionName = session.getEc2InstanceId();
- } else if (session.getEcsTaskArn() != null) {
- String taskArn = session.getEcsTaskArn();
- sessionName = taskArn.contains("/") ? taskArn.substring(taskArn.lastIndexOf('/') + 1) : taskArn;
- } else {
- sessionName = "floci-session";
- }
+ }
+ if (session.getAssumedRoleId() != null) {
+ return Optional.of(session.getAssumedRoleId());
+ } else if (session.getEc2RoleId() != null && session.getEc2InstanceId() != null) {
+ return Optional.of(session.getEc2RoleId() + ":" + session.getEc2InstanceId());
+ } else if (session.getRoleArn() != null) {
+ String roleArn = session.getRoleArn();
+ String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
+ String fallbackAccount = session.getOriginAccountId() != null
+ ? session.getOriginAccountId() : regionResolver.getAccountId();
+ String accountId = AwsArnUtils.accountOrDefault(roleArn, fallbackAccount);
+ Optional<IamRole> roleOpt = findRole(accountId, roleName);
+ String roleId = roleOpt.map(IamRole::getRoleId).filter(id -> !id.isBlank()).orElse(null);
+ if (roleId != null) {
+ String sessionName = session.getRoleSessionName();
+ if (sessionName == null || sessionName.isBlank()) {
+ if (session.getEc2InstanceId() != null) {
+ sessionName = session.getEc2InstanceId();
+ } else if (session.getEcsTaskArn() != null) {
+ String taskArn = session.getEcsTaskArn();
+ sessionName = taskArn.contains("/") ? taskArn.substring(taskArn.lastIndexOf('/') + 1) : taskArn;
+ } else {
+ sessionName = "floci-session";
}
- return Optional.of(roleId + ":" + sessionName);
}
+ return Optional.of(roleId + ":" + sessionName);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
index 0221f4790d..794a536206 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
@@ -1414,18 +1414,23 @@ public class S3Service implements Resettable, ResourceProvider {
}
String account = accessKeyId.matches("\\d{12}") ? accessKeyId : ownerId();
String rootArn = regionResolver.buildGlobalArn("iam", account, "root");
- return Optional.of(new CallerArns(rootArn, rootArn));
+ return Optional.of(new CallerArns(rootArn, rootArn, CallerArns.TYPE_ACCOUNT, account, null));
}
/**
* The request context a bucket policy is evaluated with here: the caller is an IAM principal,
- * never a service, and for a role session {@code aws:PrincipalArn} is the role's ARN.
+ * never a service, and the keys that say who is calling are the ones
+ * {@link CallerArns#putPrincipalKeys} writes, so a bucket policy sees the same principal
+ * whether S3 evaluates it or the enforcement filter does. For a role session
+ * {@code aws:PrincipalArn} is the role's ARN.
*/
private static Map<String, List<String>> bucketPolicyContext(CallerArns caller) {
- return caller != null
- ? Map.of("aws:PrincipalArn", List.of(caller.principalArn()),
- "aws:PrincipalIsAWSService", List.of("false"))
- : Map.of("aws:PrincipalIsAWSService", List.of("false"));
+ Map<String, List<String>> context = new HashMap<>();
+ context.put("aws:PrincipalIsAWSService", List.of("false"));
+ if (caller != null) {
+ caller.putPrincipalKeys(context);
+ }
+ return Map.copyOf(context);
}
private boolean isSameAccountAsBucketOwner(String accessKeyId, String principalArn, String bucketOwnerAccount) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DynamoDbTransactionAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DynamoDbTransactionAuthorizationIntegrationTest.java
index c37f9d4cab..fc2d939e79 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/DynamoDbTransactionAuthorizationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/DynamoDbTransactionAuthorizationIntegrationTest.java
@@ -100,6 +100,27 @@ class DynamoDbTransactionAuthorizationIntegrationTest {
request("test", "GetItem", keyBody(table)).statusCode(200).body("Item.value.S", equalTo("original"));
}
+ /**
+ * A transaction item is authorized against a context built for that item, so the keys that
+ * say who is calling have to be written onto it as well: a policy scoped to the caller's own
+ * {@code aws:username} authorizes the item, and the same policy naming somebody else does not.
+ */
+ @Test
+ void aTransactionItemCarriesTheCallersPrincipalKeys() {
+ String name = "tx-auth-" + UUID.randomUUID();
+ String own = table();
+ String caller = userNamed(name, policy("dynamodb:PutItem",
+ ",\"Condition\":{\"StringEquals\":{\"aws:username\":\"" + name + "\"}}"));
+ transaction(caller, "Put", own).statusCode(200);
+ assertResult("Put", own);
+
+ String other = table();
+ String stranger = user(policy("dynamodb:PutItem",
+ ",\"Condition\":{\"StringEquals\":{\"aws:username\":\"somebody-else\"}}"));
+ transaction(stranger, "Put", other).statusCode(400).body(containsString("AccessDeniedException"));
+ request("test", "GetItem", keyBody(other)).statusCode(200).body("Item.value.S", equalTo("original"));
+ }
+
@ParameterizedTest
@ValueSource(strings = {"Put", "Update", "Delete", "Get", "ConditionCheck"})
void extraEnvelopeFieldCannotBypassItemAuthorization(String operation) {
@@ -324,7 +345,11 @@ class DynamoDbTransactionAuthorizationIntegrationTest {
}
private String user(String policy) {
- String name = "tx-auth-" + UUID.randomUUID();
+ return userNamed("tx-auth-" + UUID.randomUUID(), policy);
+ }
+
+ /** A user whose name the caller chooses, for a policy that has to name it. */
+ private String userNamed(String name, String policy) {
String key = createUser(cleanup, endpoint.getPort(), auth("test", "iam"), name).accessKeyId();
given().header("Authorization", auth("test", "iam")).formParam("Action", "PutUserPolicy")
.formParam("UserName", name).formParam("PolicyName", "transaction")
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 bffa0f34dd..750f682d2a 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
@@ -366,13 +366,33 @@ class IamServiceTest {
null, "123456789012", "s", "AROATESTROLEID:s");
// The session ARN carries only the role's name; aws:PrincipalArn is the role's own ARN.
+ // The principal keys ride along from the same lookup: a role session is typed as an
+ // assumed role, its aws:userid is the stored role-id:session-name, and it has no
+ // aws:username, which the guide lists as not present for a role.
assertEquals(new IamService.CallerArns("arn:aws:sts::123456789012:assumed-role/TestRole/s",
- "arn:aws:iam::123456789012:role/team/TestRole"),
+ "arn:aws:iam::123456789012:role/team/TestRole",
+ IamService.CallerArns.TYPE_ASSUMED_ROLE, "AROATESTROLEID:s", null),
service.resolveCallerArns("ASIALIVESESSION").orElseThrow());
// An expired session answers for neither, never for one and not the other.
assertTrue(service.resolveCallerArns("ASIAEXPIREDSESSION").isEmpty());
}
+ @Test
+ void anIamUsersCallerArnsCarryItsNameIdAndType() {
+ IamService service = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>());
+ IamUser user = service.createUser("alice", "/");
+ AccessKey key = service.createAccessKey("alice");
+
+ IamService.CallerArns arns = service.resolveCallerArns(key.getAccessKeyId()).orElseThrow();
+
+ // The one principal the guide gives an aws:username, and its aws:userid is the user's own
+ // id rather than anything the ARN carries.
+ assertEquals(IamService.CallerArns.TYPE_USER, arns.principalType());
+ assertEquals("alice", arns.userName());
+ assertEquals(user.getUserId(), arns.userId());
+ assertEquals(user.getArn(), arns.callerArn());
+ }
+
@Test
void sessionExpiryFollowsTheInjectedClock() {
MutableClock clock = new MutableClock();
@@ -502,7 +522,10 @@ class IamServiceTest {
assertEquals(List.of(READ_S3), context.identityPolicies());
assertNull(context.sessionPolicyDocument());
- assertEquals(new IamService.CallerArns(alice.getArn(), alice.getArn()),
+ // Acting as the user means carrying the user's principal keys, aws:username included:
+ // the guide gives one to an IAM user and to no other principal.
+ assertEquals(new IamService.CallerArns(alice.getArn(), alice.getArn(),
+ IamService.CallerArns.TYPE_USER, alice.getUserId(), "alice"),
service.resolveCallerArns("ASIASESSIONTOKEN").orElseThrow());
assertEquals(alice.getUserId(), service.resolveCallerUserId("ASIASESSIONTOKEN", "token").orElseThrow());
}
@@ -517,7 +540,11 @@ class IamServiceTest {
// 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"),
+ // "aws:userid: AWS account ID" and no aws:username, which the guide lists as not
+ // present for the account root.
+ assertEquals(new IamService.CallerArns("arn:aws:iam::000000000000:root",
+ "arn:aws:iam::000000000000:root", IamService.CallerArns.TYPE_ACCOUNT,
+ "000000000000", null),
service.resolveCallerArns("ASIAROOTSESSION").orElseThrow());
}
@@ -624,7 +651,10 @@ class IamServiceTest {
assertEquals(READ_S3, withPolicy.identityPolicies().getFirst());
assertFederatedUserLimits(withPolicy.identityPolicies().getLast());
assertEquals(ALL_S3, withPolicy.sessionPolicyDocument());
- assertEquals(new IamService.CallerArns(federatedArn, federatedArn),
+ // The same aws:userid both ways, since one derivation now serves both readers, and no
+ // aws:username: the guide lists it as not present for a federated user.
+ assertEquals(new IamService.CallerArns(federatedArn, federatedArn,
+ IamService.CallerArns.TYPE_FEDERATED_USER, "000000000000:Bob", null),
service.resolveCallerArns("ASIAWITHPOLICY").orElseThrow());
assertEquals("000000000000:Bob", service.resolveCallerUserId("ASIAWITHPOLICY", "token").orElseThrow());
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/PrincipalContextKeysEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/PrincipalContextKeysEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..ffd5a3ecf9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/PrincipalContextKeysEnforcementIntegrationTest.java
@@ -0,0 +1,148 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.matchesPattern;
+
+/**
+ * With {@code iam.enforcement-enabled=true}, the three condition keys that describe who is calling
+ * are in the request context: {@code aws:username}, {@code aws:userid} and
+ * {@code aws:PrincipalType}.
+ *
+ * <p>Driven over the wire because the values come from the signing credential rather than from
+ * anything in the request, and because what matters is the decision a policy reaches, not the map
+ * the filter built. The guide's principal key values list gives each principal its own values, and
+ * the two this emulator can be called as are covered here: an IAM user, the only principal with an
+ * {@code aws:username}, and a role session, which has none. The rest are pinned on
+ * {@code resolveCallerArns} directly, where the branch per principal type lives.
+ */
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class PrincipalContextKeysEnforcementIntegrationTest {
+
+ private static final String ACCOUNT = "111111111111";
+
+ private record Session(String accessKeyId, String sessionToken) {
+ }
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void anIamUserCarriesItsNameItsIdAndItsType() {
+ String user = "principal-keys-" + UUID.randomUUID().toString().substring(0, 8);
+ // The id is the user's own rather than anything the ARN carries, which is why the key
+ // needs the stored user and not a parse of the ARN.
+ String userId = createUser(user);
+ putUserPolicy(user, """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",
+ "Condition":{"StringEquals":{"aws:username":"%1$s"}}},
+ {"Effect":"Allow","Action":"iam:ListRoles","Resource":"*",
+ "Condition":{"StringEquals":{"aws:username":"somebody-else"}}},
+ {"Effect":"Allow","Action":"iam:ListGroups","Resource":"*",
+ "Condition":{"StringEquals":{"aws:PrincipalType":"User"}}},
+ {"Effect":"Allow","Action":"iam:ListPolicies","Resource":"*",
+ "Condition":{"StringEquals":{"aws:userid":"%2$s"}}}]}""".formatted(user, userId));
+ String accessKeyId = createAccessKey(user);
+
+ iamCall(accessKeyId, null, "ListUsers").then().statusCode(200);
+ // The key carries this caller's name, so another name does not match it.
+ iamCall(accessKeyId, null, "ListRoles").then().statusCode(403);
+ iamCall(accessKeyId, null, "ListGroups").then().statusCode(200);
+ iamCall(accessKeyId, null, "ListPolicies").then().statusCode(200);
+ }
+
+ @Test
+ void aRoleSessionCarriesNoUserNameAndIsTypedAsAnAssumedRole() {
+ String role = "principal-keys-" + UUID.randomUUID().toString().substring(0, 8);
+ String roleArn = "arn:aws:iam::" + ACCOUNT + ":role/" + role;
+ createRole(role, """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",
+ "Condition":{"StringEquals":{"aws:PrincipalType":"AssumedRole"}}},
+ {"Effect":"Allow","Action":"iam:ListRoles","Resource":"*",
+ "Condition":{"StringEquals":{"aws:username":"%s"}}},
+ {"Effect":"Allow","Action":"iam:ListGroups","Resource":"*",
+ "Condition":{"StringLike":{"aws:userid":"AROA*:s"}}}]}""".formatted(role));
+ Session session = assumeRole(roleArn);
+
+ iamCall(session.accessKeyId(), session.sessionToken(), "ListUsers").then().statusCode(200);
+ // The guide lists aws:username as not present for a role, so a statement that matches on
+ // it cannot match: an absent key has no equal value.
+ iamCall(session.accessKeyId(), session.sessionToken(), "ListRoles").then().statusCode(403);
+ // "role-id:caller-specified-role-name", the shape the guide gives a role session.
+ iamCall(session.accessKeyId(), session.sessionToken(), "ListGroups").then().statusCode(200);
+ }
+
+ private static String createUser(String user) {
+ Response response = given().formParam("Action", "CreateUser").formParam("UserName", user)
+ .header("Authorization", auth(ACCOUNT, "iam")).when().post("/");
+ response.then().statusCode(200)
+ .body("CreateUserResponse.CreateUserResult.User.UserId",
+ matchesPattern("AIDA[A-Z0-9]{16}"));
+ return response.path("CreateUserResponse.CreateUserResult.User.UserId");
+ }
+
+ private static void putUserPolicy(String user, String policy) {
+ given().formParam("Action", "PutUserPolicy").formParam("UserName", user)
+ .formParam("PolicyName", "p").formParam("PolicyDocument", policy)
+ .header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ }
+
+ private static String createAccessKey(String user) {
+ Response response = given().formParam("Action", "CreateAccessKey").formParam("UserName", user)
+ .header("Authorization", auth(ACCOUNT, "iam")).when().post("/");
+ response.then().statusCode(200);
+ return response.path(
+ "CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
+ }
+
+ private static void createRole(String role, String policy) {
+ given().formParam("Action", "CreateRole").formParam("RoleName", role)
+ .formParam("AssumeRolePolicyDocument", """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}"""
+ .formatted(ACCOUNT))
+ .header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ given().formParam("Action", "PutRolePolicy").formParam("RoleName", role)
+ .formParam("PolicyName", "p").formParam("PolicyDocument", policy)
+ .header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ }
+
+ private static Session assumeRole(String roleArn) {
+ Response response = given().formParam("Action", "AssumeRole").formParam("RoleArn", roleArn)
+ .formParam("RoleSessionName", "s")
+ .header("Authorization", auth(ACCOUNT, "sts")).when().post("/");
+ response.then().statusCode(200);
+ return new Session(
+ response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),
+ response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"));
+ }
+
+ private static Response iamCall(String accessKeyId, String sessionToken, String action) {
+ RequestSpecification request = given().formParam("Action", action)
+ .header("Authorization", auth(accessKeyId, "iam"));
+ if (sessionToken != null) {
+ request = request.header("X-Amz-Security-Token", sessionToken);
+ }
+ return request.when().post("/");
+ }
+
+ private static String auth(String accessKeyId, String service) {
+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261001/us-east-1/" + service
+ + "/aws4_request, SignedHeaders=host, Signature=abc";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java
index dfc6cfa5d3..e5aa8ed564 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java
@@ -241,6 +241,39 @@ class S3BucketPolicyEnforcementIntegrationTest {
.then().statusCode(403);
}
+ @Test
+ void aBucketPolicyReadsTheCallersPrincipalKeys() {
+ // S3 evaluates the bucket policy itself under s3.enforce-auth, so the keys that say who is
+ // calling belong on the context it builds too: an inverted Condition on one of them matches
+ // a caller the key is absent for, which fires a Deny the policy meant to leave alone. Each
+ // key is read through the principal the guide publishes it for, aws:username being the one
+ // an IAM user has and a role session does not.
+ String suffix = UUID.randomUUID().toString().substring(0, 8);
+ String bucket = "bp-principal-keys-" + suffix;
+ String userName = "bp-keys-user-" + suffix;
+ createBucket(bucket);
+ putObject(bucket, "userid/x.txt", "userid");
+ putObject(bucket, "type/x.txt", "type");
+ putObject(bucket, "username/x.txt", "username");
+ S3RequestSigner session = sessionOfRoleUnderTeamPath("bp-keys-role-" + suffix, "000000000000");
+ S3RequestSigner user = createAccountAdmin(userName, "000000000000").signer();
+ putBucketPolicy(bucket, """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%1$s/userid/*",
+ "Condition":{"StringNotLike":{"aws:userid":"AROA*:s"}}},
+ {"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%1$s/type/*",
+ "Condition":{"StringNotEquals":{"aws:PrincipalType":"AssumedRole"}}},
+ {"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%1$s/username/*",
+ "Condition":{"StringNotEquals":{"aws:username":"%2$s"}}}]}""".formatted(bucket, userName));
+
+ given().filter(session).when().get("/" + bucket + "/userid/x.txt")
+ .then().statusCode(200).body(equalTo("userid"));
+ given().filter(session).when().get("/" + bucket + "/type/x.txt")
+ .then().statusCode(200).body(equalTo("type"));
+ given().filter(user).when().get("/" + bucket + "/username/x.txt")
+ .then().statusCode(200).body(equalTo("username"));
+ }
+
@Test
void aBucketPolicyNamingTheCallersAccountGrantsACrossAccountCopy() {
// The CopyObject source check matched a bucket policy's Principal against the caller's ARN as