Created
October 29, 2019 14:14
-
-
Save tssm0n/b25c6105714b5555e1c30215c7954b69 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
import boto3 | |
AWS_ACCOUNT_NUMBER = "xxxxxxxxxxxxxx" | |
class TestIAMPolicy(unittest.TestCase): | |
def setUp(self): | |
# Initialize the boto3 IAM client | |
self.iam = boto3.client("iam") | |
# The ARN of the IAM role that will be tested | |
self.policy_source_arn = f'arn:aws:iam::{AWS_ACCOUNT_NUMBER}:role/BlogUserRole' | |
# Return True if the specified action is allowed on the specified resource | |
def allowed(self, response, action, resource): | |
evaluation_results = response["EvaluationResults"] | |
for result in evaluation_results: | |
if action == result["EvalActionName"] and resource == result["EvalResourceName"]: | |
return result["EvalDecision"] == "allowed" | |
return False | |
def test_s3(self): | |
resource_arn = "arn:aws:s3:::my-very-special-test-bucket/UsersFile" | |
actions = ["s3:GetObject", "s3:PutObject", "s3:PutObjectAcl"] | |
response = self.iam.simulate_principal_policy(PolicySourceArn=self.policy_source_arn, ActionNames=actions, ResourceArns=[resource_arn]) | |
self.assertTrue(self.allowed(response, "s3:GetObject", resource_arn)) | |
self.assertTrue(self.allowed(response, "s3:PutObject", resource_arn)) | |
self.assertFalse(self.allowed(response, "s3:PutObjectAcl", resource_arn)) | |
def test_ec2_without_tag(self): | |
actions = ["ec2:StartInstances", "ec2:StopInstances", "ec2:DescribeInstances", "ec2:DeleteTags"] | |
response = self.iam.simulate_principal_policy(PolicySourceArn=self.policy_source_arn, ActionNames=actions) | |
self.assertFalse(self.allowed(response, "ec2:StartInstances", "*")) | |
self.assertFalse(self.allowed(response, "ec2:StopInstances", "*")) | |
self.assertTrue(self.allowed(response, "ec2:DescribeInstances", "*")) | |
self.assertFalse(self.allowed(response, "ec2:DeleteTags", "*")) | |
def test_ec2_with_tag(self): | |
actions = ["ec2:StartInstances", "ec2:StopInstances", "ec2:DescribeInstances", "ec2:CreateTags"] | |
context_entries = [{"ContextKeyName": "ec2:resourcetag/environment", "ContextKeyValues":["development"], "ContextKeyType": "string"}] | |
response = self.iam.simulate_principal_policy(PolicySourceArn=self.policy_source_arn, ActionNames=actions, ContextEntries=context_entries) | |
self.assertTrue(self.allowed(response, "ec2:StartInstances", "*")) | |
self.assertTrue(self.allowed(response, "ec2:StopInstances", "*")) | |
self.assertFalse(self.allowed(response, "ec2:CreateTags", "*")) | |
if __name__ == '__main__': | |
unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment