Exemplo n.º 1
0
    def test_copy_ami_snapshot_private_shared(self, mock_aws):
        """Assert that the task copies the image when it is private/shared."""
        mock_account_id = util_helper.generate_dummy_aws_account_id()
        mock_session = mock_aws.boto3.Session.return_value
        mock_aws.get_session_account_id.return_value = mock_account_id

        # the account id to use as the private shared image owner
        other_account_id = util_helper.generate_dummy_aws_account_id()

        mock_region = util_helper.get_random_region()
        mock_arn = util_helper.generate_dummy_arn(mock_account_id, mock_region)

        mock_image_id = util_helper.generate_dummy_image_id()
        mock_image = util_helper.generate_mock_image(mock_image_id)
        mock_snapshot_id = util_helper.generate_dummy_snapshot_id()
        mock_snapshot = util_helper.generate_mock_snapshot(
            mock_snapshot_id, encrypted=False, owner_id=other_account_id)

        mock_aws.get_session.return_value = mock_session
        mock_aws.get_ami.return_value = mock_image
        mock_aws.get_ami_snapshot_id.return_value = mock_snapshot_id
        mock_aws.get_snapshot.return_value = mock_snapshot

        account_helper.generate_image(ec2_ami_id=mock_image_id)

        with patch.object(tasks.imageprep,
                          "create_volume") as mock_create_volume, patch.object(
                              tasks.imageprep, "copy_ami_to_customer_account"
                          ) as mock_copy_ami_to_customer_account:
            tasks.copy_ami_snapshot(mock_arn, mock_image_id, mock_region)
            mock_create_volume.delay.assert_not_called()
            mock_copy_ami_to_customer_account.delay.assert_called_with(
                mock_arn, mock_image_id, mock_region)
Exemplo n.º 2
0
    def test_success(self, mock_primary_id, mock_tasks_aws, mock_create):
        """Assert the task happy path upon normal operation."""
        # User that would ultimately own the created objects.
        user = User.objects.create()

        # Dummy values for the various interactions.
        session_account_id = util_helper.generate_dummy_aws_account_id()
        auth_id = _faker.pyint()
        application_id = _faker.pyint()
        source_id = _faker.pyint()

        customer_secret_access_key = util_helper.generate_dummy_arn(
            account_id=session_account_id)
        primary_account_id = util_helper.generate_dummy_aws_account_id()
        mock_primary_id.return_value = primary_account_id
        mock_tasks_aws.get_session_account_id.return_value = session_account_id
        mock_tasks_aws.AwsArn.return_value.account_id = session_account_id

        # Fake out the policy verification.
        policy_name = _faker.slug()
        policy_arn = util_helper.generate_dummy_arn(
            account_id=session_account_id)
        mock_ensure_policy = mock_tasks_aws.ensure_cloudigrade_policy
        mock_ensure_policy.return_value = (policy_name, policy_arn)

        # Fake out the role verification.
        role_name = _faker.slug()
        role_arn = util_helper.generate_dummy_arn(
            account_id=session_account_id)
        mock_ensure_role = mock_tasks_aws.ensure_cloudigrade_role
        mock_ensure_role.return_value = (role_name, role_arn)

        tasks.configure_customer_aws_and_create_cloud_account(
            user.username,
            customer_secret_access_key,
            auth_id,
            application_id,
            source_id,
        )

        cloud_account_name = api_util.get_standard_cloud_account_name(
            "aws", session_account_id)
        mock_create.assert_called_with(
            user,
            role_arn,
            cloud_account_name,
            auth_id,
            application_id,
            source_id,
        )
