示例#1
0
    def signed_session(self, session=None):
        """Create requests session with any required auth headers applied.

        If a session object is provided, configure it directly. Otherwise,
        create a new session and return it.

        :param session: The session to configure for authentication
        :type session: requests.Session
        :rtype: requests.Session
        """
        session = super(AdalAuthentication, self).signed_session(session)

        try:
            raw_token = self._adal_method(*self._args, **self._kwargs)
        except adal.AdalError as err:
            # pylint: disable=no-member
            if 'AADSTS70008:' in ((getattr(err, 'error_response', None)
                                   or {}).get('error_description') or ''):
                raise Expired("Credentials have expired due to inactivity.")
            else:
                raise AuthenticationError(err)
        except ConnectionError as err:
            raise AuthenticationError(
                'Please ensure you have network connection. Error detail: ' +
                str(err))

        scheme, token = raw_token['tokenType'], raw_token['accessToken']
        header = "{} {}".format(scheme, token)
        session.headers['Authorization'] = header
        return session
    def signed_session(self):
        """Get a signed session for requests.

        Usually called by the Azure SDKs for you to authenticate queries.

        :rtype: requests.Session
        """
        session = super(AdalAuthentication, self).signed_session()

        try:
            raw_token = self._adal_method(*self._args, **self._kwargs)
        except adal.AdalError as err:
            # pylint: disable=no-member
            if 'AADSTS70008:' in ((getattr(err, 'error_response', None)
                                   or {}).get('error_description') or ''):
                raise Expired("Credentials have expired due to inactivity.")
            else:
                raise AuthenticationError(err)
        except ConnectionError as err:
            raise AuthenticationError(
                'Please ensure you have network connection. Error detail: ' +
                str(err))

        scheme, token = raw_token['tokenType'], raw_token['accessToken']
        header = "{} {}".format(scheme, token)
        session.headers['Authorization'] = header
        return session
    def __init__(self, port=50342, **kwargs):
        super(MSIAuthentication, self).__init__(None)

        if port != 50342:
            warnings.warn(
                "The 'port' argument is no longer used, and will be removed in a future release",
                DeprecationWarning)
        self.port = port

        self.msi_conf = {
            k: v
            for k, v in kwargs.items()
            if k in ["client_id", "object_id", "msi_res_id"]
        }

        self.cloud_environment = kwargs.get('cloud_environment',
                                            AZURE_PUBLIC_CLOUD)
        self.resource = kwargs.get(
            'resource',
            self.cloud_environment.endpoints.active_directory_resource_id)

        if _is_app_service():
            if self.msi_conf:
                raise AuthenticationError(
                    "User Assigned Entity is not available on WebApp yet.")
        elif "MSI_ENDPOINT" not in os.environ:
            # Use IMDS if no MSI_ENDPOINT
            self._vm_msi = _ImdsTokenProvider(self.msi_conf)
        # Follow the same convention as all Credentials class to check for the token at creation time #106
        self.set_token()
示例#4
0
def test_create_service_principal_with_auth_error(mocked_auth_create):
    secrets = secrets_provider.provide_secrets_via_service_principal()
    inner_exception = MagicMock()
    mocked_auth_create.side_effect = \
        AuthenticationError("Auth error", inner_exception)

    with pytest.raises(InterruptExecution) as _:
        with auth(secrets) as _:
            pass
 def set_token(self):
     if _is_app_service():
         if self.msi_conf:
             raise AuthenticationError(
                 "User Assigned Entity is not available on WebApp yet.")
         self.scheme, _, self.token = get_msi_token_webapp(self.resource)
     else:
         self.scheme, _, self.token = get_msi_token(self.resource,
                                                    self.port,
                                                    self.msi_conf)
示例#6
0
    def test_initialize_session_authentication_error(self, mock_log, mock_cred):
        with self.assertRaises(SystemExit):
            adal_err = AdalError("test")
            adal_err.error_response = {'error': 'test'}
            err = AuthenticationError('test')
            err.inner_exception = adal_err
            mock_cred.side_effect = err

            with patch.dict(os.environ,
                            {
                                constants.ENV_TENANT_ID: DEFAULT_TENANT_ID,
                                constants.ENV_SUB_ID: DEFAULT_SUBSCRIPTION_ID,
                                constants.ENV_CLIENT_ID: 'client',
                                constants.ENV_CLIENT_SECRET: 'secret'
                            }, clear=True):
                s = Session()
                s.get_credentials().get_token()

        mock_log.assert_called_once()
示例#7
0
文件: azure.py 项目: Tubbz-alt/pcw
 def __check_credentials(self):
     for i in range(1, 40):
         try:
             self.list_resource_groups()
             return True
         except AuthenticationError:
             self.log_info(
                 "Check credentials failed (attemp:{}) - client_id {} should expire at {}",
                 i, self.__credentials.getData('client_id'),
                 self.__credentials.getAuthExpire())
             time.sleep(1)
     raise AuthenticationError("Invalid Azure credentials")
示例#8
0
    def test_validate_api_credentials(self, azure_clients_manager_class):
        """Check that method will raise AutoloadException if Azure API credentials aren't valid"""
        cloud_provider_model = mock.MagicMock()
        azure_clients_manager_class.side_effect = AuthenticationError(
            mock.MagicMock())

        # Act
        with self.assertRaises(AutoloadException) as ex:
            self.autoload_operation._validate_api_credentials(
                cloud_provider_model=cloud_provider_model, logger=self.logger)
        # Verify
        self.assertEqual(
            ex.exception.message,
            "Failed to connect to Azure API, please check the log for more details"
        )
示例#9
0
    def test_constructor(self, mocked_open, mocked_kv_auth, mocked_kv_client,
                         mocked_sp_credentials):
        file_mock = StringIO(
            CONFIG_TEMPLATE.format(KV_CLIENT_ID, KV_SECRET_ID, KV_TENANT_ID,
                                   KV_URI))
        mocked_open.return_value = file_mock

        sp_credentials_mock = MagicMock()
        mocked_sp_credentials.return_value = sp_credentials_mock

        kv_auth_mock = MagicMock()
        mocked_kv_auth.return_value = kv_auth_mock

        kv_client_mock = MagicMock()
        mocked_kv_client.return_value = kv_client_mock

        az_authentication = AzureAuthentication.from_config_file(CONFIG_FILE)

        mocked_sp_credentials.assert_called_with(client_id=KV_CLIENT_ID,
                                                 secret=KV_SECRET_ID,
                                                 tenant=KV_TENANT_ID,
                                                 resource=DEFAULT_RESOURCE)
        mocked_kv_auth.assert_called_with(credentials=sp_credentials_mock)
        mocked_kv_client.assert_called_with(kv_auth_mock)

        self.assertEqual(az_authentication.vault_uri, KV_URI)
        self.assertEqual(az_authentication.kv_client, kv_client_mock)

        mocked_kv_client.side_effect = AuthenticationError(
            "Get Token request returned http error: 400")
        file_mock = StringIO(
            CONFIG_TEMPLATE.format(
                KV_CLIENT_ID,
                KV_SECRET_ID,
                KV_TENANT_ID,
                KV_URI,
            ))
        mocked_open.return_value = file_mock

        with self.assertRaises(AzureAuthenticationException):
            AzureAuthentication.from_config_file(CONFIG_FILE)
示例#10
0
 def mock_list_resource_groups(self):
     nonlocal count_list_resource_groups
     count_list_resource_groups = count_list_resource_groups + 1
     if count_list_resource_groups > failed_list_resource_groups:
         return True
     raise AuthenticationError("OHA Mocked auth error")