Пример #1
0
    def __init__(self,
                 default_resource_group_name: str,
                 default_region: str = 'eastus',
                 profile_name: Optional[str] = None) -> None:
        """Initialize the AZAccount class.

    Args:
      default_resource_group_name (str): The default resource group in which to
          create new resources in. If the resource group does not exists,
          it will be automatically created.
      default_region (str): Optional. The default region to create new
          resources in. Default is eastus.
      profile_name (str): Optional. The name of the profile to use for Azure
          operations. For more information on profiles, see GetCredentials()
          in libcloudforensics.providers.azure.internal.common.py. Default
          does not use profiles and will authenticate to Azure using
          environment variables.
    """
        self.subscription_id, self.credentials = common.GetCredentials(
            profile_name)
        self.default_region = default_region
        self._compute = None  # type: Optional[compute_module.AZCompute]
        self._monitoring = None  # type: Optional[monitoring_module.AZMonitoring]
        self._network = None  # type: Optional[network_module.AZNetwork]
        self._resource = None  # type: Optional[resource_module.AZResource]
        self._storage = None  # type: Optional[storage_module.AZStorage]
        self.default_resource_group_name = self.resource.GetOrCreateResourceGroup(
            default_resource_group_name)
Пример #2
0
  def __init__(self,
               default_resource_group_name: str,
               default_region: str = 'eastus',
               profile_name: Optional[str] = None) -> None:
    """Initialize the AZAccount class.

    Args:
      default_resource_group_name (str): The default resource group in which to
          create new resources in. If the resource group does not exists,
          it will be automatically created.
      default_region (str): Optional. The default region to create new
          resources in. Default is eastus.
      profile_name (str): Optional. The name of the profile to use for Azure
          operations. For more information on profiles, see GetCredentials()
          in libcloudforensics.providers.azure.internal.common.py. Default
          does not use profiles and will authenticate to Azure using
          environment variables.
    """
    self.subscription_id, self.credentials = common.GetCredentials(profile_name)
    self.default_region = default_region
    self.compute_client = azure_compute.ComputeManagementClient(
        self.credentials, self.subscription_id)
    self.storage_client = storage.StorageManagementClient(
        self.credentials, self.subscription_id)
    self.resource_client = resource.ResourceManagementClient(
        self.credentials, self.subscription_id)
    self.network_client = network.NetworkManagementClient(
        self.credentials, self.subscription_id)
    self.default_resource_group_name = self._GetOrCreateResourceGroup(
        default_resource_group_name)
Пример #3
0
    def testGetCredentials(self, mock_azure_credentials):
        """Test that everything works when environment variables are provided."""
        mock_azure_credentials.return_value = None
        # If all environment variables are defined, things should work correctly
        os.environ['AZURE_SUBSCRIPTION_ID'] = 'fake-subscription-id'
        os.environ["AZURE_CLIENT_ID"] = 'fake-client-id'
        os.environ["AZURE_CLIENT_SECRET"] = 'fake-client-secret'
        os.environ["AZURE_TENANT_ID"] = 'fake-tenant-id'

        subscription_id, _ = common.GetCredentials()
        self.assertEqual('fake-subscription-id', subscription_id)
        mock_azure_credentials.assert_called()
Пример #4
0
    def testGetCredentialsFromProfileFile(self, mock_azure_credentials):
        """Test that credentials can be obtained from profile files."""
        # If the file is correctly formatted, then things should work correctly
        mock_azure_credentials.return_value = None

        os.environ['AZURE_CREDENTIALS_PATH'] = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.dirname(os.path.dirname(
                        os.path.realpath(__file__))))), azure_mocks.JSON_FILE)
        subscription_id, _ = common.GetCredentials(
            profile_name='test_profile_name')
        self.assertEqual('fake-subscription-id-from-credential-file',
                         subscription_id)
        mock_azure_credentials.assert_called()
Пример #5
0
    def testGetCredentialsMissingEnvVar(self, mock_azure_credentials):
        """Test that missing environment variables will raise an error."""
        # If an environment variable is missing, a RuntimeError should be raised
        mock_azure_credentials.return_value = None
        os.environ['AZURE_SUBSCRIPTION_ID'] = 'fake-subscription-id'
        os.environ["AZURE_CLIENT_ID"] = 'fake-client-id'
        os.environ["AZURE_CLIENT_SECRET"] = 'fake-client-secret'
        # Omitting AZURE_TENANT_ID

        with self.assertRaises(errors.CredentialsConfigurationError) as error:
            _, _ = common.GetCredentials()
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Please make sure you defined the following environment variables: '
            '[AZURE_SUBSCRIPTION_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, '
            'AZURE_TENANT_ID].', str(error.exception))
Пример #6
0
    def testGetCredentialsFromInexistingProfileName(self,
                                                    mock_azure_credentials):
        """Test that inexisting profile names will raise an error."""
        # If the profile name does not exist, should raise a ValueError
        mock_azure_credentials.return_value = None

        os.environ['AZURE_CREDENTIALS_PATH'] = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.dirname(os.path.dirname(
                        os.path.realpath(__file__))))), azure_mocks.JSON_FILE)

        with self.assertRaises(errors.CredentialsConfigurationError) as error:
            _, _ = common.GetCredentials(profile_name='foo')
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Profile name foo not found in credentials file {0:s}'.format(
                os.environ['AZURE_CREDENTIALS_PATH']), str(error.exception))