Exemplo n.º 3
0
    def test_create_fails_when_assume_role_fails_unexpectedly(self):
        """Test that account is not saved if assume_role fails unexpectedly."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        validated_data = {
            'account_arn': arn,
        }

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        client_error = ClientError(
            error_response=MagicMock(),
            operation_name=Mock(),
        )

        with patch.object(aws.sts, 'boto3') as mock_boto3:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.side_effect = client_error
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(ClientError) as cm:
                serializer.create(validated_data)
            raised_exception = cm.exception
            self.assertEqual(raised_exception, client_error)
Exemplo n.º 4
0
    def test_create_fails_when_arn_access_denied(self):
        """Test that an account is not saved if ARN access is denied."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        validated_data = {
            'account_arn': arn,
        }

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        client_error = ClientError(
            error_response={'Error': {
                'Code': 'AccessDenied'
            }},
            operation_name=Mock(),
        )

        with patch.object(aws.sts, 'boto3') as mock_boto3:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.side_effect = client_error
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(ValidationError) as cm:
                serializer.create(validated_data)
            raised_exception = cm.exception
            self.assertIn('account_arn', raised_exception.detail)
            self.assertIn(arn, raised_exception.detail['account_arn'][0])
Exemplo n.º 5
0
 def setUp(self):
     """Set up test models."""
     aws_account_id = util_helper.generate_dummy_aws_account_id()
     arn = util_helper.generate_dummy_arn(account_id=aws_account_id)
     self.role = util_helper.generate_dummy_role()
     self.account = helper.generate_cloud_account(
         arn=arn, aws_account_id=aws_account_id, name="test")
Exemplo n.º 6
0
    def test_copy_ami_snapshot_not_marketplace(self, mock_aws):
        """Assert that an exception is raised when there is an error."""
        mock_account_id = util_helper.generate_dummy_aws_account_id()
        mock_session = mock_aws.boto3.Session.return_value
        mock_aws.get_session_account_id.return_value = mock_account_id

        mock_region = random.choice(util_helper.SOME_AWS_REGIONS)
        mock_arn = util_helper.generate_dummy_arn(mock_account_id, mock_region)

        mock_image_id = util_helper.generate_dummy_image_id()
        mock_image = util_helper.generate_mock_image(mock_image_id)
        mock_snapshot_id = util_helper.generate_dummy_snapshot_id()

        mock_aws.get_session.return_value = mock_session
        mock_aws.get_ami.return_value = mock_image
        mock_aws.get_ami_snapshot_id.return_value = mock_snapshot_id
        mock_aws.get_snapshot.side_effect = ClientError(
            error_response={
                'Error': {
                    'Code': 'ItIsAMystery',
                    'Message': 'Mystery Error',
                }
            },
            operation_name=Mock(),
        )

        with self.assertRaises(RuntimeError) as e:
            copy_ami_snapshot(mock_arn, mock_image_id, mock_region)

        self.assertIn('ClientError', e.exception.args[0])
        self.assertIn('ItIsAMystery', e.exception.args[0])
        self.assertIn('Mystery Error', e.exception.args[0])
Exemplo n.º 7
0
    def test_update_cloudtrail_exception(self):
        """
        Test the update_cloudtrail function.

        Assert that an error is returned when the CloudTrail does not exist.
        """
        aws_account_id = helper.generate_dummy_aws_account_id()
        name = '{0}{1}'.format(settings.CLOUDTRAIL_NAME_PREFIX, aws_account_id)

        mock_session = Mock()

        mock_copy_error = {
            'Error': {
                'Code':
                'TrailNotFoundException',
                'Message':
                'Unknown trail: {0} for the user '
                '{1}'.format(name, aws_account_id)
            }
        }

        mock_client = mock_session.client.return_value

        mock_client.update_trail.side_effect = ClientError(
            mock_copy_error, 'UpdateTrail')

        with self.assertRaises(ClientError):
            cloudtrail.update_cloudtrail(mock_client, name)
