diff --git a/AUTHORS.md b/AUTHORS.md index 82f0313e6..0c7b081ad 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -62,3 +62,4 @@ Moto is written by Steve Pulec with contributions from: * [Ariel Beck](https://github.com/arielb135) * [Roman Rader](https://github.com/rrader/) * [Bryan Chen](https://github.com/bchen1116) +* [Jonas Bulik](https://github.com/MrGreenTea) diff --git a/moto/iot/models.py b/moto/iot/models.py index b377a4eac..1c79656e1 100644 --- a/moto/iot/models.py +++ b/moto/iot/models.py @@ -992,6 +992,13 @@ class IoTBackend(BaseBackend): cert.status = new_status def create_policy(self, policy_name, policy_document): + if policy_name in self.policies: + current_policy = self.policies[policy_name] + raise ResourceAlreadyExistsException( + f"Policy cannot be created - name already exists (name={policy_name})", + current_policy.name, + current_policy.arn, + ) policy = FakePolicy(policy_name, policy_document, self.region_name) self.policies[policy.name] = policy return policy diff --git a/tests/test_iot/test_iot_policies.py b/tests/test_iot/test_iot_policies.py index 6f9657bd4..42592fa96 100644 --- a/tests/test_iot/test_iot_policies.py +++ b/tests/test_iot/test_iot_policies.py @@ -414,3 +414,24 @@ def test_list_targets_for_policy_resource_not_found(iot_client): e.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") e.value.response["Error"]["Message"].should.contain("Policy not found") + + +def test_create_policy_fails_when_name_taken(iot_client, policy): + policy_name = policy["policyName"] + + with pytest.raises(ClientError) as e: + iot_client.create_policy( + policyName=policy_name, + policyDocument='{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}', + ) + + current_policy = iot_client.get_policy(policyName=policy_name) + e.value.response["Error"]["Code"].should.equal("ResourceAlreadyExistsException") + e.value.response["Error"]["Message"].should.equal( + f"Policy cannot be created - name already exists (name={policy_name})" + ) + + # the policy should not have been overwritten + current_policy.should.have.key("policyDocument").which.should.equal( + policy["policyDocument"] + )