Пример #7
0
    def testGetCredentialsFromInvalidProfileFile(self, mock_azure_credentials):
        """Test that an error is raised when a profile file contain invalid JSON."""
        # If a profile name is passed to the method, then it will look for a
        # credential file (default path being ~/.azure/credentials.json). We can
        # set a particular path by setting the AZURE_CREDENTIALS_PATH variable.
        mock_azure_credentials.return_value = None

        # If the file is not a valid json file, should raise a ValueError
        os.environ['AZURE_CREDENTIALS_PATH'] = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.dirname(os.path.dirname(
                        os.path.realpath(__file__))))),
            azure_mocks.STARTUP_SCRIPT)
        with self.assertRaises(errors.InvalidFileFormatError) as error:
            _, _ = common.GetCredentials(profile_name='foo')
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Could not decode JSON file. Please verify the file format: Expecting '
            'value: line 1 column 1 (char 0)', str(error.exception))
Пример #8
0
    def testGetCredentialsFromMalformedProfileFile(self,
                                                   mock_azure_credentials):
        """Test that an error is raised when the profile file is incomplete."""
        # If the profile name exists but there are missing entries, should raise
        # a ValueError
        mock_azure_credentials.return_value = None

        os.environ['AZURE_CREDENTIALS_PATH'] = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.dirname(os.path.dirname(
                        os.path.realpath(__file__))))), azure_mocks.JSON_FILE)

        with self.assertRaises(errors.CredentialsConfigurationError) as error:
            _, _ = common.GetCredentials(
                profile_name='incomplete_profile_name')
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Profile name incomplete_profile_name not found in credentials file '
            '{0:s}'.format(os.environ['AZURE_CREDENTIALS_PATH']),
            str(error.exception))
Пример #9
0
    def testGetCredentials(self, mock_azure_credentials):
        """Test that credentials are parsed correctly / found."""

        mock_azure_credentials.return_value = None

        # If all environment variables are defined, things should work correctly
        os.environ['AZURE_SUBSCRIPTION_ID'] = 'fake-subscription-id'
        os.environ["AZURE_CLIENT_ID"] = 'fake-client-id'
        os.environ["AZURE_CLIENT_SECRET"] = 'fake-client-secret'
        os.environ["AZURE_TENANT_ID"] = 'fake-tenant-id'

        subscription_id, _ = common.GetCredentials()
        self.assertEqual('fake-subscription-id', subscription_id)
        mock_azure_credentials.assert_called_with('fake-client-id',
                                                  'fake-client-secret',
                                                  tenant='fake-tenant-id')

        # If an environment variable is missing, a RuntimeError should be raised
        del os.environ['AZURE_SUBSCRIPTION_ID']
        with self.assertRaises(RuntimeError) as error:
            _, _ = common.GetCredentials()
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Please make sure you defined the following environment variables: '
            '[AZURE_SUBSCRIPTION_ID,AZURE_CLIENT_ID, AZURE_CLIENT_SECRET,'
            'AZURE_TENANT_ID].', str(error.exception))

        # If a profile name is passed to the method, then it will look for a
        # credential file (default path being ~/.azure/credentials.json). We can
        # set a particular path by setting the AZURE_CREDENTIALS_PATH variable.

        # If the file is not a valid json file, should raise a ValueError
        os.environ['AZURE_CREDENTIALS_PATH'] = os.path.join(
            os.path.dirname(
                os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),
            STARTUP_SCRIPT)
        with self.assertRaises(ValueError) as error:
            _, _ = common.GetCredentials(profile_name='foo')
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Could not decode JSON file. Please verify the file format: Expecting '
            'value: line 1 column 1 (char 0)', str(error.exception))

        # If the file is correctly formatted, then things should work correctly
        os.environ['AZURE_CREDENTIALS_PATH'] = os.path.join(
            os.path.dirname(
                os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),
            JSON_FILE)
        subscription_id, _ = common.GetCredentials(
            profile_name='test_profile_name')
        self.assertEqual('fake-subscription-id-from-credential-file',
                         subscription_id)
        mock_azure_credentials.assert_called_with(
            'fake-client-id-from-credential-file',
            'fake-client-secret-from-credential-file',
            tenant='fake-tenant-id-from-credential-file')

        # If the profile name does not exist, should raise a ValueError
        with self.assertRaises(ValueError) as error:
            _, _ = common.GetCredentials(profile_name='foo')
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Profile name foo not found in credentials file {0:s}'.format(
                os.environ['AZURE_CREDENTIALS_PATH']), str(error.exception))

        # If the profile name exists but there are missing entries, should raise
        # a ValueError
        with self.assertRaises(ValueError) as error:
            _, _ = common.GetCredentials(
                profile_name='incomplete_profile_name')
            mock_azure_credentials.assert_not_called()
        self.assertEqual(
            'Profile name incomplete_profile_name not found in credentials file '
            '{0:s}'.format(os.environ['AZURE_CREDENTIALS_PATH']),
            str(error.exception))