Exemplo n.º 8
0
    def test_save_with_concurrent_usages(self):
        """Test that save deletes the related concurrent_usages."""
        user = util_helper.generate_test_user()
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        account = api_helper.generate_cloud_account(
            aws_account_id=aws_account_id,
            user=user,
        )
        image = api_helper.generate_image(
            owner_aws_account_id=aws_account_id,
            rhel_detected=True,
        )
        instance = api_helper.generate_instance(account, image=image)
        api_helper.generate_single_run(
            instance,
            (
                util_helper.utc_dt(2019, 5, 1, 1, 0, 0),
                util_helper.utc_dt(2019, 5, 1, 2, 0, 0),
            ),
            image=instance.machine_image,
        )
        request_date = datetime.date(2019, 5, 1)
        calculate_max_concurrent_usage(request_date, user_id=user.id)

        self.assertEquals(1, ConcurrentUsage.objects.count())
        image.rhel_detected_by_tag = True
        image.save()
        self.assertEquals(0, ConcurrentUsage.objects.count())
Exemplo n.º 9
0
    def setUp(self):
        """Set up shared variables."""
        self.authentication_id = _faker.pyint()
        self.account_id = util_helper.generate_dummy_aws_account_id()
        self.arn = util_helper.generate_dummy_arn(account_id=self.account_id)

        self.clount = api_helper.generate_cloud_account(
            arn=self.arn, platform_authentication_id=self.authentication_id)

        self.username = _faker.user_name()
        self.application_id = _faker.pyint()
        self.source_id = _faker.pyint()

        self.account_number = str(_faker.pyint())

        self.auth_return_value = {
            "username": self.arn,
            "resource_type": settings.SOURCES_RESOURCE_TYPE,
            "resource_id": self.application_id,
            "id": self.authentication_id,
            "authtype": settings.SOURCES_CLOUDMETER_ARN_AUTHTYPE,
        }
        self.app_return_value = {
            "source_id": self.source_id,
            "id": self.application_id,
        }
Exemplo n.º 10
0
    def test_delete_cloudtrail_exception(self):
        """
        Test the delete_cloudtrail function.

        Assert that an error is returned when the CloudTrail does not exist.
        """
        aws_account_id = helper.generate_dummy_aws_account_id()
        name = "{0}{1}".format(settings.CLOUDTRAIL_NAME_PREFIX, aws_account_id)

        mock_session = Mock()

        mock_error = {
            "Error": {
                "Code":
                "TrailNotFoundException",
                "Message":
                "Unknown trail: {0} for the user: {1}".format(
                    name, aws_account_id),
            }
        }

        mock_client = mock_session.client.return_value

        mock_client.delete_trail.side_effect = ClientError(
            mock_error, "DeleteTrail")

        with self.assertRaises(ClientError):
            cloudtrail.delete_cloudtrail(mock_client, name)
Exemplo n.º 11
0
    def test_delete_cloudtrail(self):
        """Test the delete_cloudtrail function.

        Assert that delete_cloudtrail function returns the response returned
        from calling the cloudtrail delete_trail function.
        """
        aws_account_id = helper.generate_dummy_aws_account_id()
        name = "{0}{1}".format(settings.CLOUDTRAIL_NAME_PREFIX, aws_account_id)

        mock_session = Mock()

        # This was the real response from a delete_trail call made on 2020-07-15.
        mock_response = {
            "ResponseMetadata": {
                "RequestId": "cd3513ab-6c5f-490a-b94f-7dea5faa9e40",
                "HTTPStatusCode": 200,
                "HTTPHeaders": {
                    "x-amzn-requestid": "cd3513ab-6c5f-490a-b94f-7dea5faa9e40",
                    "content-type": "application/x-amz-json-1.1",
                    "content-length": "2",
                    "date": "Wed, 15 Jul 2020 15:31:25 GMT",
                },
                "RetryAttempts": 0,
            }
        }

        mock_client = mock_session.client.return_value
        mock_client.delete_trail.return_value = mock_response
        expected_value = mock_response
        actual_value = cloudtrail.delete_cloudtrail(mock_client, name)

        self.assertEqual(expected_value, actual_value)
