async def test_client_secret_credential_async(aad_credential, live_eventhub): try: from azure.identity.aio import EnvironmentCredential except ImportError: pytest.skip("No azure identity library") credential = EnvironmentCredential() producer_client = EventHubProducerClient(host=live_eventhub['hostname'], event_hub_path=live_eventhub['event_hub'], credential=credential, user_agent='customized information') consumer_client = EventHubConsumerClient(host=live_eventhub['hostname'], event_hub_path=live_eventhub['event_hub'], credential=credential, user_agent='customized information') async with producer_client: await producer_client.send(EventData(body='A single message')) async def event_handler(partition_context, events): assert partition_context.partition_id == '0' assert len(events) == 1 assert list(events[0].body)[0] == 'A single message'.encode('utf-8') async with consumer_client: task = asyncio.ensure_future( consumer_client.receive(event_handler=event_handler, consumer_group='$default', partition_id='0')) await asyncio.sleep(2) task.cancel()
async def test_client_secret_credential_async(live_eventhub): credential = EnvironmentCredential() producer_client = EventHubProducerClient( fully_qualified_namespace=live_eventhub['hostname'], eventhub_name=live_eventhub['event_hub'], credential=credential, user_agent='customized information') consumer_client = EventHubConsumerClient( fully_qualified_namespace=live_eventhub['hostname'], eventhub_name=live_eventhub['event_hub'], consumer_group='$default', credential=credential, user_agent='customized information') async with producer_client: batch = await producer_client.create_batch(partition_id='0') batch.add(EventData(body='A single message')) await producer_client.send_batch(batch) def on_event(partition_context, event): on_event.called = True on_event.partition_id = partition_context.partition_id on_event.event = event on_event.called = False async with consumer_client: task = asyncio.ensure_future( consumer_client.receive(on_event, partition_id='0', starting_position='-1')) await asyncio.sleep(13) await task assert on_event.called is True assert on_event.partition_id == "0" assert list(on_event.event.body)[0] == 'A single message'.encode('utf-8')
async def cred() -> Any: credential = EnvironmentCredential() vault = SecretClient(vault_url="https://aca-keys.vault.azure.net", credential=credential) yield await vault.get_secret("acastorage-key1") await credential.close() await vault.close()
def create_vault_client(self, vault_uri): if self.is_live: credential = EnvironmentCredential() else: credential = Mock(get_token=asyncio.coroutine( lambda _: AccessToken("fake-token", 0))) return VaultClient(vault_uri, credential)
def create_vault_client(self, vault_uri): if self.is_live: credential = EnvironmentCredential() else: credential = Mock(get_token=asyncio.coroutine(lambda _: AccessToken("fake-token", 0))) return VaultClient( vault_uri, credential, transport=AiohttpTestTransport(), is_live=self.is_live, **self.client_kwargs )
def _initialize_credentials(self): if self.subscription_id is not None \ and self.arm_base_url is not None: if self.vscode_tenant_id is None: self.vscode_tenant_id = self._get_tenant_id( arm_base_url=self.arm_base_url, subscription_id=self.subscription_id) if self.shared_cache_tenant_id is None: self.shared_cache_tenant_id = self._get_tenant_id( arm_base_url=self.arm_base_url, subscription_id=self.subscription_id) if self.interactive_browser_tenant_id is None: self.interactive_browser_tenant_id = self._get_tenant_id( arm_base_url=self.arm_base_url, subscription_id=self.subscription_id) credentials = [] # type: List[AsyncTokenCredential] if not self.exclude_token_file_credential: credentials.append(_TokenFileCredential()) if not self.exclude_environment_credential: credentials.append(EnvironmentCredential(authority=self.authority)) if not self.exclude_managed_identity_credential: credentials.append( ManagedIdentityCredential( client_id=self.managed_identity_client_id)) if not self.exclude_shared_token_cache_credential and SharedTokenCacheCredential.supported( ): try: # username and/or tenant_id are only required when the cache contains tokens for multiple identities shared_cache = SharedTokenCacheCredential( username=self.shared_cache_username, tenant_id=self.shared_cache_tenant_id, authority=self.authority) credentials.append(shared_cache) except Exception as ex: # pylint:disable=broad-except _LOGGER.info("Shared token cache is unavailable: '%s'", ex) if not self.exclude_visual_studio_code_credential: credentials.append( VisualStudioCodeCredential(tenant_id=self.vscode_tenant_id)) if not self.exclude_cli_credential: credentials.append(AzureCliCredential()) if not self.exclude_powershell_credential: credentials.append(AzurePowerShellCredential()) if not self.exclude_interactive_browser_credential: credentials.append( InteractiveBrowserCredential( tenant_id=self.interactive_browser_tenant_id)) if not self.exclude_device_code_credential: credentials.append( DeviceCodeCredential( tenant_id=self.interactive_browser_tenant_id)) self.credentials = credentials
async def test_close(): transport = AsyncMockTransport() with mock.patch.dict( ENVIRON, {var: "..." for var in EnvironmentVariables.CLIENT_SECRET_VARS}, clear=True): credential = EnvironmentCredential(transport=transport) assert transport.__aexit__.call_count == 0 await credential.close() assert transport.__aexit__.call_count == 1
def test_passes_authority_argument(credential_name, environment_variables): """the credential pass the 'authority' keyword argument to its inner credential""" authority = "authority" with mock.patch.dict( ENVIRON, {variable: "foo" for variable in environment_variables}, clear=True): with mock.patch(EnvironmentCredential.__module__ + "." + credential_name) as mock_credential: EnvironmentCredential(authority=authority) assert mock_credential.call_count == 1 _, kwargs = mock_credential.call_args assert kwargs["authority"] == authority
async def run(): credential = EnvironmentCredential() # Note: One has other options to specify the credential. For instance, DefaultAzureCredential. # Default Azure Credentials attempt a chained set of authentication methods, per documentation here: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity # For example user to be logged in can be specified by the environment variable AZURE_USERNAME, consumed via the ManagedIdentityCredential # Alternately, one can specify the AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET to use the EnvironmentCredentialClass. # The docs above specify all mechanisms which the defaultCredential internally support. # credential = DefaultAzureCredential() servicebus_client = ServiceBusClient(FULLY_QUALIFIED_NAMESPACE, credential) async with servicebus_client: sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME) async with sender: await sender.send_messages(ServiceBusMessage('Single Message')) await credential.close()
async def run(): credential = EnvironmentCredential() producer = EventHubProducerClient( fully_qualified_namespace=fully_qualified_namespace, eventhub_name=eventhub_name, credential=credential) async with producer: event_data_batch = await producer.create_batch() while True: try: event_data_batch.add( EventData('Message inside EventBatchData')) except ValueError: # EventDataBatch object reaches max_size. # New EventDataBatch object can be created here to send more data. break await producer.send_batch(event_data_batch)
async def test_client_secret_environment_credential(monkeypatch): client_id = "fake-client-id" secret = "fake-client-secret" tenant_id = "fake-tenant-id" monkeypatch.setenv(EnvironmentVariables.AZURE_CLIENT_ID, client_id) monkeypatch.setenv(EnvironmentVariables.AZURE_CLIENT_SECRET, secret) monkeypatch.setenv(EnvironmentVariables.AZURE_TENANT_ID, tenant_id) success_message = "request passed validation" def validate_request(request, **kwargs): assert tenant_id in request.url assert request.data["client_id"] == client_id assert request.data["client_secret"] == secret # raising here makes mocking a transport response unnecessary raise ClientAuthenticationError(success_message) credential = EnvironmentCredential(transport=Mock(send=validate_request)) with pytest.raises(ClientAuthenticationError) as ex: await credential.get_token("scope") assert str(ex.value) == success_message
async def test_client_secret_credential_async(aad_credential, live_eventhub): try: from azure.identity.aio import EnvironmentCredential except ImportError: pytest.skip("No azure identity library") credential = EnvironmentCredential() producer_client = EventHubProducerClient( fully_qualified_namespace=live_eventhub['hostname'], eventhub_name=live_eventhub['event_hub'], credential=credential, user_agent='customized information') consumer_client = EventHubConsumerClient( fully_qualified_namespace=live_eventhub['hostname'], eventhub_name=live_eventhub['event_hub'], consumer_group='$default', credential=credential, user_agent='customized information') async with producer_client: await producer_client.send(EventData(body='A single message'), partition_id='0') def on_event(partition_context, event): on_event.called = True on_event.partition_id = partition_context.partition_id on_event.event = event on_event.called = False async with consumer_client: task = asyncio.ensure_future( consumer_client.receive(on_event, partition_id='0')) await asyncio.sleep(6) await task assert on_event.called is True assert on_event.partition_id == "0" assert list(on_event.event.body)[0] == 'A single message'.encode('utf-8')
def test_client_secret_configuration(): """the credential should pass expected values and any keyword arguments to its inner credential""" client_id = "client-id" client_secret = "..." tenant_id = "tenant_id" bar = "bar" environment = { EnvironmentVariables.AZURE_CLIENT_ID: client_id, EnvironmentVariables.AZURE_CLIENT_SECRET: client_secret, EnvironmentVariables.AZURE_TENANT_ID: tenant_id, } with mock.patch(EnvironmentCredential.__module__ + ".ClientSecretCredential") as mock_credential: with mock.patch.dict("os.environ", environment, clear=True): EnvironmentCredential(foo=bar) assert mock_credential.call_count == 1 _, kwargs = mock_credential.call_args assert kwargs["client_id"] == client_id assert kwargs["client_secret"] == client_secret assert kwargs["tenant_id"] == tenant_id assert kwargs["foo"] == bar
def test_certificate_configuration(): """the credential should pass expected values and any keyword arguments to its inner credential""" client_id = "client-id" certificate_path = "..." tenant_id = "tenant_id" bar = "bar" environment = { EnvironmentVariables.AZURE_CLIENT_ID: client_id, EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PATH: certificate_path, EnvironmentVariables.AZURE_TENANT_ID: tenant_id, } with mock.patch(EnvironmentCredential.__module__ + ".CertificateCredential") as mock_credential: with mock.patch.dict(ENVIRON, environment, clear=True): EnvironmentCredential(foo=bar) assert mock_credential.call_count == 1 _, kwargs = mock_credential.call_args assert kwargs["client_id"] == client_id assert kwargs["certificate_path"] == certificate_path assert kwargs["tenant_id"] == tenant_id assert kwargs["foo"] == bar
def create_credential(self): if self.is_live: return EnvironmentCredential() return Mock(get_token=lambda *_: get_completed_future( AccessToken("fake-token", 0)))
If not provided, defaults to the 'organizations' tenant, which supports only Azure Active Directory work or school accounts. Please refer to azure.identity library for detailed information. """ import os import asyncio from azure.servicebus import Message from azure.servicebus.aio import ServiceBusClient from azure.identity.aio import EnvironmentCredential FULLY_QUALIFIED_NAMESPACE = os.environ['SERVICE_BUS_NAMESPACE'] QUEUE_NAME = os.environ["SERVICE_BUS_QUEUE_NAME"] credential = EnvironmentCredential() # Note: One has other options to specify the credential. For instance, DefaultAzureCredential. # Default Azure Credentials attempt a chained set of authentication methods, per documentation here: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity # For example user to be logged in can be specified by the environment variable AZURE_USERNAME, consumed via the ManagedIdentityCredential # Alternately, one can specify the AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET to use the EnvironmentCredentialClass. # The docs above specify all mechanisms which the defaultCredential internally support. # credential = DefaultAzureCredential() async def run(): servicebus_client = ServiceBusClient(FULLY_QUALIFIED_NAMESPACE, credential) async with servicebus_client: sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME) async with sender: await sender.send(Message("DATA" * 64))
async def test_context_manager_incomplete_configuration(): with mock.patch.dict(ENVIRON, {}, clear=True): async with EnvironmentCredential(): pass