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
    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
Пример #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
Пример #4
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()
Пример #5
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
Пример #6
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"
Пример #7
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()
Пример #8
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
Пример #9
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"
        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()
        self.user_profile_dict = user_profile.as_dict()