Exemplo n.º 12
0
    def test_create_cloudtrail_limit_exception(self):
        """Test the create_cloudtrail function.

        Assert that an error is returned when trail limit is reached
        """
        aws_account_id = helper.generate_dummy_aws_account_id()
        name = "{0}{1}".format(settings.CLOUDTRAIL_NAME_PREFIX, aws_account_id)

        mock_session = Mock()

        mock_error = {
            "Error": {
                "Code":
                "MaximumNumberOfTrailsExceededException",
                "Message":
                "User: 123456789012 already has 1337 trails in us-east-1.",
            }
        }

        mock_client = mock_session.client.return_value
        mock_client.create_trail.side_effect = ClientError(
            mock_error, "CreateTrail")

        with self.assertRaises(MaximumNumberOfTrailsExceededException):
            cloudtrail.create_cloudtrail(mock_client, name)
Exemplo n.º 13
0
    def test_create_fails_when_cloudtrail_fails(self):
        """Test that an account is not saved if cloudtrails errors."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        role = util_helper.generate_dummy_role()

        validated_data = {
            'account_arn': arn,
        }

        client_error = ClientError(
            error_response={'Error': {
                'Code': 'AccessDeniedException'
            }},
            operation_name=Mock(),
        )

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        with patch.object(aws, 'verify_account_access') as mock_verify, \
                patch.object(aws.sts, 'boto3') as mock_boto3, \
                patch.object(aws, 'configure_cloudtrail') as mock_cloudtrail:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = role
            mock_verify.return_value = True, []
            mock_cloudtrail.side_effect = client_error
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(ValidationError) as cm:
                serializer.create(validated_data)
            raised_exception = cm.exception
            self.assertIn('account_arn', raised_exception.detail)
            self.assertIn(arn, raised_exception.detail['account_arn'][0])
Exemplo n.º 14
0
    def test_copy_ami_snapshot_not_marketplace(self, mock_aws):
        """Assert that an exception is raised when there is an error."""
        mock_account_id = util_helper.generate_dummy_aws_account_id()
        mock_session = mock_aws.boto3.Session.return_value
        mock_aws.get_session_account_id.return_value = mock_account_id

        mock_region = util_helper.get_random_region()
        mock_arn = util_helper.generate_dummy_arn(mock_account_id, mock_region)

        mock_image_id = util_helper.generate_dummy_image_id()
        account_helper.generate_image(ec2_ami_id=mock_image_id)
        mock_image = util_helper.generate_mock_image(mock_image_id)
        mock_snapshot_id = util_helper.generate_dummy_snapshot_id()

        mock_aws.get_session.return_value = mock_session
        mock_aws.get_ami.return_value = mock_image
        mock_aws.get_ami_snapshot_id.return_value = mock_snapshot_id
        mock_aws.get_snapshot.side_effect = ClientError(
            error_response={
                "Error": {
                    "Code": "ItIsAMystery",
                    "Message": "Mystery Error"
                }
            },
            operation_name=Mock(),
        )

        with self.assertRaises(RuntimeError) as e:
            tasks.copy_ami_snapshot(mock_arn, mock_image_id, mock_region)

        self.assertIn("ClientError", e.exception.args[0])
        self.assertIn("ItIsAMystery", e.exception.args[0])
        self.assertIn("Mystery Error", e.exception.args[0])
Exemplo n.º 15
0
    def test_copy_ami_snapshot_marketplace(self, mock_aws):
        """Assert that a suspected marketplace image is checked."""
        mock_account_id = util_helper.generate_dummy_aws_account_id()
        mock_session = mock_aws.boto3.Session.return_value
        mock_aws.get_session_account_id.return_value = mock_account_id

        mock_region = util_helper.get_random_region()
        mock_arn = util_helper.generate_dummy_arn(mock_account_id, mock_region)

        mock_image_id = util_helper.generate_dummy_image_id()
        mock_image = util_helper.generate_mock_image(mock_image_id)
        mock_snapshot_id = util_helper.generate_dummy_snapshot_id()

        mock_aws.get_session.return_value = mock_session
        mock_aws.get_ami.return_value = mock_image
        mock_aws.get_ami_snapshot_id.return_value = mock_snapshot_id
        mock_aws.get_snapshot.side_effect = ClientError(
            error_response={"Error": {
                "Code": "InvalidSnapshot.NotFound"
            }},
            operation_name=Mock(),
        )

        account_helper.generate_image(ec2_ami_id=mock_image_id)

        with patch.object(tasks.imageprep,
                          "create_volume") as mock_create_volume, patch.object(
                              tasks.imageprep, "copy_ami_to_customer_account"
                          ) as mock_copy_ami_to_customer_account:
            tasks.copy_ami_snapshot(mock_arn, mock_image_id, mock_region)
            mock_create_volume.delay.assert_not_called()
            mock_copy_ami_to_customer_account.delay.assert_called_with(
                mock_arn, mock_image_id, mock_region)
Exemplo n.º 16
0
    def test_update_from_sources_kafka_message_new_aws_account_id(
            self, mock_enable, mock_get_auth, mock_notify_sources,
            mock_get_app):
        """
        Assert the new cloud account created for new aws_account_id.

        A new CloudAccount will get created with the new arn. And the old
        CloudAccount will be removed.
        """
        message, headers = util_helper.generate_authentication_create_message_value(
            self.account_number, self.username, self.authentication_id)
        new_account_id = util_helper.generate_dummy_aws_account_id()
        new_arn = util_helper.generate_dummy_arn(account_id=new_account_id)

        self.auth_return_value["username"] = new_arn
        mock_get_auth.return_value = self.auth_return_value
        mock_get_app.return_value = self.app_return_value

        with patch.object(sts, "boto3") as mock_boto3, patch.object(
                aws_models, "_delete_cloudtrail"), patch(
                    "api.clouds.aws.util.verify_permissions"):
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = util_helper.generate_dummy_role()
            tasks.update_from_source_kafka_message(message, headers)

        mock_enable.assert_called()
Exemplo n.º 17
0
    def test_put_event_selectors(self):
        """Test the put_event_selectors function.

        Assert that put_event_selectors returns the response returned from
        calling the cloudtrail put_event_selectors function.
        """
        aws_account_id = helper.generate_dummy_aws_account_id()
        name = '{0}{1}'.format(settings.CLOUDTRAIL_NAME_PREFIX, aws_account_id)

        mock_session = Mock()

        mock_response = {
            'TrailARN':
            'arn:aws:cloudtrail:us-east-1:'
            '{0}:trail/{1}'.format(aws_account_id, name),
            'EventSelectors': [{
                'ReadWriteType': 'WriteOnly',
                'IncludeManagementEvents': True,
                'DataResources': []
            }],
        }

        mock_client = mock_session.client.return_value
        # set the aws put_event_selectors function response as mock_response
        mock_client.put_event_selectors.return_value = mock_response

        # set the expected response as the mock_response as well
        expected_return_value = mock_response

        actual_return_value = cloudtrail.put_event_selectors(mock_client, name)
        self.assertEqual(expected_return_value, actual_return_value)
Exemplo n.º 18
0
    def test_create_cloudtrail_exception(self):
        """Test the create_cloudtrail function.

        Assert that an error is returned when the trail already exists
        """
        aws_account_id = helper.generate_dummy_aws_account_id()
        name = '{0}{1}'.format(settings.CLOUDTRAIL_NAME_PREFIX, aws_account_id)

        mock_session = Mock()

        mock_error = {
            'Error': {
                'Code':
                'TrailAlreadyExistsException',
                'Message':
                'Trail {0} already exists'
                'for customer: {1}'.format(name, aws_account_id)
            }
        }

        mock_client = mock_session.client.return_value
        mock_client.create_trail.side_effect = ClientError(
            mock_error, 'CreateTrail')

        with self.assertRaises(ClientError):
            cloudtrail.create_cloudtrail(mock_client, name)
Exemplo n.º 19
0
    def test_create_fails_when_account_not_verified(self):
        """Test that an account is not saved if verification fails."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        role = util_helper.generate_dummy_role()
        validated_data = {
            'account_arn': arn,
        }

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        failed_actions = ['foo', 'bar']

        with patch.object(aws, 'verify_account_access') as mock_verify, \
                patch.object(aws.sts, 'boto3') as mock_boto3:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = role
            mock_verify.return_value = False, failed_actions
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(serializers.ValidationError) as cm:
                serializer.create(validated_data)

            exception = cm.exception
            self.assertIn('account_arn', exception.detail)
            for index in range(len(failed_actions)):
                self.assertIn(failed_actions[index],
                              exception.detail['account_arn'][index + 1])
