From 422bca8e9018694d2e201944a422bb70b1855f95 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Mon, 11 Nov 2019 08:21:42 +0000 Subject: [PATCH] IAM - Add Validation on duplicate role names --- moto/iam/models.py | 4 ++++ tests/test_iam/test_iam.py | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/moto/iam/models.py b/moto/iam/models.py index b64c9402f..3e744f6a7 100644 --- a/moto/iam/models.py +++ b/moto/iam/models.py @@ -898,6 +898,10 @@ class IAMBackend(BaseBackend): permissions_boundary ), ) + if [role for role in self.get_roles() if role.name == role_name]: + raise EntityAlreadyExists( + "Role with name {0} already exists.".format(role_name) + ) clean_tags = self._tag_verification(tags) role = Role( diff --git a/tests/test_iam/test_iam.py b/tests/test_iam/test_iam.py index c5e856b68..5146f891c 100644 --- a/tests/test_iam/test_iam.py +++ b/tests/test_iam/test_iam.py @@ -18,6 +18,7 @@ from nose.tools import raises from datetime import datetime from tests.helpers import requires_boto_gte +from uuid import uuid4 MOCK_CERT = """-----BEGIN CERTIFICATE----- @@ -2050,6 +2051,26 @@ def test_create_role_with_permissions_boundary(): conn.list_roles().get("Roles")[0].get("PermissionsBoundary").should.equal(expected) +@mock_iam +def test_create_role_with_same_name_should_fail(): + iam = boto3.client("iam", region_name="us-east-1") + test_role_name = str(uuid4()) + iam.create_role( + RoleName=test_role_name, AssumeRolePolicyDocument="policy", Description="test" + ) + # Create the role again, and verify that it fails + with assert_raises(ClientError) as err: + iam.create_role( + RoleName=test_role_name, + AssumeRolePolicyDocument="policy", + Description="test", + ) + err.exception.response["Error"]["Code"].should.equal("EntityAlreadyExists") + err.exception.response["Error"]["Message"].should.equal( + "Role with name {0} already exists.".format(test_role_name) + ) + + @mock_iam def test_create_open_id_connect_provider(): client = boto3.client("iam", region_name="us-east-1")