def test_post_new_profile_with_uuid_should_fail(self, fake_jwks):
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis-verify.ini"
        os.environ["CIS_STREAM_BYPASS"] = "******"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        from cis_change_service import api

        f = FakeBearer()
        user_profile = FakeUser(config=FakeProfileConfig().minimal())
        user_profile.uuid.value = "something"
        fake_jwks.return_value = json_form_of_pk
        token = f.generate_bearer_without_scope()
        api.app.testing = True
        self.app = api.app.test_client()
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(user_profile.as_dict()),
            content_type="application/json",
            follow_redirects=True,
        )

        results = json.loads(result.get_data())
        expected_result = {
            "code":
            "uuid_or_primary_username_set",
            "description":
            "The fields primary_username or uuid have been set in a new profile.",
        }

        assert result.status_code == 403
        assert results == expected_result
Ejemplo n.º 2
0
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "purple"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        self.vault_client = vault.IdentityVault()
        self.vault_client.connect()
        self.vault_client.find_or_create()

        self.user_profile = FakeUser().as_dict()
        self.user_profile["active"]["value"] = True
        self.uuid = self.user_profile["uuid"]["value"]
        self.vault_json_datastructure = {
            "id":
            self.user_profile.get("user_id").get("value"),
            "user_uuid":
            self.uuid,
            "primary_email":
            self.user_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(self.user_profile),
            "active":
            True,
        }
        self.boto_session = boto3.session.Session(region_name="us-east-1")
        self.dynamodb_resource = self.boto_session.resource("dynamodb")
        self.dynamodb_client = self.boto_session.client("dynamodb")
        self.table = self.dynamodb_resource.Table("purple-identity-vault")
Ejemplo n.º 3
0
 def _generate_fake_users(self):
     users = []
     for i in range(0, 10):
         cis_profile_object = FakeUser()
         user_profile = cis_profile_object.as_dict()
         users.append({
             "id":
             user_profile["user_id"]["value"],
             "user_uuid":
             user_profile["uuid"]["value"],
             "profile":
             json.dumps(user_profile),
             "primary_email":
             user_profile["primary_email"]["value"],
             "primary_username":
             user_profile["primary_username"]["value"],
             "sequence_number":
             str(uuid.uuid4().int),
             "active":
             user_profile["active"]["value"],
             "flat_profile": {
                 k: self.deserializer.deserialize(v)
                 for k, v in
                 cis_profile_object.as_dynamo_flat_dict().items()
             },
         })
     self.users = users
    def test_post_profiles_it_should_fail(self, fake_jwks):
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis-verify.ini"
        os.environ["CIS_STREAM_BYPASS"] = "******"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        from cis_change_service import api

        f = FakeBearer()
        user_profile = FakeUser(config=FakeProfileConfig().minimal())
        user_profile.first_name.signature.publisher.name = "cis"
        user_profile.first_name.value = "Something"
        fake_jwks.return_value = json_form_of_pk
        token = f.generate_bearer_without_scope()
        api.app.testing = True
        self.app = api.app.test_client()
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(user_profile.as_dict()),
            content_type="application/json",
            follow_redirects=True,
        )

        results = json.loads(result.get_data())
        expected_result = {
            "code":
            "invalid_publisher",
            "description":
            "[create] cis is NOT allowed to publish field first_name",
        }

        assert result.status_code == 403
        assert results == expected_result
Ejemplo n.º 5
0
    def setup(self):
        self.patcher_salt = mock.patch(
            "cis_crypto.secret.AWSParameterstoreProvider.uuid_salt")
        self.patcher_salt = self.patcher_salt.start()
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        self.dynalite_port = str(random.randint(32000, 34000))
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        self.dynaliteprocess = subprocess.Popen(
            [
                "/usr/sbin/java",
                "-Djava.library.path=/opt/dynamodb_local/DynamoDBLocal_lib",
                "-jar",
                "/opt/dynamodb_local/DynamoDBLocal.jar",
                "-inMemory",
                "-port",
                self.dynalite_port,
            ],
            preexec_fn=os.setsid,
        )
        from cis_identity_vault import vault

        v = vault.IdentityVault()
        v.connect()
        v.create()
        user_profile = FakeUser(config=FakeProfileConfig().minimal())
        self.user_profile = user_profile.as_json()
        self.user_profile_dict = user_profile.as_dict()