Exemplo n.º 20
0
    def test_parse_arn_with_region_and_account(self):
        """Assert successful account ID parsing from a well-formed ARN."""
        mock_account_id = helper.generate_dummy_aws_account_id()
        mock_arn = helper.generate_dummy_arn(account_id=mock_account_id,
                                             region="test-region-1")

        arn_object = AwsArn(mock_arn)

        partition = arn_object.partition
        self.assertIsNotNone(partition)

        service = arn_object.service
        self.assertIsNotNone(service)

        region = arn_object.region
        self.assertIsNotNone(region)

        account_id = arn_object.account_id
        self.assertIsNotNone(account_id)

        resource_type = arn_object.resource_type
        self.assertIsNotNone(resource_type)

        resource_separator = arn_object.resource_separator
        self.assertIsNotNone(resource_separator)

        resource = arn_object.resource
        self.assertIsNotNone(resource)

        reconstructed_arn = ("arn:" + partition + ":" + service + ":" +
                             region + ":" + str(account_id) + ":" +
                             resource_type + resource_separator + resource)

        self.assertEqual(mock_account_id, account_id)
        self.assertEqual(mock_arn, reconstructed_arn)
Exemplo n.º 21
0
    def test_copy_ami_snapshot_encrypted(self, mock_aws):
        """Assert that the task marks the image as encrypted in the DB."""
        mock_account_id = util_helper.generate_dummy_aws_account_id()
        mock_region = util_helper.get_random_region()
        mock_arn = util_helper.generate_dummy_arn(mock_account_id, mock_region)

        mock_image_id = util_helper.generate_dummy_image_id()
        mock_image = util_helper.generate_mock_image(mock_image_id)
        mock_snapshot_id = util_helper.generate_dummy_snapshot_id()
        mock_snapshot = util_helper.generate_mock_snapshot(mock_snapshot_id,
                                                           encrypted=True)
        mock_session = mock_aws.boto3.Session.return_value

        mock_aws.get_session.return_value = mock_session
        mock_aws.get_ami.return_value = mock_image
        mock_aws.get_ami_snapshot_id.return_value = mock_snapshot_id
        mock_aws.get_snapshot.return_value = mock_snapshot

        ami = account_helper.generate_image(ec2_ami_id=mock_image_id)

        with patch.object(tasks, "create_volume") as mock_create_volume:
            tasks.copy_ami_snapshot(mock_arn, mock_image_id, mock_region)
            ami.refresh_from_db()
            self.assertTrue(ami.is_encrypted)
            self.assertEqual(ami.status, ami.ERROR)
            mock_create_volume.delay.assert_not_called()
