下面列出了com.amazonaws.auth.policy.conditions.ConditionFactory#com.amazonaws.auth.policy.Principal 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testGetAssumeRolePolicyDocument() throws IOException {
String assumeRolePolicyDocument = awsIamService.getResourceFileAsString(
"json/aws-assume-role-policy-document.json");
String encodedAssumeRolePolicyDocument = URLEncoder.encode(assumeRolePolicyDocument,
StandardCharsets.UTF_8);
Statement statement = new Statement(Effect.Allow).withId("1")
.withPrincipals(new Principal("AWS", "arn:aws:iam::123456890:role/assume-role"))
.withActions(SecurityTokenServiceActions.AssumeRole);
Policy expectedAssumeRolePolicy = new Policy().withStatements(statement);
Role role = mock(Role.class);
when(role.getAssumeRolePolicyDocument()).thenReturn(encodedAssumeRolePolicyDocument);
Policy assumeRolePolicy = awsIamService.getAssumeRolePolicy(role);
assertThat(assumeRolePolicy).isNotNull();
assertThat(assumeRolePolicy.toJson()).isEqualTo(expectedAssumeRolePolicy.toJson());
}
protected Policy allowSendMessagePolicy(String roleARN) {
Policy policy = new Policy();
Statement statement = new Statement(Statement.Effect.Allow);
statement.setActions(Collections.singletonList(SQSActions.SendMessage));
statement.setPrincipals(new Principal(roleARN));
statement.setResources(Collections.singletonList(new Resource("arn:aws:sqs:*:*:*")));
policy.setStatements(Collections.singletonList(statement));
return policy;
}
private String getPolicy(List<String> accountIds) {
Policy policy = new Policy("AuthorizedWorkerAccessPolicy");
Statement stmt = new Statement(Effect.Allow);
Action action = SQSActions.SendMessage;
stmt.getActions().add(action);
stmt.setResources(new LinkedList<>());
for(String accountId : accountIds) {
Principal principal = new Principal(accountId);
stmt.getPrincipals().add(principal);
}
stmt.getResources().add(new Resource(getQueueARN()));
policy.getStatements().add(stmt);
return policy.toJson();
}
public static String getPublicReadPolicy(String bucket_name) {
Policy bucket_policy = new Policy().withStatements(
new Statement(Statement.Effect.Allow)
.withPrincipals(Principal.AllUsers)
.withActions(S3Actions.GetObject)
.withResources(new Resource(
"arn:aws:s3:::" + bucket_name + "/*")));
return bucket_policy.toJson();
}
/**
* For retrieving vault inventory. For initializing SQS for determining when
* job completed. Does nothing if member snsTopicName is null. Sets members
* sqsQueueURL, sqsQueueARN, and sqsClient.
*/
private void setupSQS() {
// If no sqsQueueName setup then simply return
if (sqsQueueName == null)
return;
CreateQueueRequest request = new CreateQueueRequest()
.withQueueName(sqsQueueName);
CreateQueueResult result = sqsClient.createQueue(request);
sqsQueueURL = result.getQueueUrl();
GetQueueAttributesRequest qRequest = new GetQueueAttributesRequest()
.withQueueUrl(sqsQueueURL).withAttributeNames("QueueArn");
GetQueueAttributesResult qResult = sqsClient
.getQueueAttributes(qRequest);
sqsQueueARN = qResult.getAttributes().get("QueueArn");
Policy sqsPolicy = new Policy().withStatements(new Statement(
Effect.Allow).withPrincipals(Principal.AllUsers)
.withActions(SQSActions.SendMessage)
.withResources(new Resource(sqsQueueARN)));
Map<String, String> queueAttributes = new HashMap<String, String>();
queueAttributes.put("Policy", sqsPolicy.toJson());
sqsClient.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueURL,
queueAttributes));
}
private TemporaryQueue createQueue(String snsTopicArn, String sqsQueueArn, String sqsQueueName) {
String sqsQueueUrl =
amazonSQS
.createQueue(
new CreateQueueRequest()
.withQueueName(sqsQueueName)
.withAttributes(
Collections.singletonMap(
"MessageRetentionPeriod", "60")) // 60s message retention
)
.getQueueUrl();
log.info("Created Temporary S3 Notification Queue: {}", value("queue", sqsQueueUrl));
String snsTopicSubscriptionArn =
amazonSNS.subscribe(snsTopicArn, "sqs", sqsQueueArn).getSubscriptionArn();
Statement snsStatement =
new Statement(Statement.Effect.Allow).withActions(SQSActions.SendMessage);
snsStatement.setPrincipals(Principal.All);
snsStatement.setResources(Collections.singletonList(new Resource(sqsQueueArn)));
snsStatement.setConditions(
Collections.singletonList(
new Condition()
.withType("ArnEquals")
.withConditionKey("aws:SourceArn")
.withValues(snsTopicArn)));
Policy allowSnsPolicy = new Policy("allow-sns", Collections.singletonList(snsStatement));
HashMap<String, String> attributes = new HashMap<>();
attributes.put("Policy", allowSnsPolicy.toJson());
amazonSQS.setQueueAttributes(sqsQueueUrl, attributes);
return new TemporaryQueue(snsTopicArn, sqsQueueArn, sqsQueueUrl, snsTopicSubscriptionArn);
}
@Test
public void ec2NotInPrincipals() {
assertThat(awsInstanceProfileEC2TrustValidator.checkEC2InPrincipals(
Collections.singletonList(Principal.All))).isFalse();
assertThat(awsInstanceProfileEC2TrustValidator.checkEC2InPrincipals(
Collections.singletonList(Principal.AllServices))).isFalse();
assertThat(awsInstanceProfileEC2TrustValidator.checkEC2InPrincipals(
Collections.singletonList(new Principal("Service", "invalid")))).isFalse();
assertThat(awsInstanceProfileEC2TrustValidator.checkEC2InPrincipals(
Arrays.asList(
Principal.All,
Principal.AllServices,
new Principal("Service", "invalid")
))).isFalse();
}
@Test
public void ec2InPrincipals() {
assertThat(awsInstanceProfileEC2TrustValidator.checkEC2InPrincipals(Collections.singletonList(
new Principal("Service", Services.AmazonEC2.getServiceId())))).isTrue();
assertThat(awsInstanceProfileEC2TrustValidator.checkEC2InPrincipals(
Arrays.asList(
Principal.AllServices,
new Principal("Service", Services.AmazonEC2.getServiceId())
))).isTrue();
}
private Policy getTrustedPolicy() {
return new Policy().withStatements(
new Statement(Effect.Allow)
.withActions(SecurityTokenServiceActions.AssumeRole)
.withPrincipals(new Principal("Service", Services.AmazonEC2.getServiceId()))
);
}
@Test
public void
test_that_filterKeysCreatedByKmsService_filters_out_keys_that_do_not_contain_expected_arn_prefix() {
Policy policyThatShouldBeInSet =
new Policy()
.withStatements(
new Statement(Statement.Effect.Allow)
.withId(CERBERUS_MANAGEMENT_SERVICE_SID)
.withPrincipals(
new Principal("arn:aws:iam:123456:role/" + ENV + "-cms-role-alk234khsdf")),
new Statement(Statement.Effect.Allow),
new Statement(Statement.Effect.Allow),
new Statement(Statement.Effect.Allow));
Policy policyThatShouldNotBeInSet =
new Policy()
.withStatements(
new Statement(Statement.Effect.Allow)
.withId(CERBERUS_MANAGEMENT_SERVICE_SID)
.withPrincipals(
new Principal("arn:aws:iam:123456:role/prod-cms-role-alk234khsdf")),
new Statement(Statement.Effect.Allow),
new Statement(Statement.Effect.Allow),
new Statement(Statement.Effect.Allow));
Policy policyThatWasntCreatedByCms =
new Policy()
.withStatements(
new Statement(Statement.Effect.Allow)
.withId("foo-bar")
.withPrincipals(
new Principal("arn:aws:iam:123456:role/" + ENV + "-cms-role-alk234khsdf")));
KmsService kmsServiceSpy = spy(kmsService);
Set<String> allKmsCmkIdsForRegion = ImmutableSet.of("key1", "key2", "key3", "key4", "key5");
String region = "us-west-2";
Set<String> expectedKeys = ImmutableSet.of("key3");
doReturn(Optional.of(policyThatShouldNotBeInSet))
.when(kmsServiceSpy)
.downloadPolicy("key1", region, 0);
doReturn(Optional.of(policyThatShouldNotBeInSet))
.when(kmsServiceSpy)
.downloadPolicy("key2", region, 0);
doReturn(Optional.of(policyThatShouldBeInSet))
.when(kmsServiceSpy)
.downloadPolicy("key3", region, 0);
doReturn(Optional.of(policyThatShouldNotBeInSet))
.when(kmsServiceSpy)
.downloadPolicy("key4", region, 0);
doReturn(Optional.of(policyThatWasntCreatedByCms))
.when(kmsServiceSpy)
.downloadPolicy("key5", region, 0);
Set<String> actual = kmsServiceSpy.filterKeysCreatedByKmsService(allKmsCmkIdsForRegion, region);
assertEquals(expectedKeys, actual);
}
public void connectToTopic(boolean callerIsMaster, int maxAttempts, String userAccountPrincipalId, String userARN) throws Exception {
// try up to max attempts to connect to pre-existing topic
for (int i=0; i<maxAttempts; i++) {
logger.debug("connectToTopic() attempt: " + (i+1));
ListTopicsResult listResult = snsClient.listTopics();
List<Topic> topics = listResult.getTopics();
while(topics != null) {
for (Topic topic : topics) {
// note we do index of match....
if (topic.getTopicArn().indexOf(snsControlTopicName) != -1) {
snsTopicARN = topic.getTopicArn();
logger.info("Found existing SNS topic by name: "+snsControlTopicName + " @ " + snsTopicARN);
break;
}
}
String nextToken = listResult.getNextToken();
if (nextToken != null && snsTopicARN == null) {
listResult = snsClient.listTopics(nextToken);
topics = listResult.getTopics();
} else {
break;
}
}
// if consumer, retry, otherwise is master, so just exit quick to create...
if (snsTopicARN == null && !callerIsMaster) {
Thread.currentThread().sleep(1000);
continue;
} else {
break; // exit;
}
}
// if master only he can create...
if (snsTopicARN == null && callerIsMaster) {
this.snsControlTopicName = this.snsControlTopicName.substring(0,(snsControlTopicName.length() > 80 ? 80 : this.snsControlTopicName.length()));
logger.info("Attempting to create new SNS control channel topic by name: "+this.snsControlTopicName);
CreateTopicResult createTopicResult = snsClient.createTopic(this.snsControlTopicName);
snsTopicARN = createTopicResult.getTopicArn();
snsClient.addPermission(snsTopicARN, "Permit_SNSAdd",
Arrays.asList(new String[]{userARN}),
Arrays.asList(new String[]{"Publish","Subscribe","Receive"}));
logger.info("Created new SNS control channel topic by name: "+this.snsControlTopicName + " @ " + snsTopicARN);
} else if (snsTopicARN == null) {
throw new Exception("Worker() cannot start, snsControlTopicName has yet to be created by master?: " + this.snsControlTopicName);
}
// http://www.jorgjanke.com/2013/01/aws-sns-topic-subscriptions-with-sqs.html
// create SQS queue to get SNS notifications (max 80 len)
String prefix = ("s3bktLoaderCC_" + mySourceIdentifier);
String sqsQueueName = prefix.substring(0,(prefix.length() > 80 ? 80 : prefix.length()));
CreateQueueResult createQueueResult = sqsClient.createQueue(sqsQueueName);
this.sqsQueueUrl = createQueueResult.getQueueUrl();
this.sqsQueueARN = sqsClient.getQueueAttributes(sqsQueueUrl, Arrays.asList(new String[]{"QueueArn"})).getAttributes().get("QueueArn");
Statement statement = new Statement(Effect.Allow)
.withActions(SQSActions.SendMessage)
.withPrincipals(new Principal("*"))
.withConditions(ConditionFactory.newSourceArnCondition(snsTopicARN))
.withResources(new Resource(sqsQueueARN));
Policy policy = new Policy("SubscriptionPermission").withStatements(statement);
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("Policy", policy.toJson());
SetQueueAttributesRequest request = new SetQueueAttributesRequest(sqsQueueUrl, attributes);
sqsClient.setQueueAttributes(request);
logger.info("Created SQS queue: " + sqsQueueARN + " @ " + sqsQueueUrl);
// subscribe our SQS queue to the SNS:s3MountTest topic
SubscribeResult subscribeResult = snsClient.subscribe(snsTopicARN,"sqs",sqsQueueARN);
snsSubscriptionARN = subscribeResult.getSubscriptionArn();
logger.info("Subscribed for messages from SNS control channel:" + snsTopicARN + " ----> SQS: "+sqsQueueARN);
logger.info("Subscription ARN: " + snsSubscriptionARN);
this.consumerThread = new Thread(this,"ControlChannel msg consumer thread");
this.consumerThread.start();
logger.info("\n-------------------------------------------\n" +
"CONTROL CHANNEL: ALL SNS/SQS resources hooked up OK\n" +
"-------------------------------------------\n");
}
boolean checkEC2InPrincipals(List<Principal> principals) {
return principals
.stream()
.anyMatch(principal -> "Service".equals(principal.getProvider())
&& Services.AmazonEC2.getServiceId().equals(principal.getId()));
}