Ejemplo n.º 6
0
    def test_partial_update_it_should_fail(self, fake_jwks):
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["AWS_ACCESS_KEY_ID"] = "foo"
        os.environ["AWS_SECRET_ACCESS_KEY"] = "bar"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"
        from cis_change_service import api

        fake_new_user = FakeUser(config=FakeProfileConfig().minimal())
        # Create a brand new user
        patched_user_profile = ensure_appropriate_publishers_and_sign(
            fake_new_user.as_dict(), self.publisher_rules, "create")

        f = FakeBearer()
        fake_jwks.return_value = json_form_of_pk
        token = f.generate_bearer_without_scope()
        api.app.testing = True
        self.app = api.app.test_client()
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(patched_user_profile.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )

        response = json.loads(result.get_data())
        assert result.status_code == 200
        assert response["condition"] == "create"

        logger.info("A stub user has been created and verified to exist.")

        logger.info("Attempting failing partial update.")
        null_profile = profile.User(user_structure_json=None)
        null_profile.alternative_name.value = "iamanewpreferredlastname"
        null_profile.sign_attribute("alternative_name", "mozilliansorg")
        null_profile.user_id.value = "ad|wrong|LDAP"
        null_profile.active.value = True
        null_profile.sign_attribute("active", "access_provider")

        result = self.app.post(
            "/v2/user?user_id={}".format("mismatching_user_id"),
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(null_profile.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )
        response = json.loads(result.get_data())
        assert result.status_code == 400
    def test_rewrite(self):
        from cis_change_service import profile

        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis-verify.ini"

        v = profile.Vault()
        u = FakeUser()
        u.active.value = False
        u.active.signature.publisher.name = "ldap"
        u.sign_attribute("active", "ldap")
        ud = v._update_attr_owned_by_cis(u.user_id.value, u)
        assert ud.active.signature.publisher.name == "cis"
Ejemplo n.º 8
0
    def test_partial_update_it_should_succeed(self, fake_jwks):
        os.environ["CIS_STREAM_BYPASS"] = "******"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_VERIFY_PUBLISHERS"] = "true"
        from cis_change_service import api

        fake_new_user = FakeUser(config=FakeProfileConfig().minimal())
        # Create a brand new user
        patched_user_profile = ensure_appropriate_publishers_and_sign(
            fake_new_user.as_dict(), self.publisher_rules, "create")

        f = FakeBearer()
        fake_jwks.return_value = json_form_of_pk
        token = f.generate_bearer_without_scope()
        api.app.testing = True
        self.app = api.app.test_client()
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(patched_user_profile.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )

        response = json.loads(result.get_data())
        assert result.status_code == 200
        assert response["condition"] == "create"

        logger.info("A stub user has been created and verified to exist.")
        logger.info("Attempting partial update.")

        # Now let's try a partial update :)
        null_profile = profile.User(user_structure_json=None)
        null_profile.active.value = True
        null_profile.sign_attribute("active", "access_provider")
        null_profile.last_name.value = "iamanewpreferredlastname"
        null_profile.sign_attribute("last_name", "mozilliansorg")

        result = self.app.post(
            "/v2/user?user_id={}".format(patched_user_profile.user_id.value),
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(null_profile.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )
        logger.info(result.get_data())
        response = json.loads(result.get_data())
        assert result.status_code == 200
        assert response["condition"] == "update"
Ejemplo n.º 9
0
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "testing"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"

        # Mock a user profile using the faker to send to the database.
        self.user_profile = FakeUser().as_dict()
    def test_post_profiles_and_retrieving_status_it_should_succeed(
            self, fake_jwks):
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        from cis_change_service import api

        f = FakeBearer()
        fake_jwks.return_value = json_form_of_pk
        profiles = []
        for x in range(0, 10):
            profiles.append(FakeUser().as_json())
        token = f.generate_bearer_without_scope()
        api.app.testing = True
        self.app = api.app.test_client()
        result = self.app.post(
            "/v2/users",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(profiles),
            content_type="application/json",
            follow_redirects=True,
        )

        results = json.loads(result.get_data())
        assert results is not None
Ejemplo n.º 11
0
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "purple"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"
        self.vault_client = vault.IdentityVault()
        self.vault_client.connect()
        self.vault_client.find_or_create()
        self.boto_session = boto3.session.Session(region_name="us-east-1")
        self.dynamodb_resource = self.boto_session.resource("dynamodb")
        self.dynamodb_client = self.boto_session.client("dynamodb")
        self.table = self.dynamodb_resource.Table("purple-identity-vault")

        for x in range(0, 50):  # Must generate 50 users to test paginator
            user_profile = FakeUser().as_dict()
            user_profile["active"]["value"] = True
            uuid = user_profile["uuid"]["value"]
            vault_json_datastructure = {
                "id":
                user_profile.get("user_id").get("value"),
                "user_uuid":
                uuid,
                "primary_email":
                user_profile.get("primary_email").get("value"),
                "primary_username":
                user_profile.get("primary_username").get("value"),
                "sequence_number":
                "12345678",
                "profile":
                json.dumps(user_profile),
                "active":
                True,
            }
            from cis_identity_vault.models import user

            profile = user.Profile(self.table,
                                   self.dynamodb_client,
                                   transactions=False)
            profile.create(vault_json_datastructure)

        self.user_profile = FakeUser().as_dict()
        self.user_profile["active"]["value"] = True
        self.uuid = self.user_profile["uuid"]["value"]
        self.vault_json_datastructure = {
            "id":
            self.user_profile.get("user_id").get("value"),
            "user_uuid":
            self.uuid,
            "primary_email":
            self.user_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(self.user_profile),
            "active":
            True,
        }
Ejemplo n.º 12
0
    def setup(self):
        self.dynalite_port = str(random.randint(32000, 34000))
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        os.environ["CIS_REGION_NAME"] = "us-west-2"
        os.environ["AWS_ACCESS_KEY_ID"] = "foo"
        os.environ["AWS_SECRET_ACCESS_KEY"] = "bar"
        from cis_identity_vault import vault
        from cis_change_service.common import get_config

        self.patcher_salt = mock.patch(
            "cis_crypto.secret.AWSParameterstoreProvider.uuid_salt")
        self.mock_salt = self.patcher_salt.start()

        config = get_config()
        os.environ["CIS_DYNALITE_PORT"] = str(random.randint(32000, 34000))
        self.dynalite_port = config("dynalite_port", namespace="cis")
        self.dynaliteprocess = subprocess.Popen(
            [
                "/usr/sbin/java",
                "-Djava.library.path=/opt/dynamodb_local/DynamoDBLocal_lib",
                "-jar",
                "/opt/dynamodb_local/DynamoDBLocal.jar",
                "-inMemory",
                "-port",
                self.dynalite_port,
            ],
            preexec_fn=os.setsid,
        )
        v = vault.IdentityVault()
        v.connect()
        v.create()

        user_profile = FakeUser(config=FakeProfileConfig().minimal())
        self.user_profile = user_profile.as_json()
        from cis_change_service import api

        api.app.testing = True
        self.app = api.app.test_client()
        self.publisher_rules = common.WellKnown().get_publisher_rules()
        self.complex_structures = get_complex_structures()
Ejemplo n.º 13
0
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "testing"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"
        os.environ["CIS_POSTGRES_HOST"] = "db"
        os.environ["CIS_POSTGRES_PORT"] = "5432"
        os.environ["CIS_DB_USER"] = "******"
        os.environ["CIS_DB_PASSWORD"] = "******"

        # Mock a user profile using the faker to send to the database.
        self.user_profile = FakeUser().as_dict()
Ejemplo n.º 14
0
    def test_user_find(self):
        from cis_identity_vault import vault
        from cis_identity_vault.models import user

        v = vault.RelationalIdentityVault()
        v.create()
        u = user.ProfileRDS()
        res = u.create(user_profile=self.user_profile)
        positive_search_result = u.find(self.user_profile)
        assert positive_search_result is not None
        non_existant_user = FakeUser().as_dict()
        negative_search_result = u.find(non_existant_user)
        assert negative_search_result is None
        u.delete(user_profile=self.user_profile)
        assert res is not None
Ejemplo n.º 15
0
    def test_user_find(self):
        os.environ["CIS_POSTGRES_HOST"] = "db"
        os.environ["CIS_POSTGRES_PORT"] = "5432"
        os.environ["CIS_DB_USER"] = "******"
        os.environ["CIS_DB_PASSWORD"] = "******"
        from cis_identity_vault import vault
        from cis_identity_vault.models import user

        v = vault.RelationalIdentityVault()
        v.create()
        u = user.ProfileRDS()
        res = u.create(user_profile=self.user_profile)
        positive_search_result = u.find(self.user_profile)
        assert positive_search_result is not None
        non_existant_user = FakeUser().as_dict()
        negative_search_result = u.find(non_existant_user)
        assert negative_search_result is None
        u.delete(user_profile=self.user_profile)
        assert res is not None
        v.delete()
Ejemplo n.º 16
0
class TestUsersDynalite(object):
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "purple"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        self.vault_client = vault.IdentityVault()
        self.vault_client.connect()
        self.vault_client.find_or_create()

        self.user_profile = FakeUser().as_dict()
        self.user_profile["active"]["value"] = True
        self.uuid = self.user_profile["uuid"]["value"]
        self.vault_json_datastructure = {
            "id":
            self.user_profile.get("user_id").get("value"),
            "user_uuid":
            self.uuid,
            "primary_email":
            self.user_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(self.user_profile),
            "active":
            True,
        }
        self.boto_session = boto3.session.Session(region_name="us-east-1")
        self.dynamodb_resource = self.boto_session.resource("dynamodb")
        self.dynamodb_client = self.boto_session.client("dynamodb")
        self.table = self.dynamodb_resource.Table("purple-identity-vault")

    def test_create_method(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.create(self.vault_json_datastructure)
        assert result is not None

    def test_update_method(self):
        from cis_identity_vault.models import user

        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = "*****@*****.**"
        modified_profile["active"]["value"] = True
        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.update(vault_json_datastructure)
        assert result is not None

    def test_find_user(self):
        from cis_identity_vault.models import user

        primary_email = "*****@*****.**"
        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = primary_email
        modified_profile["active"]["value"] = True
        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure)

        profile = user.Profile(self.table)
        user_id = self.user_profile.get("user_id").get("value")
        result_for_user_id = profile.find_by_id(user_id)
        result_for_email = profile.find_by_email(primary_email)
        assert result_for_user_id is not None
        assert result_for_email is not None

    def test_find_user_multi_id_for_email(self):
        from cis_identity_vault.models import user

        primary_email = "*****@*****.**"
        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = primary_email
        modified_profile["active"]["value"] = True
        vault_json_datastructure_first_id = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure_first_id)

        vault_json_datastructure_second_id = {
            "id":
            "foo|mcbar",
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile.update(vault_json_datastructure_second_id)

        profile = user.Profile(self.table)
        self.user_profile.get("user_id").get("value")
        result_for_email = profile.find_by_email(primary_email)
        assert result_for_email is not None
        assert len(result_for_email.get("Items")) > 2

    def test_find_user_multi_id_for_username(self):
        from cis_identity_vault.models import user

        primary_username = "******"
        modified_profile = self.user_profile
        modified_profile["primary_username"]["value"] = primary_username
        modified_profile["active"]["value"] = False
        vault_json_datastructure_first_id = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure_first_id)

        vault_json_datastructure_second_id = {
            "id":
            "foo|mcbar",
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile.update(vault_json_datastructure_second_id)

        profile = user.Profile(self.table)
        self.user_profile.get("user_id").get("value")
        result_for_username = profile.find_by_username(primary_username)
        assert result_for_username is not None
        assert len(result_for_username.get("Items")) == 2

    def test_find_by_uuid(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        user = json.loads(profile.all[0].get("profile"))

        result_for_uuid = profile.find_by_uuid(user["uuid"]["value"])
        assert len(result_for_uuid.get("Items")) > 0

    def test_find_by_username(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        user = json.loads(profile.all[0].get("profile"))

        result_for_username = profile.find_by_username(
            user["primary_username"]["value"])
        assert len(result_for_username.get("Items")) > 0

    def test_all_by_filter(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.all_filtered(connection_method="email")
        assert len(result) > 0

        result = profile.all_filtered(connection_method="email", active=True)
        assert len(result) > 0
        for record in result:
            assert record["active"]["BOOL"] is True

        result = profile.all_filtered(connection_method="email", active=False)
        for record in result:
            assert record["active"]["BOOL"] is False
Ejemplo n.º 17
0
class TestUsersDynalite(object):
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "purple"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"
        self.vault_client = vault.IdentityVault()
        self.vault_client.connect()
        self.vault_client.find_or_create()
        self.boto_session = boto3.session.Session(region_name="us-east-1")
        self.dynamodb_resource = self.boto_session.resource("dynamodb")
        self.dynamodb_client = self.boto_session.client("dynamodb")
        self.table = self.dynamodb_resource.Table("purple-identity-vault")

        for x in range(0, 50):  # Must generate 50 users to test paginator
            user_profile = FakeUser().as_dict()
            user_profile["active"]["value"] = True
            uuid = user_profile["uuid"]["value"]
            vault_json_datastructure = {
                "id":
                user_profile.get("user_id").get("value"),
                "user_uuid":
                uuid,
                "primary_email":
                user_profile.get("primary_email").get("value"),
                "primary_username":
                user_profile.get("primary_username").get("value"),
                "sequence_number":
                "12345678",
                "profile":
                json.dumps(user_profile),
                "active":
                True,
            }
            from cis_identity_vault.models import user

            profile = user.Profile(self.table,
                                   self.dynamodb_client,
                                   transactions=False)
            profile.create(vault_json_datastructure)

        self.user_profile = FakeUser().as_dict()
        self.user_profile["active"]["value"] = True
        self.uuid = self.user_profile["uuid"]["value"]
        self.user_profile["staff_information"]["director"] = True
        self.vault_json_datastructure = {
            "id":
            self.user_profile.get("user_id").get("value"),
            "user_uuid":
            self.uuid,
            "primary_email":
            self.user_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(self.user_profile),
            "active":
            True,
        }

        profile.create(self.vault_json_datastructure)

    def test_create_method(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.create(self.vault_json_datastructure)
        assert result is not None

    def test_delete_method(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        profile.create(self.vault_json_datastructure)
        result = profile.delete(self.vault_json_datastructure)
        assert result is not None

    def test_update_method(self):
        from cis_identity_vault.models import user

        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = "*****@*****.**"
        modified_profile["active"]["value"] = True
        modified_profile["phone_numbers"]["values"] = {"foo": ""}
        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.update(vault_json_datastructure)
        assert result is not None

    def test_find_user(self):
        from cis_identity_vault.models import user

        primary_email = "*****@*****.**"
        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = primary_email
        modified_profile["active"]["value"] = True
        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure)

        profile = user.Profile(self.table)
        user_id = self.user_profile.get("user_id").get("value")
        result_for_user_id = profile.find_by_id(user_id)
        result_for_email = profile.find_by_email(primary_email)
        assert result_for_user_id is not None
        assert result_for_email is not None

    def test_find_user_multi_id_for_email(self):
        from cis_identity_vault.models import user

        primary_email = "*****@*****.**"
        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = primary_email
        modified_profile["active"]["value"] = True
        vault_json_datastructure_first_id = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure_first_id)

        vault_json_datastructure_second_id = {
            "id":
            "foo|mcbar",
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile.update(vault_json_datastructure_second_id)

        profile = user.Profile(self.table)
        self.user_profile.get("user_id").get("value")
        result_for_email = profile.find_by_email(primary_email)
        assert result_for_email is not None
        assert len(result_for_email.get("Items")) > 2

    def test_find_user_multi_id_for_username(self):
        from cis_identity_vault.models import user

        primary_username = "******"
        modified_profile = self.user_profile
        modified_profile["primary_username"]["value"] = primary_username
        modified_profile["active"]["value"] = False
        vault_json_datastructure_first_id = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure_first_id)

        vault_json_datastructure_second_id = {
            "id":
            "foo|mcbar",
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile.update(vault_json_datastructure_second_id)

        profile = user.Profile(self.table)
        self.user_profile.get("user_id").get("value")
        result_for_username = profile.find_by_username(primary_username)
        assert result_for_username is not None
        assert len(result_for_username.get("Items")) == 2

    def test_find_by_uuid(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        user = json.loads(profile.all[0].get("profile"))

        result_for_uuid = profile.find_by_uuid(user["uuid"]["value"])
        assert len(result_for_uuid.get("Items")) > 0

    def test_find_by_username(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        user = json.loads(profile.all[0].get("profile"))

        result_for_username = profile.find_by_username(
            user["primary_username"]["value"])
        assert len(result_for_username.get("Items")) > 0

    def test_all_by_filter(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.all_filtered(connection_method="email", active=None)
        assert len(result["users"]) > 0
        assert result.get("nextPage") is None
        logger.debug(f"The result of the filtered query is: {result}")

        result = profile.all_filtered(connection_method="email", active=True)
        assert len(result["users"]) > 0
        for record in result["users"]:
            assert record["active"]["BOOL"] is True

    def test_namespace_generator(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        result = profile._namespace_generator("access_information.ldap", "foo")
        assert result == "flat_profile.access_information.ldap.foo"

    def test_find_by_any(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        user_idx = 0

        logger.info("Attempting the generation of a fixture user.")
        try:
            sample_user = json.loads(profile.all[user_idx].get("profile"))
            sample_ldap_group = list(
                sample_user["access_information"]["ldap"]["values"].keys())[0]
            logger.info("Fixure user generated successfully the first try.")
        except Exception as e:  # Cause sometimes the faker doesn't give an LDAP user.
            logger.error(
                f"The first fixture user was not an ldap user.  Mixing the salad.  Error: {e}"
            )
            user_idx = user_idx + 1
            sample_user = json.loads(profile.all[user_idx].get("profile"))

            valid = False
            while valid is False:
                if sample_user["access_information"]["ldap"]["values"] != {}:
                    valid = True
                else:
                    user_idx = user_idx + 1
                    json.loads(profile.all[user_idx].get("profile"))
            sample_ldap_group = list(
                sample_user["access_information"]["ldap"]["values"].keys())[0]
        sample_hris_attr = sample_user["access_information"]["hris"]["values"][
            "employee_id"]

        # Search by ldap group and return only user IDs
        logger.info(f"Attempting a search for users in {sample_ldap_group}")
        result = profile.find_by_any(attr="access_information.ldap",
                                     comparator=sample_ldap_group)
        assert len(result) > 0
        for this_profile in result["users"]:
            assert this_profile.get("id") is not None

        # Search by ldap group and return user_ids with profiles
        result = profile.find_by_any(attr="access_information.ldap",
                                     comparator=sample_ldap_group,
                                     full_profiles=True)

        assert len(result) > 0
        # Ensure that our data retrieved contains full profiles
        for this_profile in result["users"]:
            assert this_profile["id"] is not None
            assert this_profile["profile"]["last_name"]["value"] is not None

        # Search by ldap group inverse match and return user_ids with profiles
        result = profile.find_by_any(attr="not_access_information.ldap",
                                     comparator=sample_ldap_group,
                                     full_profiles=True)

        # Test a search against an hris group
        result = profile.find_by_any(
            attr="access_information.hris.employee_id",
            comparator=sample_hris_attr,
            full_profiles=False)

        assert len(result["users"]) > 0

        # Test search against staff

        result = profile.find_by_any(attr="staff_information.director",
                                     comparator="true",
                                     full_profiles=False)

        while result.get("nextPage"):
            result = profile.find_by_any(attr="staff_information.staff",
                                         comparator=True,
                                         full_profiles=False,
                                         next_page=result.get("nextPage"))

            assert result is not None

    def test_filter_expression_generator(self):
        from cis_identity_vault.models import user

        use_case = dict(
            attr="staff_information.worker_type",
            namespace="flat_profile.staff_information.worker_type",
            comparator=None,
            operator="eq",
            active=True,
        )

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile._filter_expression_generator(**use_case)
        assert result is not None
Ejemplo n.º 18
0
    def setup(self):
        from cis_change_service.common import get_config

        os.environ["CIS_ENVIRONMENT"] = "local"
        name = "local-identity-vault"
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        config = get_config()
        self.kinesalite_port = config("kinesalite_port", namespace="cis")
        self.kinesalite_host = config("kinesalite_host", namespace="cis")
        self.dynalite_port = config("dynalite_port", namespace="cis")
        self.dynaliteprocess = subprocess.Popen(
            ["dynalite", "--port", self.dynalite_port], preexec_fn=os.setsid)
        self.kinesaliteprocess = subprocess.Popen(
            ["kinesalite", "--port", self.kinesalite_port],
            preexec_fn=os.setsid)
        conn = boto3.client(
            "dynamodb",
            region_name="us-west-2",
            aws_access_key_id="ak",
            aws_secret_access_key="sk",
            endpoint_url="http://localhost:{}".format(self.dynalite_port),
        )

        # XXX TBD this will eventually be replaced by logic from the vault module
        # The vault module will have the authoritative definitions for Attributes and GSI
        try:
            conn.create_table(
                TableName=name,
                KeySchema=[{
                    "AttributeName": "id",
                    "KeyType": "HASH"
                }],
                AttributeDefinitions=[
                    {
                        "AttributeName": "id",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "uuid",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "sequence_number",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "primary_email",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "primary_username",
                        "AttributeType": "S"
                    },
                ],
                ProvisionedThroughput={
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 5
                },
                GlobalSecondaryIndexes=[
                    {
                        "IndexName":
                        "{}-sequence_number".format(name),
                        "KeySchema": [{
                            "AttributeName": "sequence_number",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-primary_email".format(name),
                        "KeySchema": [{
                            "AttributeName": "primary_email",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-primary_username".format(name),
                        "KeySchema": [{
                            "AttributeName": "primary_username",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName": "{}-uuid".format(name),
                        "KeySchema": [{
                            "AttributeName": "uuid",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                ],
            )
        except Exception as e:
            logger.error("Table error: {}".format(e))

        conn = Stubber(
            boto3.session.Session(region_name="us-west-2")).client.client(
                "kinesis",
                endpoint_url="http://{}:{}".format(self.kinesalite_host,
                                                   self.kinesalite_port))

        try:
            name = "local-stream"
            conn.create_stream(StreamName=name, ShardCount=1)
        except Exception as e:
            logger.error("Stream creation error: {}".format(e))
            # This just means we tried too many tests too fast.
            pass

        waiter = conn.get_waiter("stream_exists")

        waiter.wait(StreamName=name,
                    Limit=100,
                    WaiterConfig={
                        "Delay": 1,
                        "MaxAttempts": 5
                    })

        tags_1 = {"Key": "cis_environment", "Value": "local"}
        tags_2 = {"Key": "application", "Value": "change-stream"}
        conn.add_tags_to_stream(StreamName=name, Tags=tags_1)
        conn.add_tags_to_stream(StreamName=name, Tags=tags_2)
        self.user_profile = FakeUser().as_json()
Ejemplo n.º 19
0
    def test_wrong_publisher(self, fake_jwks):
        """
        This verifies a wrong-publisher can't update
        it creates a valid user, then wrongly modify an attribute its not allowed to
        """
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis-verify.ini"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_ENVIRONMENT"] = "local"
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["AWS_ACCESS_KEY_ID"] = "foo"
        os.environ["AWS_SECRET_ACCESS_KEY"] = "bar"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"
        os.environ["CIS_VERIFY_SIGNATURES"] = "true"
        os.environ["CIS_VERIFY_PUBLISHERS"] = "true"
        from cis_change_service import api

        fake_new_user = FakeUser(
            config=FakeProfileConfig().minimal().no_display())
        # Create a brand new user
        patched_user_profile = ensure_appropriate_publishers_and_sign(
            fake_new_user.as_dict(), self.publisher_rules, "create")
        # Ensure a first_name is set as we'll use that for testing
        patched_user_profile.first_name.value = "test"
        patched_user_profile.first_name.signature.publisher.name = "ldap"
        patched_user_profile.first_name.metadata.display = "public"
        patched_user_profile.sign_attribute("first_name", "ldap")

        f = FakeBearer()
        fake_jwks.return_value = json_form_of_pk
        token = f.generate_bearer_without_scope()
        api.app.testing = True
        self.app = api.app.test_client()
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(patched_user_profile.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )

        response = json.loads(result.get_data())
        assert result.status_code == 200
        assert response["condition"] == "create"

        # sign first_name again but with wrong publisher (but same value as before)
        new_user = cis_profile.User(user_id=patched_user_profile.user_id.value)
        new_user.first_name = patched_user_profile.first_name
        new_user.sign_attribute("first_name", "access_provider")
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(new_user.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )
        response = json.loads(result.get_data())
        assert response["status_code"] == 202

        # sign first_name again but with wrong publisher and different display (but same value as before)
        new_user = cis_profile.User(user_id=patched_user_profile.user_id.value)
        new_user.first_name = patched_user_profile.first_name
        new_user.first_name.metadata.display = "staff"
        new_user.sign_attribute("first_name", "access_provider")
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(new_user.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )
        response = json.loads(result.get_data())
        assert response["code"] == "invalid_publisher"

        # sign first_name again but with wrong publisher and wrong value (it should fail)
        new_user.first_name.value = "new-test"
        new_user.sign_attribute("first_name", "access_provider")
        result = self.app.post(
            "/v2/user",
            headers={"Authorization": "Bearer " + token},
            data=json.dumps(new_user.as_json()),
            content_type="application/json",
            follow_redirects=True,
        )
        response = json.loads(result.get_data())
        assert result.status_code != 200
    def setup(self):
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"

        from cis_change_service.common import get_config

        config = get_config()
        os.environ["CIS_DYNALITE_PORT"] = str(random.randint(32000, 34000))
        self.dynalite_port = config("dynalite_port", namespace="cis")
        self.dynaliteprocess = subprocess.Popen(
            ["dynalite", "--port", self.dynalite_port], preexec_fn=os.setsid)

        name = "local-identity-vault"
        conn = boto3.client(
            "dynamodb",
            region_name="us-west-2",
            aws_access_key_id="ak",
            aws_secret_access_key="sk",
            endpoint_url="http://localhost:{}".format(self.dynalite_port),
        )
        try:
            conn.create_table(
                TableName=name,
                KeySchema=[{
                    "AttributeName": "id",
                    "KeyType": "HASH"
                }],
                AttributeDefinitions=[
                    {
                        "AttributeName": "id",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "user_uuid",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "sequence_number",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "primary_email",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "primary_username",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "profile",
                        "AttributeType": "S"
                    },
                ],
                ProvisionedThroughput={
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 5
                },
                GlobalSecondaryIndexes=[
                    {
                        "IndexName":
                        "{}-sequence_number".format(name),
                        "KeySchema": [{
                            "AttributeName": "sequence_number",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-primary_email".format(name),
                        "KeySchema": [{
                            "AttributeName": "primary_email",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-primary_username".format(name),
                        "KeySchema": [{
                            "AttributeName": "primary_username",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-user_uuid".format(name),
                        "KeySchema": [{
                            "AttributeName": "user_uuid",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                ],
            )
            waiter = conn.get_waiter("table_exists")
            waiter.wait(TableName="local-identity-vault",
                        WaiterConfig={
                            "Delay": 1,
                            "MaxAttempts": 5
                        })
        except Exception as e:
            logger.error("Table error: {}".format(e))

        user_profile = FakeUser(config=FakeProfileConfig().minimal())
        self.user_profile = user_profile.as_json()
        from cis_change_service import api

        api.app.testing = True
        self.app = api.app.test_client()
        self.publisher_rules = common.WellKnown().get_publisher_rules()
        self.complex_structures = get_complex_structures()
Ejemplo n.º 21
0
class TestUsersDynalite(object):
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "purple"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"
        self.vault_client = vault.IdentityVault()
        self.vault_client.connect()
        self.vault_client.find_or_create()
        self.boto_session = boto3.session.Session(region_name="us-east-1")
        self.dynamodb_resource = self.boto_session.resource("dynamodb")
        self.dynamodb_client = self.boto_session.client("dynamodb")
        self.table = self.dynamodb_resource.Table("purple-identity-vault")

        for x in range(0, 50):  # Must generate 50 users to test paginator
            user_profile = FakeUser().as_dict()
            user_profile["active"]["value"] = True
            uuid = user_profile["uuid"]["value"]
            vault_json_datastructure = {
                "id":
                user_profile.get("user_id").get("value"),
                "user_uuid":
                uuid,
                "primary_email":
                user_profile.get("primary_email").get("value"),
                "primary_username":
                user_profile.get("primary_username").get("value"),
                "sequence_number":
                "12345678",
                "profile":
                json.dumps(user_profile),
                "active":
                True,
            }
            from cis_identity_vault.models import user

            profile = user.Profile(self.table,
                                   self.dynamodb_client,
                                   transactions=False)
            profile.create(vault_json_datastructure)

        self.user_profile = FakeUser().as_dict()
        self.user_profile["active"]["value"] = True
        self.uuid = self.user_profile["uuid"]["value"]
        self.vault_json_datastructure = {
            "id":
            self.user_profile.get("user_id").get("value"),
            "user_uuid":
            self.uuid,
            "primary_email":
            self.user_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(self.user_profile),
            "active":
            True,
        }

    def test_create_method(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.create(self.vault_json_datastructure)
        assert result is not None

    def test_delete_method(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        profile.create(self.vault_json_datastructure)
        result = profile.delete(self.vault_json_datastructure)
        assert result is not None

    def test_update_method(self):
        from cis_identity_vault.models import user

        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = "*****@*****.**"
        modified_profile["active"]["value"] = True
        modified_profile["phone_numbers"]["values"] = {"foo": ""}
        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.update(vault_json_datastructure)
        assert result is not None

    def test_find_user(self):
        from cis_identity_vault.models import user

        primary_email = "*****@*****.**"
        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = primary_email
        modified_profile["active"]["value"] = True
        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure)

        profile = user.Profile(self.table)
        user_id = self.user_profile.get("user_id").get("value")
        result_for_user_id = profile.find_by_id(user_id)
        result_for_email = profile.find_by_email(primary_email)
        assert result_for_user_id is not None
        assert result_for_email is not None

    def test_find_user_multi_id_for_email(self):
        from cis_identity_vault.models import user

        primary_email = "*****@*****.**"
        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = primary_email
        modified_profile["active"]["value"] = True
        vault_json_datastructure_first_id = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure_first_id)

        vault_json_datastructure_second_id = {
            "id":
            "foo|mcbar",
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile.update(vault_json_datastructure_second_id)

        profile = user.Profile(self.table)
        self.user_profile.get("user_id").get("value")
        result_for_email = profile.find_by_email(primary_email)
        assert result_for_email is not None
        assert len(result_for_email.get("Items")) > 2

    def test_find_user_multi_id_for_username(self):
        from cis_identity_vault.models import user

        primary_username = "******"
        modified_profile = self.user_profile
        modified_profile["primary_username"]["value"] = primary_username
        modified_profile["active"]["value"] = False
        vault_json_datastructure_first_id = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure_first_id)

        vault_json_datastructure_second_id = {
            "id":
            "foo|mcbar",
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile.update(vault_json_datastructure_second_id)

        profile = user.Profile(self.table)
        self.user_profile.get("user_id").get("value")
        result_for_username = profile.find_by_username(primary_username)
        assert result_for_username is not None
        assert len(result_for_username.get("Items")) == 2

    def test_find_by_uuid(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        user = json.loads(profile.all[0].get("profile"))

        result_for_uuid = profile.find_by_uuid(user["uuid"]["value"])
        assert len(result_for_uuid.get("Items")) > 0

    def test_find_by_username(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        user = json.loads(profile.all[0].get("profile"))

        result_for_username = profile.find_by_username(
            user["primary_username"]["value"])
        assert len(result_for_username.get("Items")) > 0

    def test_all_by_filter(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.all_filtered(connection_method="email")
        assert len(result) > 0

        result = profile.all_filtered(connection_method="email", active=True)
        assert len(result) > 0
        for record in result:
            assert record["active"]["BOOL"] is True

        result = profile.all_filtered(connection_method="email", active=False)
        for record in result:
            assert record["active"]["BOOL"] is False

    def test_namespace_generator(self):
        pass
        # from cis_identity_vault.models import user
        # profile = user.Profile(self.table, self.dynamodb_client, transactions=False)

        # result = profile.

    def test_find_by_any(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        user_idx = 0
        try:
            sample_user = json.loads(profile.all[user_idx].get("profile"))
            sample_ldap_group = list(
                sample_user["access_information"]["ldap"]["values"].keys())[0]
        except IndexError:  # Cause sometimes the faker doesn't give an LDAP user.
            user_idx = user_idx + 1
            sample_user = json.loads(profile.all[user_idx].get("profile"))

            while len(
                    json.loads(
                        profile.all[user_idx].get("profile")
                        ["access_information"]["ldap"]["values"].keys())) == 0:
                user_idx = user_idx + 1

            sample_ldap_group = list(
                sample_user["access_information"]["ldap"]["values"].keys())[0]
        sample_hris_attr = sample_user["access_information"]["hris"]["values"][
            "employee_id"]

        # Search by ldap group and return only user IDs
        result = profile.find_by_any(attr="access_information.ldap",
                                     comparator=sample_ldap_group)
        assert len(result) > 0
        for this_profile in result["users"]:
            assert this_profile.get("id") is not None

        # Search by ldap group and return user_ids with profiles
        result = profile.find_by_any(attr="access_information.ldap",
                                     comparator=sample_ldap_group,
                                     full_profiles=True)

        assert len(result) > 0
        # Ensure that our data retrieved contains full profiles
        for this_profile in result["users"]:
            assert this_profile["id"] is not None
            assert this_profile["profile"]["last_name"]["value"] is not None

        # Search by ldap group inverse match and return user_ids with profiles
        result = profile.find_by_any(attr="not_access_information.ldap",
                                     comparator=sample_ldap_group,
                                     full_profiles=True)

        # assert result.get("nextPage") is not None

        # Follow the nextPage token and ask for the second page.
        paged_result = profile.find_by_any(
            attr="not_access_information.ldap",
            comparator=sample_ldap_group,
            full_profiles=True,
            next_page=result.get("nextPage"),
        )

        assert paged_result.get("users") is not None

        # Test a search against an hris group
        result = profile.find_by_any(
            attr="access_information.hris.employee_id",
            comparator=sample_hris_attr,
            full_profiles=False)

        assert result is not None
Ejemplo n.º 22
0
 def test_profile_base(self):
     fake_user = FakeUser()
     exch = exchange.ProfileBase()
     exch.user_structure_json = fake_user.as_dict()
     assert exch.valid is True
     assert fake_user.as_dict() == exch.cis_profile.as_dict()
    def setup(self):
        os.environ["AWS_XRAY_SDK_ENABLED"] = "false"
        os.environ["CIS_ENVIRONMENT"] = "local"
        name = "local-identity-vault"
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        self.dynalite_port = str(random.randint(32000, 34000))
        os.environ["CIS_DYNALITE_PORT"] = self.dynalite_port
        self.dynaliteprocess = subprocess.Popen(
            ["dynalite", "--port", self.dynalite_port], preexec_fn=os.setsid)
        conn = boto3.client(
            "dynamodb",
            region_name="us-west-2",
            aws_access_key_id="ak",
            aws_secret_access_key="sk",
            endpoint_url="http://localhost:{}".format(self.dynalite_port),
        )

        # XXX TBD this will eventually be replaced by logic from the vault module
        # The vault module will have the authoritative definitions for Attributes and GSI
        try:
            conn.create_table(
                TableName=name,
                KeySchema=[{
                    "AttributeName": "id",
                    "KeyType": "HASH"
                }],
                AttributeDefinitions=[
                    {
                        "AttributeName": "id",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "user_uuid",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "sequence_number",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "primary_email",
                        "AttributeType": "S"
                    },
                    {
                        "AttributeName": "primary_username",
                        "AttributeType": "S"
                    },
                ],
                ProvisionedThroughput={
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 5
                },
                GlobalSecondaryIndexes=[
                    {
                        "IndexName":
                        "{}-sequence_number".format(name),
                        "KeySchema": [{
                            "AttributeName": "sequence_number",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-primary_email".format(name),
                        "KeySchema": [{
                            "AttributeName": "primary_email",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-primary_username".format(name),
                        "KeySchema": [{
                            "AttributeName": "primary_username",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                    {
                        "IndexName":
                        "{}-user_uuid".format(name),
                        "KeySchema": [{
                            "AttributeName": "user_uuid",
                            "KeyType": "HASH"
                        }],
                        "Projection": {
                            "ProjectionType": "ALL"
                        },
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": 5,
                            "WriteCapacityUnits": 5
                        },
                    },
                ],
            )
            waiter = conn.get_waiter("table_exists")
            waiter.wait(TableName="local-identity-vault",
                        WaiterConfig={
                            "Delay": 5,
                            "MaxAttempts": 5
                        })
        except Exception as e:
            logger.error("Table error: {}".format(e))
        user_profile = FakeUser(config=FakeProfileConfig().minimal())
        self.user_profile = user_profile.as_json()