Exemplo n.º 22
0
    def test_create_new_machine_images(self):
        """Test that new machine images are saved to the DB."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        account = AwsAccount(
            account_arn=arn,
            aws_account_id=aws_account_id,
            user=util_helper.generate_test_user(),
        )
        account.save()

        region = random.choice(util_helper.SOME_AWS_REGIONS)
        running_instances = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running
                )
            ]
        }
        ami_id = running_instances[region][0]['ImageId']

        result = util.create_new_machine_images(account, running_instances)

        amis = AwsMachineImage.objects.filter(account=account).all()

        self.assertEqual(result, [ami_id])
        for ami in amis:
            self.assertEqual(ami.ec2_ami_id, ami_id)
Exemplo n.º 23
0
    def test_create_new_machine_images_with_windows_image(self):
        """Test that new windows machine images are marked appropriately."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        account = AwsAccount(
            account_arn=arn,
            aws_account_id=aws_account_id,
            user=util_helper.generate_test_user(),
        )
        account.save()

        region = random.choice(util_helper.SOME_AWS_REGIONS)
        running_instances = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running
                )
            ]
        }
        running_instances[region][0]['Platform'] = 'Windows'
        ami_id = running_instances[region][0]['ImageId']

        result = util.create_new_machine_images(account, running_instances)

        amis = AwsMachineImage.objects.filter(account=account).all()

        self.assertEqual(result, [ami_id])
        for ami in amis:
            self.assertEqual(ami.ec2_ami_id, ami_id)
            self.assertEqual(ImageTag.objects.filter(
                description='windows').first(),
                ami.tags.filter(description='windows').first())
