mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iam): populate aws:username, aws:userid and aws:PrincipalType (#5568)
The request context carried seven aws: keys plus aws:PrincipalArn, and none of
the three that say who is calling. A Condition matching on any of them could
not match, which is also why an IAM policy variable has nothing to resolve:
AWS's own IAMUserChangePassword policy scopes itself to user/${aws:username},
and substituting that needs the key to exist before it needs a substituter.
The values come from the user guide's principal key values list, one shape per
principal: 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 on an EC2 instance is role-id:instance-id.
aws:username is the exception and is only published for an IAM user. The guide
is explicit: "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". Leaving it absent is what makes a
statement matching on it fail to match, which is the documented behaviour for a
key with no value, so the absence is the enforcement rather than a gap in it.
One judgement. The principal key values list renders the role-session type both
as AssumedRole and, twice, as "Assumed role". The unspaced form is the one that
fits the vocabulary of every other value in that list, each a single word or
CamelCase, and it is the form AWS publishes machine-side, as CloudTrail's
userIdentity.type does.
aws:userid was already derived in full by resolveCallerUserId, for every
principal type including the EC2 and ECS session-name fallbacks, so that
derivation is now a shared sessionUserId rather than a second copy inside
resolveCallerArns: reporting one key two ways is how the two readers would
drift. CallerArns carries the three values so they come from the single lookup
its javadoc already required, two lookups being able to straddle a session's
expiry, and it writes them itself, so every context a request is evaluated
against describes the same principal and there is one place that decides which
keys a principal publishes. The enforcement filter builds one context per
resource the request names and, since #5576, one per transaction item, which is
what a policy scoped to dynamodb:LeadingKeys = ${aws:userid} will need. S3
builds one of its own when s3.enforce-auth has it evaluate a bucket policy
there and then, and that one carried aws:PrincipalArn alone, so an inverted
Condition on any of the three keys held against a caller that has them and
fired a Deny the policy meant to leave alone.
Three unit tests and four integration tests, one on the transaction-item path
and one in S3's own bucket-policy class, with the existing caller-ARN
assertions widened to pin the keys for the root, federated and user-minted
session principals they already covered. Each key probed by dropping it alone:
without aws:PrincipalType or aws:userid both enforcement tests fail, without
aws:username one does, and giving a role session a username it should not have
fails the test that asserts the absence. The two contexts outside the filter
are probed the same way, each reverted to aws:PrincipalArn alone, and each
fails its own test. 4489 tests pass at this commit, across all 277 IAM and
core/common classes, the shared enforcement fixtures, and the S3 policy,
enforcement, presigned and account-context ones, the shared filter and
CallerArns reaching all of them. Checkstyle and docs-check clean.
This commit is contained in:
1 parent
c5a964297e
commit
287d683da7
8 files changed
+415
-65
No files matched your search
+26
-1
@@ -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")
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
+148
@@ -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";
|
||||
}
|
||||
}
|
||||
+33
@@ -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
|
||||
|
||||
Reference in new issue
Block a user