mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): populate stored caller principal tags (#7591)
This commit is contained in:
1 parent
983fdecc79
commit
1ce40a1c79
6 files changed
+343
-5
No files matched your search
@@ -761,6 +761,9 @@ key in. A role named as the policy source is not a session, so there is no sessi
|
||||
`aws:userid` and no documented `aws:PrincipalType` for it; those keys stay absent and a statement
|
||||
matching on one does not match.
|
||||
|
||||
`aws:PrincipalTag/<key>` must be supplied in `ContextEntries`, even when the policy source is a
|
||||
tagged user or role. The simulator does not populate stored identity tags.
|
||||
|
||||
`PolicySourceArn` on `SimulatePrincipalPolicy` and `GetContextKeysForPrincipalPolicy` resolves an
|
||||
IAM user or role only, not a group. It is held to the 20 characters `arnType` declares before it
|
||||
is resolved, so a value too short to be any ARN is a `ValidationError` with status 400 naming the
|
||||
@@ -2709,6 +2712,13 @@ 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:PrincipalTag/<key>`: the stored tags of the IAM user making the request, including a
|
||||
`GetSessionToken` session, or of the role an assumed-role session represents. Tags are read
|
||||
from that identity's account and copied for the request; later requests see tag updates and
|
||||
removals. Identity policies, resource policies and `AssumeRole` trust policies see the same
|
||||
caller tags. A role session uses its role's tags, not those of the user that assumed it.
|
||||
Untagged identities, account-root principals and federated users have no stored principal tags.
|
||||
STS session tags, their overrides and transitive inheritance are not implemented.
|
||||
- `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
|
||||
|
||||
@@ -300,6 +300,10 @@ request context holds `sts:RoleSessionName`, `sts:ExternalId` when the caller pa
|
||||
guard, refuses a call that omits it or passes another value, and a conditional `Deny` applies only
|
||||
when its condition matches.
|
||||
|
||||
`aws:PrincipalTag/<key>` contains the stored tags of the calling IAM user or assumed role.
|
||||
The target role's tags do not supply the caller's principal tags. A chained request reads the
|
||||
current caller role's tags; tags on the user that originally assumed it are not inherited.
|
||||
|
||||
### Known limitations
|
||||
|
||||
- **Session tags and source identity are not modelled.** `aws:RequestTag/*`, `aws:TagKeys`,
|
||||
|
||||
@@ -5194,7 +5194,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
return delegatedApproverRole(approverArn)
|
||||
.map(role -> new CallerArns(approverArn, role.getArn(), CallerArns.TYPE_ASSUMED_ROLE,
|
||||
null, null, role.getPermissionsBoundaryArn() != null));
|
||||
null, null, role.getPermissionsBoundaryArn() != null, role.getTags()));
|
||||
}
|
||||
|
||||
/** The {@code aws:userid} of delegated credentials: the approver's, in the approver's shape. */
|
||||
@@ -5445,9 +5445,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* @param userName the request's {@code aws:username}, which only an IAM user has
|
||||
* @param permissionsBoundary whether a permissions boundary is attached to the user, or to the
|
||||
* role a session assumed, which a Deny's {@code NotPrincipal} never spares
|
||||
* @param principalTags the stored user's or assumed role's tags, snapshotted for this request;
|
||||
* STS session tags are not yet recorded
|
||||
*/
|
||||
public record CallerArns(String callerArn, String principalArn, String principalType,
|
||||
String userId, String userName, boolean permissionsBoundary) {
|
||||
String userId, String userName, boolean permissionsBoundary,
|
||||
Map<String, String> principalTags) {
|
||||
|
||||
public CallerArns {
|
||||
principalTags = Map.copyOf(principalTags);
|
||||
}
|
||||
|
||||
/** A caller without stored principal tags, including account-root and federated identities. */
|
||||
public CallerArns(String callerArn, String principalArn, String principalType, String userId,
|
||||
String userName, boolean permissionsBoundary) {
|
||||
this(callerArn, principalArn, principalType, userId, userName, permissionsBoundary, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code aws:PrincipalType} values, from the IAM User Guide's principal key values
|
||||
@@ -5508,6 +5521,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
if (userName != null) {
|
||||
context.put("aws:username", List.of(userName));
|
||||
}
|
||||
principalTags.forEach((key, value) -> context.put("aws:PrincipalTag/" + key, List.of(value)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5518,8 +5532,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* anything derivable from the ARN.
|
||||
*/
|
||||
private static CallerArns callerForUser(IamUser user) {
|
||||
return callerForUser(user, true);
|
||||
}
|
||||
|
||||
private static CallerArns callerForUser(IamUser user, boolean includeTags) {
|
||||
return new CallerArns(user.getArn(), user.getArn(), CallerArns.TYPE_USER,
|
||||
user.getUserId(), user.getUserName(), user.getPermissionsBoundaryArn() != null);
|
||||
user.getUserId(), user.getUserName(), user.getPermissionsBoundaryArn() != null,
|
||||
includeTags ? user.getTags() : Map.of());
|
||||
}
|
||||
|
||||
|
||||
@@ -5547,7 +5566,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
if (principalArn == null || !principalArn.contains(":user/")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return userFromArnOrName(principalArn).map(IamService::callerForUser);
|
||||
// The simulator requires callers to supply tag context explicitly, even for a tagged user.
|
||||
return userFromArnOrName(principalArn).map(user -> callerForUser(user, false));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5614,9 +5634,11 @@ 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();
|
||||
Optional<IamRole> role = roleFromArnOrName(roleArn);
|
||||
return Optional.of(new CallerArns(sessionArn, roleArn, CallerArns.TYPE_ASSUMED_ROLE,
|
||||
sessionUserId(session).orElse(null), null,
|
||||
roleFromArnOrName(roleArn).map(IamRole::getPermissionsBoundaryArn).isPresent()));
|
||||
role.map(IamRole::getPermissionsBoundaryArn).isPresent(),
|
||||
role.map(IamRole::getTags).orElse(Map.of())));
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
|
||||
+2
@@ -199,6 +199,7 @@ class CloudFormationPolicyDocumentIntrinsicsIntegrationTest {
|
||||
String policyName = "unresolvable-policy-" + suffix;
|
||||
|
||||
createStack(stackName, stackWithUnresolvablePolicyResource(roleName, policyName));
|
||||
CfnStackWaits.awaitStatus(stackName, "ROLLBACK_COMPLETE", CFN_AUTH);
|
||||
|
||||
String status = cfnQuery("DescribeStacks", stackName).then().statusCode(200).extract().asString();
|
||||
assertFalse(status.contains("<StackStatus>CREATE_COMPLETE</StackStatus>"),
|
||||
@@ -219,6 +220,7 @@ class CloudFormationPolicyDocumentIntrinsicsIntegrationTest {
|
||||
String policyName = "unresolvable-user-policy-" + suffix;
|
||||
|
||||
createStack(stackName, stackWithUnresolvableUserPolicy(userName, policyName));
|
||||
CfnStackWaits.awaitStatus(stackName, "ROLLBACK_COMPLETE", CFN_AUTH);
|
||||
|
||||
String status = cfnQuery("DescribeStacks", stackName).then().statusCode(200).extract().asString();
|
||||
assertFalse(status.contains("<StackStatus>CREATE_COMPLETE</StackStatus>"),
|
||||
|
||||
@@ -514,6 +514,73 @@ class IamServiceTest {
|
||||
assertEquals(user.getArn(), arns.callerArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userPrincipalTagsAreSnapshottedAndRefreshedForEachRequest() {
|
||||
IamUser user = iamService.createUser("tagged", "/team/");
|
||||
user.setTags(new LinkedHashMap<>(Map.of("Team", "platform", "Empty", "")));
|
||||
String key = iamService.createAccessKey("tagged").getAccessKeyId();
|
||||
IamService.CallerArns caller = iamService.resolveCallerArns(key).orElseThrow();
|
||||
user.getTags().put("Team", "other");
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
caller.putPrincipalKeys(context);
|
||||
assertEquals(List.of("platform"), context.get("aws:PrincipalTag/Team"));
|
||||
assertEquals(List.of(""), context.get("aws:PrincipalTag/Empty"));
|
||||
context.clear();
|
||||
iamService.resolveCallerArns(key).orElseThrow().putPrincipalKeys(context);
|
||||
assertEquals(List.of("other"), context.get("aws:PrincipalTag/Team"));
|
||||
user.getTags().clear();
|
||||
context.clear();
|
||||
iamService.resolveCallerArns(key).orElseThrow().putPrincipalKeys(context);
|
||||
assertTrue(context.keySet().stream().noneMatch(k -> k.startsWith("aws:PrincipalTag/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void userSessionTokensCarryUserTagsButFederatedAndRootSessionsDoNot() {
|
||||
IamUser user = iamService.createUser("tagged", "/");
|
||||
user.setTags(Map.of("Team", "platform"));
|
||||
String key = iamService.createAccessKey("tagged").getAccessKeyId();
|
||||
Instant expiration = Instant.now().plusSeconds(3600);
|
||||
iamService.registerIssuedSession("ASIAUSER", "secret", "token", null, expiration,
|
||||
null, "000000000000", key);
|
||||
iamService.registerIssuedSession("ASIAFEDERATED", "secret", "token",
|
||||
"arn:aws:sts::000000000000:federated-user/tagged", expiration, null, "000000000000", key);
|
||||
iamService.registerIssuedSession("ASIAROOT", "secret", "token", null, expiration,
|
||||
null, "000000000000", "test");
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.resolveCallerArns("ASIAUSER").orElseThrow().putPrincipalKeys(context);
|
||||
assertEquals(List.of("platform"), context.get("aws:PrincipalTag/Team"));
|
||||
for (String session : List.of("ASIAFEDERATED", "ASIAROOT")) {
|
||||
context.clear();
|
||||
iamService.resolveCallerArns(session).orElseThrow().putPrincipalKeys(context);
|
||||
assertFalse(context.containsKey("aws:PrincipalTag/Team"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleSessionPrincipalTagsComeFromTheStoredRoleWithItsPath() {
|
||||
IamRole role = iamService.createRole("Worker", "/teams/platform/", "{}", null, 3600, null);
|
||||
role.setTags(Map.of("Team", "platform"));
|
||||
iamService.registerSession("ASIATAGGEDROLE", "secret", "token", role.getArn(),
|
||||
Instant.now().plusSeconds(3600), null, "000000000000", "worker", "AROAWORKER:worker");
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.resolveCallerArns("ASIATAGGEDROLE").orElseThrow().putPrincipalKeys(context);
|
||||
assertEquals(List.of("platform"), context.get("aws:PrincipalTag/Team"));
|
||||
role.setTags(Map.of());
|
||||
context.clear();
|
||||
iamService.resolveCallerArns("ASIATAGGEDROLE").orElseThrow().putPrincipalKeys(context);
|
||||
assertFalse(context.containsKey("aws:PrincipalTag/Team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void simulationStillRequiresCallerSuppliedPrincipalTags() {
|
||||
IamUser user = iamService.createUser("tagged", "/");
|
||||
user.setTags(Map.of("Team", "platform"));
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.simulationPrincipalKeys(user.getArn()).orElseThrow().putPrincipalKeys(context);
|
||||
assertFalse(context.containsKey("aws:PrincipalTag/Team"));
|
||||
assertEquals(List.of("tagged"), context.get("aws:username"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void callerArnsSayWhetherAPermissionsBoundaryIsAttached() {
|
||||
IamService service = iamService(false);
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.awscore.exception.AwsServiceException;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.Tag;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.sts.StsClient;
|
||||
import software.amazon.awssdk.services.sts.model.Credentials;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class PrincipalTagEnforcementIntegrationTest {
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String OTHER_ACCOUNT = "222222222222";
|
||||
private static final String ALLOW_ASSUME = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}""";
|
||||
private static final String TAG_POLICY = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalTag/Team":"platform"}}},
|
||||
{"Effect":"Deny","Action":"iam:ListUsers","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalTag/Blocked":"yes"}}}]}""";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI baseUri;
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void userTagsControlAllowAndDenyAndUpdatesApplyToExistingCredentials() {
|
||||
String name = "principal-user-" + suffix();
|
||||
UserCredentials keys = user(ACCOUNT, name, TAG_POLICY);
|
||||
try (IamClient admin = admin(ACCOUNT); IamClient caller = userClient(keys)) {
|
||||
denied(caller::listUsers);
|
||||
admin.tagUser(r -> r.userName(name).tags(tag("Team", "Platform")));
|
||||
denied(caller::listUsers);
|
||||
admin.tagUser(r -> r.userName(name).tags(tag("Team", "platform")));
|
||||
caller.listUsers();
|
||||
admin.tagUser(r -> r.userName(name).tags(tag("Blocked", "yes")));
|
||||
denied(caller::listUsers);
|
||||
admin.untagUser(r -> r.userName(name).tagKeys("Blocked"));
|
||||
caller.listUsers();
|
||||
admin.untagUser(r -> r.userName(name).tagKeys("Team"));
|
||||
denied(caller::listUsers);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionTokenUsesTheIssuingUsersTags() {
|
||||
String name = "principal-token-" + suffix();
|
||||
UserCredentials keys = user(ACCOUNT, name, TAG_POLICY);
|
||||
try (IamClient admin = admin(ACCOUNT);
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
|
||||
Region.US_EAST_1)) {
|
||||
admin.tagUser(r -> r.userName(name).tags(tag("Team", "platform")));
|
||||
Credentials session = sts.getSessionToken().credentials();
|
||||
try (IamClient caller = sessionClient(session)) {
|
||||
caller.listUsers();
|
||||
admin.untagUser(r -> r.userName(name).tagKeys("Team"));
|
||||
denied(caller::listUsers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void assumedRoleUsesItsOwnAccountAndTagsRatherThanTheSourceUserOrSameNamedRole() {
|
||||
String name = "principal-role-" + suffix();
|
||||
String source = "principal-source-" + suffix();
|
||||
UserCredentials keys = user(ACCOUNT, source, ALLOW_ASSUME);
|
||||
try (IamClient own = admin(ACCOUNT); IamClient other = admin(OTHER_ACCOUNT);
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
|
||||
Region.US_EAST_1)) {
|
||||
own.tagUser(r -> r.userName(source).tags(tag("Team", "source-user"), tag("Blocked", "yes")));
|
||||
role(own, ACCOUNT, name, trust(null), TAG_POLICY);
|
||||
own.tagRole(r -> r.roleName(name).tags(tag("Team", "wrong-account"), tag("Blocked", "yes")));
|
||||
String target = role(other, OTHER_ACCOUNT, name, trust(null), TAG_POLICY);
|
||||
other.tagRole(r -> r.roleName(name).tags(tag("Team", "platform")));
|
||||
Credentials session = sts.assumeRole(r -> r.roleArn(target).roleSessionName("tag-test")).credentials();
|
||||
try (IamClient caller = sessionClient(session)) {
|
||||
caller.listUsers();
|
||||
other.tagRole(r -> r.roleName(name).tags(tag("Blocked", "yes")));
|
||||
denied(caller::listUsers);
|
||||
other.untagRole(r -> r.roleName(name).tagKeys("Blocked", "Team"));
|
||||
denied(caller::listUsers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void trustPolicyReadsTheCallersTagsInsteadOfTheTargetRolesTags() {
|
||||
String name = "principal-trust-" + suffix();
|
||||
String source = "principal-truster-" + suffix();
|
||||
UserCredentials keys = user(ACCOUNT, source, ALLOW_ASSUME);
|
||||
try (IamClient admin = admin(ACCOUNT);
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
|
||||
Region.US_EAST_1)) {
|
||||
String target = role(admin, ACCOUNT, name, trust("platform"), ALLOW_ASSUME);
|
||||
admin.tagRole(r -> r.roleName(name).tags(tag("Team", "platform")));
|
||||
denied(() -> sts.assumeRole(r -> r.roleArn(target).roleSessionName("missing")));
|
||||
admin.tagUser(r -> r.userName(source).tags(tag("Team", "other")));
|
||||
denied(() -> sts.assumeRole(r -> r.roleArn(target).roleSessionName("wrong")));
|
||||
admin.tagUser(r -> r.userName(source).tags(tag("Team", "platform")));
|
||||
Credentials session = sts.assumeRole(r -> r.roleArn(target).roleSessionName("matching")).credentials();
|
||||
// A chained request sees the assumed role's tags, not the original user's tags.
|
||||
admin.tagUser(r -> r.userName(source).tags(tag("Team", "other")));
|
||||
try (StsClient chained = StsClient.builder().endpointOverride(baseUri).region(Region.US_EAST_1)
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder()).credentialsProvider(provider(session)).build()) {
|
||||
chained.assumeRole(r -> r.roleArn(target).roleSessionName("chain"));
|
||||
admin.untagRole(r -> r.roleName(name).tagKeys("Team"));
|
||||
denied(() -> chained.assumeRole(r -> r.roleArn(target).roleSessionName("untagged")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNamedUsersInDifferentAccountsKeepTheirOwnTags() {
|
||||
String name = "principal-account-" + suffix();
|
||||
UserCredentials first = user(ACCOUNT, name, TAG_POLICY);
|
||||
UserCredentials second = user(OTHER_ACCOUNT, name, TAG_POLICY);
|
||||
try (IamClient own = admin(ACCOUNT); IamClient other = admin(OTHER_ACCOUNT);
|
||||
IamClient allowed = userClient(first); IamClient refused = userClient(second)) {
|
||||
own.tagUser(r -> r.userName(name).tags(tag("Team", "platform")));
|
||||
other.tagUser(r -> r.userName(name).tags(tag("Team", "other")));
|
||||
allowed.listUsers();
|
||||
denied(refused::listUsers);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketPolicyDeniesTheTaggedCaller() {
|
||||
String bucket = "principal-bucket-" + suffix();
|
||||
String name = "principal-reader-" + suffix();
|
||||
UserCredentials keys = user(ACCOUNT, name, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}""".formatted(bucket));
|
||||
try (S3Client owner = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
|
||||
S3Client reader = AwsTestClients.create(S3Client.builder().forcePathStyle(true), keys.accessKeyId(),
|
||||
keys.secretAccessKey(), Region.US_EAST_1);
|
||||
IamClient admin = admin(ACCOUNT)) {
|
||||
owner.createBucket(r -> r.bucket(bucket));
|
||||
cleanup.register(() -> {
|
||||
try (S3Client client = AwsTestClients.create(S3Client.builder().forcePathStyle(true),
|
||||
ACCOUNT, Region.US_EAST_1)) {
|
||||
client.deleteObject(r -> r.bucket(bucket).key("key"));
|
||||
client.deleteBucket(r -> r.bucket(bucket));
|
||||
}
|
||||
});
|
||||
owner.putObject(r -> r.bucket(bucket).key("key"), RequestBody.fromString("content"));
|
||||
owner.putBucketPolicy(r -> r.bucket(bucket).policy("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*",
|
||||
"Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalTag/Blocked":"yes"}}}]}""".formatted(bucket)));
|
||||
assertEquals("content", reader.getObjectAsBytes(r -> r.bucket(bucket).key("key")).asUtf8String());
|
||||
admin.tagUser(r -> r.userName(name).tags(tag("Blocked", "yes")));
|
||||
denied(() -> reader.getObjectAsBytes(r -> r.bucket(bucket).key("key")));
|
||||
}
|
||||
}
|
||||
|
||||
private UserCredentials user(String account, String name, String policy) {
|
||||
UserCredentials keys = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(account, "iam"), name);
|
||||
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(account, "iam"), name, "principal", policy);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private String role(IamClient admin, String account, String name, String trust, String policy) {
|
||||
String arn = admin.createRole(r -> r.roleName(name).path("/teams/platform/")
|
||||
.assumeRolePolicyDocument(trust)).role().arn();
|
||||
cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), auth(account, "iam"), name));
|
||||
admin.putRolePolicy(r -> r.roleName(name).policyName("principal").policyDocument(policy));
|
||||
return arn;
|
||||
}
|
||||
|
||||
private static String trust(String team) {
|
||||
String condition = team == null ? "" : ",\"Condition\":{\"StringEquals\":{\"aws:PrincipalTag/Team\":\"" + team + "\"}}";
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"}%s}]}""".formatted(ACCOUNT, condition);
|
||||
}
|
||||
|
||||
private static IamClient admin(String account) {
|
||||
return AwsTestClients.create(IamClient.builder(), account, Region.US_EAST_1);
|
||||
}
|
||||
|
||||
private static IamClient userClient(UserCredentials keys) {
|
||||
return AwsTestClients.create(IamClient.builder(), keys.accessKeyId(), keys.secretAccessKey(), Region.US_EAST_1);
|
||||
}
|
||||
|
||||
private IamClient sessionClient(Credentials session) {
|
||||
return IamClient.builder().endpointOverride(baseUri).region(Region.US_EAST_1)
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder()).credentialsProvider(provider(session)).build();
|
||||
}
|
||||
|
||||
private static StaticCredentialsProvider provider(Credentials session) {
|
||||
return StaticCredentialsProvider.create(AwsSessionCredentials.create(
|
||||
session.accessKeyId(), session.secretAccessKey(), session.sessionToken()));
|
||||
}
|
||||
|
||||
private static void denied(Runnable operation) {
|
||||
AwsServiceException error = assertThrows(AwsServiceException.class, operation::run);
|
||||
assertEquals(403, error.statusCode());
|
||||
assertEquals("AccessDenied", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
private static Tag tag(String key, String value) {
|
||||
return Tag.builder().key(key).value(value).build();
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user