Exemplo n.º 24
0
    def test_copy_ami_snapshot_encrypted(self, mock_aws):
        """Assert that the task marks the image as encrypted in the DB."""
        mock_account_id = util_helper.generate_dummy_aws_account_id()
        mock_region = random.choice(util_helper.SOME_AWS_REGIONS)
        mock_arn = util_helper.generate_dummy_arn(mock_account_id, mock_region)

        mock_image_id = util_helper.generate_dummy_image_id()
        mock_image = util_helper.generate_mock_image(mock_image_id)
        mock_snapshot_id = util_helper.generate_dummy_snapshot_id()
        mock_snapshot = util_helper.generate_mock_snapshot(mock_snapshot_id,
                                                           encrypted=True)
        mock_session = mock_aws.boto3.Session.return_value

        mock_aws.get_session.return_value = mock_session
        mock_aws.get_ami.return_value = mock_image
        mock_aws.get_ami_snapshot_id.return_value = mock_snapshot_id
        mock_aws.get_snapshot.return_value = mock_snapshot

        account = AwsAccount(
            aws_account_id=mock_account_id,
            account_arn=mock_arn,
            user=util_helper.generate_test_user(),
        )
        account.save()
        ami = AwsMachineImage.objects.create(account=account,
                                             is_windows=False,
                                             ec2_ami_id=mock_image_id)

        ami.save()

        with patch.object(tasks, 'create_volume') as mock_create_volume,\
                self.assertRaises(AwsSnapshotEncryptedError):
            copy_ami_snapshot(mock_arn, mock_image_id, mock_region)
            self.assertTrue(ami.is_encrypted)
            mock_create_volume.delay.assert_not_called()
Exemplo n.º 25
0
    def test_report_with_timezones_specified(self):
        """Test that start/end dates with timezones shift correctly to UTC."""
        cloud_provider = AWS_PROVIDER_STRING
        cloud_account_id = util_helper.generate_dummy_aws_account_id()
        start_no_tz = '2018-01-01T00:00:00-05'
        end_no_tz = '2018-02-01T00:00:00+04'
        request_data = {
            'cloud_provider': cloud_provider,
            'cloud_account_id': str(cloud_account_id),
            'start': start_no_tz,
            'end': end_no_tz,
        }
        expected_start = util_helper.utc_dt(2018, 1, 1, 5, 0)
        expected_end = util_helper.utc_dt(2018, 1, 31, 20, 0)

        with patch.object(reports, 'get_time_usage') as mock_get_hourly:
            serializer = ReportSerializer(data=request_data)
            serializer.is_valid(raise_exception=True)
            results = serializer.generate()
            mock_get_hourly.assert_called_with(
                cloud_provider=cloud_provider,
                cloud_account_id=cloud_account_id,
                start=expected_start,
                end=expected_end)
            self.assertEqual(results, mock_get_hourly.return_value)
