From 02a7e272e9f23516dd5a9802abd3871c1d09bb93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Caparr=C3=B3s?= <30770801+acapagarcia@users.noreply.github.com> Date: Thu, 11 Nov 2021 11:32:58 +0100 Subject: [PATCH] Search cognito identities from iot moto backend (#4555) --- moto/iot/models.py | 15 ++++++++++++--- tests/test_iot/test_iot.py | 27 ++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/moto/iot/models.py b/moto/iot/models.py index 2d29bb498..b3b9b35da 100644 --- a/moto/iot/models.py +++ b/moto/iot/models.py @@ -913,9 +913,18 @@ class IoTBackend(BaseBackend): raise ResourceNotFoundException() principal = certs[0] return principal - else: - # TODO: search for cognito_ids - pass + from moto.cognitoidentity import cognitoidentity_backends + + cognito = cognitoidentity_backends[self.region_name] + identities = [] + for identity_pool in cognito.identity_pools: + pool_identities = cognito.pools_identities.get(identity_pool, None) + identities.extend( + [pi["IdentityId"] for pi in pool_identities.get("Identities", [])] + ) + if principal_arn in identities: + return {"IdentityId": principal_arn} + raise ResourceNotFoundException() def attach_principal_policy(self, policy_name, principal_arn): diff --git a/tests/test_iot/test_iot.py b/tests/test_iot/test_iot.py index 46b97dee9..4a1c3a1e9 100644 --- a/tests/test_iot/test_iot.py +++ b/tests/test_iot/test_iot.py @@ -2,7 +2,7 @@ import json import sure # noqa # pylint: disable=unused-import import boto3 -from moto import mock_iot +from moto import mock_iot, mock_cognitoidentity from botocore.exceptions import ClientError import pytest @@ -55,6 +55,31 @@ def test_attach_policy(): res["policies"][0]["policyName"].should.equal("my-policy") +@mock_iot +@mock_cognitoidentity +def test_attach_policy_to_identity(): + region = "ap-northeast-1" + + cognito_identity_client = boto3.client("cognito-identity", region_name=region) + identity_pool_name = "test_identity_pool" + identity_pool = cognito_identity_client.create_identity_pool( + IdentityPoolName=identity_pool_name, AllowUnauthenticatedIdentities=True + ) + identity = cognito_identity_client.get_id( + AccountId="test", IdentityPoolId=identity_pool["IdentityPoolId"] + ) + + client = boto3.client("iot", region_name=region) + policy_name = "my-policy" + doc = "{}" + client.create_policy(policyName=policy_name, policyDocument=doc) + client.attach_policy(policyName=policy_name, target=identity["IdentityId"]) + + res = client.list_attached_policies(target=identity["IdentityId"]) + res.should.have.key("policies").which.should.have.length_of(1) + res["policies"][0]["policyName"].should.equal(policy_name) + + @mock_iot def test_detach_policy(): client = boto3.client("iot", region_name="ap-northeast-1")