Exemplo n.º 26
0
    def test_save_instance_with_available_image(self):
        """Test that save instance events also writes image on instance."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        account = api_helper.generate_cloud_account(
            arn=arn, aws_account_id=aws_account_id)

        region = util_helper.get_random_region()
        instances_data = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running)
            ]
        }
        ami_id = instances_data[region][0]["ImageId"]

        mock_session = Mock()
        described_amis = util_helper.generate_dummy_describe_image(
            image_id=ami_id, owner_id=aws_account_id)

        with patch.object(util.aws, "describe_images") as mock_describe_images:
            mock_describe_images.return_value = [described_amis]
            util.create_new_machine_images(mock_session, instances_data)
            mock_describe_images.assert_called_with(mock_session, {ami_id},
                                                    region)
        awsinstance = util.save_instance(account, instances_data[region][0],
                                         region)
        instance = awsinstance.instance.get()
        self.assertEqual(instance.machine_image.content_object.ec2_ami_id,
                         ami_id)
        self.assertEqual(instance.machine_image.status, MachineImage.PENDING)
Exemplo n.º 27
0
    def test_create_new_machine_images_with_windows_image(self):
        """Test that new windows machine images are marked appropriately."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        api_helper.generate_cloud_account(arn=arn,
                                          aws_account_id=aws_account_id)

        region = util_helper.get_random_region()
        instances_data = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running)
            ]
        }
        instances_data[region][0]["Platform"] = "Windows"
        ami_id = instances_data[region][0]["ImageId"]

        mock_session = Mock()
        described_amis = util_helper.generate_dummy_describe_image(
            image_id=ami_id, owner_id=aws_account_id)

        with patch.object(util.aws, "describe_images") as mock_describe_images:
            mock_describe_images.return_value = [described_amis]
            result = util.create_new_machine_images(mock_session,
                                                    instances_data)
            mock_describe_images.assert_called_with(mock_session, {ami_id},
                                                    region)

        self.assertEqual(result, [ami_id])

        images = list(AwsMachineImage.objects.all())
        self.assertEqual(len(images), 1)
        self.assertEqual(images[0].ec2_ami_id, ami_id)
        self.assertEqual(images[0].platform, AwsMachineImage.WINDOWS)
Exemplo n.º 28
0
 def test_delete_clount_doesnt_delete_user_for_two_clounts(
         self, mock_notify_source):
     """Test User is not deleted if it has more clounts left."""
     user = util_helper.generate_test_user()
     username = user.username
     aws_account_id = util_helper.generate_dummy_aws_account_id()
     account = api_helper.generate_cloud_account(
         aws_account_id=aws_account_id,
         user=user,
     )
     aws_account_id2 = util_helper.generate_dummy_aws_account_id()
     api_helper.generate_cloud_account(
         aws_account_id=aws_account_id2,
         user=user,
     )
     account.delete()
     self.assertTrue(User.objects.filter(username=username).exists())
Exemplo n.º 29
0
 def setUp(self):
     """Set up common variables for tests."""
     self.user = util_helper.generate_test_user()
     self.aws_account_id = util_helper.generate_dummy_aws_account_id()
     self.account = api_helper.generate_cloud_account(
         aws_account_id=self.aws_account_id, user=self.user)
     self.arn = util_helper.generate_dummy_arn(
         account_id=self.aws_account_id)
Exemplo n.º 30
0
 def test_generate_aws_account_with_args(self):
     """Assert generation of an AwsAccount with all specified args."""
     aws_account_id = util_helper.generate_dummy_aws_account_id()
     arn = util_helper.generate_dummy_arn(aws_account_id)
     account = helper.generate_aws_account(arn, aws_account_id)
     self.assertIsInstance(account, AwsAccount)
     self.assertEqual(account.account_arn, arn)
     self.assertEqual(account.aws_account_id, aws_account_id)