def test_persistent_cache_linux(mock_extensions):
    """The credential should use an unencrypted cache when encryption is unavailable and the user explicitly opts in.

    This test was written when Linux was the only platform on which encryption may not be available.
    """

    required_arguments = ("tenant-id", "client-id", "secret")

    # the credential should prefer an encrypted cache even when the user allows an unencrypted one
    ClientSecretCredential(*required_arguments,
                           _enable_persistent_cache=True,
                           _allow_unencrypted_cache=True)
    assert mock_extensions.PersistedTokenCache.called_with(
        mock_extensions.LibsecretPersistence)
    mock_extensions.PersistedTokenCache.reset_mock()

    # (when LibsecretPersistence's dependencies aren't available, constructing it raises ImportError)
    mock_extensions.LibsecretPersistence = Mock(side_effect=ImportError)

    # encryption unavailable, no opt in to unencrypted cache -> credential should raise
    with pytest.raises(ValueError):
        ClientSecretCredential(*required_arguments,
                               _enable_persistent_cache=True)

    ClientSecretCredential(*required_arguments,
                           _enable_persistent_cache=True,
                           _allow_unencrypted_cache=True)
    assert mock_extensions.PersistedTokenCache.called_with(
        mock_extensions.FilePersistence)
async def test_request_url():
    authority = "localhost"
    tenant_id = "expected_tenant"
    access_token = "***"

    async def mock_send(request, **kwargs):
        parsed = urlparse(request.url)
        assert parsed.scheme == "https"
        assert parsed.netloc == authority
        assert parsed.path.startswith("/" + tenant_id)

        return mock_response(json_payload={
            "token_type": "Bearer",
            "expires_in": 42,
            "access_token": access_token
        })

    credential = ClientSecretCredential(tenant_id,
                                        "client-id",
                                        "secret",
                                        transport=Mock(send=mock_send),
                                        authority=authority)
    token = await credential.get_token("scope")
    assert token.token == access_token

    # authority can be configured via environment variable
    with patch.dict("os.environ",
                    {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority},
                    clear=True):
        credential = ClientSecretCredential(tenant_id,
                                            "client-id",
                                            "secret",
                                            transport=Mock(send=mock_send))
        await credential.get_token("scope")
    assert token.token == access_token
def test_enable_persistent_cache():
    """the credential should use the persistent cache only when given enable_persistent_cache=True"""

    required_arguments = ("tenant-id", "client-id", "secret")
    persistent_cache = "azure.identity._internal.persistent_cache"

    # credential should default to an in memory cache
    raise_when_called = Mock(side_effect=Exception(
        "credential shouldn't attempt to load a persistent cache"))
    with patch(persistent_cache + "._load_persistent_cache",
               raise_when_called):
        ClientSecretCredential(*required_arguments)

        # allowing an unencrypted cache doesn't count as opting in to the persistent cache
        ClientSecretCredential(*required_arguments,
                               _allow_unencrypted_cache=True)

    # keyword argument opts in to persistent cache
    with patch(persistent_cache + ".msal_extensions") as mock_extensions:
        ClientSecretCredential(*required_arguments,
                               _enable_persistent_cache=True)
    assert mock_extensions.PersistedTokenCache.call_count == 1

    # opting in on an unsupported platform raises an exception
    with patch(persistent_cache + ".sys.platform", "commodore64"):
        with pytest.raises(NotImplementedError):
            ClientSecretCredential(*required_arguments,
                                   _enable_persistent_cache=True)
        with pytest.raises(NotImplementedError):
            ClientSecretCredential(*required_arguments,
                                   _enable_persistent_cache=True,
                                   _allow_unencrypted_cache=True)
Пример #4
0
async def test_request_url(authority):
    """the credential should accept an authority, with or without scheme, as an argument or environment variable"""

    tenant_id = "expected-tenant"
    access_token = "***"
    parsed_authority = urlparse(authority)
    expected_netloc = parsed_authority.netloc or authority  # "localhost" parses to netloc "", path "localhost"

    async def mock_send(request, **kwargs):
        actual = urlparse(request.url)
        assert actual.scheme == "https"
        assert actual.netloc == expected_netloc
        assert actual.path.startswith("/" + tenant_id)
        return mock_response(json_payload={"token_type": "Bearer", "expires_in": 42, "access_token": access_token})

    credential = ClientSecretCredential(
        tenant_id, "client-id", "secret", transport=Mock(send=mock_send), authority=authority
    )
    token = await credential.get_token("scope")
    assert token.token == access_token

    # authority can be configured via environment variable
    with patch.dict("os.environ", {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
        credential = ClientSecretCredential(tenant_id, "client-id", "secret", transport=Mock(send=mock_send))
        await credential.get_token("scope")
    assert token.token == access_token
Пример #5
0
def test_tenant_id_validation():
    """The credential should raise ValueError when given an invalid tenant_id"""

    valid_ids = {"c878a2ab-8ef4-413b-83a0-199afb84d7fb", "contoso.onmicrosoft.com", "organizations", "common"}
    for tenant in valid_ids:
        ClientSecretCredential(tenant, "client-id", "secret")

    invalid_ids = {"", "my tenant", "my_tenant", "/", "\\", '"my-tenant"', "'my-tenant'"}
    for tenant in invalid_ids:
        with pytest.raises(ValueError):
            ClientSecretCredential(tenant, "client-id", "secret")
Пример #6
0
async def test_cache_multiple_clients():
    """the credential shouldn't use tokens issued to other service principals"""

    access_token_a = "token a"
    access_token_b = "not " + access_token_a
    transport_a = async_validating_transport(
        requests=[Request()],
        responses=[
            mock_response(json_payload=build_aad_response(
                access_token=access_token_a))
        ])
    transport_b = async_validating_transport(
        requests=[Request()],
        responses=[
            mock_response(json_payload=build_aad_response(
                access_token=access_token_b))
        ])

    cache = TokenCache()
    with patch(ClientSecretCredential.__module__ +
               "._load_persistent_cache") as mock_cache_loader:
        mock_cache_loader.return_value = Mock(wraps=cache)
        credential_a = ClientSecretCredential(
            "tenant",
            "client-a",
            "secret",
            transport=transport_a,
            cache_persistence_options=TokenCachePersistenceOptions(),
        )
        assert mock_cache_loader.call_count == 1, "credential should load the persistent cache"

        credential_b = ClientSecretCredential(
            "tenant",
            "client-b",
            "secret",
            transport=transport_b,
            cache_persistence_options=TokenCachePersistenceOptions(),
        )
        assert mock_cache_loader.call_count == 2, "credential should load the persistent cache"

    # A caches a token
    scope = "scope"
    token_a = await credential_a.get_token(scope)
    assert token_a.token == access_token_a
    assert transport_a.send.call_count == 1

    # B should get a different token for the same scope
    token_b = await credential_b.get_token(scope)
    assert token_b.token == access_token_b
    assert transport_b.send.call_count == 1

    assert len(cache.find(TokenCache.CredentialType.ACCESS_TOKEN)) == 2
Пример #7
0
def test_token_cache():
    """the credential should default to an in memory cache, and optionally use a persistent cache"""

    with patch("azure.identity._persistent_cache.msal_extensions") as mock_msal_extensions:
        with patch(ClientSecretCredential.__module__ + ".msal") as mock_msal:
            ClientSecretCredential("tenant", "client-id", "secret")
        assert mock_msal.TokenCache.call_count == 1
        assert not mock_msal_extensions.PersistedTokenCache.called

        ClientSecretCredential(
            "tenant", "client-id", "secret", cache_persistence_options=TokenCachePersistenceOptions()
        )
        assert mock_msal_extensions.PersistedTokenCache.call_count == 1
Пример #8
0
async def test_cache():
    expired = "this token's expired"
    now = int(time.time())
    expired_on = now - 3600
    expired_token = AccessToken(expired, expired_on)
    token_payload = {
        "access_token": expired,
        "expires_in": 0,
        "ext_expires_in": 0,
        "expires_on": expired_on,
        "not_before": now,
        "token_type": "Bearer",
    }
    mock_send = Mock(return_value=mock_response(json_payload=token_payload))
    transport = Mock(send=wrap_in_future(mock_send))
    scope = "scope"

    credential = ClientSecretCredential("tenant-id", "client-id", "secret", transport=transport)

    # get_token initially returns the expired token because the credential
    # doesn't check whether tokens it receives from the service have expired
    token = await credential.get_token(scope)
    assert token == expired_token

    access_token = "new token"
    token_payload["access_token"] = access_token
    token_payload["expires_on"] = now + 3600
    valid_token = AccessToken(access_token, now + 3600)

    # second call should observe the cached token has expired, and request another
    token = await credential.get_token(scope)
    assert token == valid_token
    assert mock_send.call_count == 2
async def test_multitenant_authentication():
    first_tenant = "first-tenant"
    first_token = "***"
    second_tenant = "second-tenant"
    second_token = first_token * 2

    async def send(request, **kwargs):
        assert "tenant_id" not in kwargs, "tenant_id kwarg shouldn't get passed to send method"

        parsed = urlparse(request.url)
        tenant = parsed.path.split("/")[1]
        assert tenant in (first_tenant, second_tenant), 'unexpected tenant "{}"'.format(tenant)

        token = first_token if tenant == first_tenant else second_token
        return mock_response(json_payload=build_aad_response(access_token=token))

    credential = ClientSecretCredential(
        first_tenant, "client-id", "secret", transport=Mock(send=send)
    )
    token = await credential.get_token("scope")
    assert token.token == first_token

    token = await credential.get_token("scope", tenant_id=first_tenant)
    assert token.token == first_token

    token = await credential.get_token("scope", tenant_id=second_tenant)
    assert token.token == second_token

    # should still default to the first tenant
    token = await credential.get_token("scope")
    assert token.token == first_token
Пример #10
0
async def test_client_secret_credential_cache():
    expired = "this token's expired"
    now = time.time()
    expired_on = int(now - 300)
    expired_token = AccessToken(expired, expired_on)
    token_payload = {
        "access_token": expired,
        "expires_in": 0,
        "ext_expires_in": 0,
        "expires_on": expired_on,
        "not_before": now,
        "token_type": "Bearer",
        "resource": str(uuid.uuid1()),
    }

    mock_response = Mock(
        text=lambda: json.dumps(token_payload),
        headers={"content-type": "application/json"},
        status_code=200,
        content_type=["application/json"],
    )
    mock_send = Mock(return_value=mock_response)

    credential = ClientSecretCredential(
        "client_id",
        "secret",
        tenant_id=str(uuid.uuid1()),
        transport=Mock(send=asyncio.coroutine(mock_send)))
    scopes = ("https://foo.bar/.default", "https://bar.qux/.default")
    token = await credential.get_token(*scopes)
    assert token == expired_token

    token = await credential.get_token(*scopes)
    assert token == expired_token
    assert mock_send.call_count == 2
Пример #11
0
async def test_client_secret_credential_async(aad_credential, live_eventhub):
    try:
        from azure.identity.aio import ClientSecretCredential
    except ImportError:
        pytest.skip("No azure identity library")

    client_id, secret, tenant_id = aad_credential
    credential = ClientSecretCredential(client_id=client_id,
                                        client_secret=secret,
                                        tenant_id=tenant_id)
    client = EventHubClient(host=live_eventhub['hostname'],
                            event_hub_path=live_eventhub['event_hub'],
                            credential=credential,
                            user_agent='customized information')
    sender = client.create_producer(partition_id='0')
    receiver = client.create_consumer(consumer_group="$default",
                                      partition_id='0',
                                      event_position=EventPosition("@latest"))

    async with receiver:

        received = await receiver.receive(timeout=3)
        assert len(received) == 0

        async with sender:
            event = EventData(body='A single message')
            await sender.send(event)

        await asyncio.sleep(1)

        received = await receiver.receive(timeout=3)

        assert len(received) == 1
        assert list(received[0].body)[0] == 'A single message'.encode('utf-8')
    async def create_attestation_client_shared(self):
        """
        Instantiate an attestation client using client secrets to access the shared attestation provider.
        """

        write_banner("create_attestation_client_shared")
        # [START sharedclient_create]
        tenant_id = os.getenv("ATTESTATION_TENANT_ID")
        client_id = os.getenv("ATTESTATION_CLIENT_ID")
        secret = os.getenv("ATTESTATION_CLIENT_SECRET")

        if not tenant_id or not client_id or not secret:
            raise Exception("Must provide client credentials.")

        # Create azure-identity class
        from azure.identity.aio import ClientSecretCredential

        from azure.security.attestation.aio import AttestationClient

        shared_short_name = os.getenv("ATTESTATION_LOCATION_SHORT_NAME")
        shared_url = 'https://shared' + shared_short_name + \
            '.' + shared_short_name + '.attest.azure.net'

        async with ClientSecretCredential(
                tenant_id=tenant_id, client_id=client_id,
                client_secret=secret) as credentials, AttestationClient(
                    credentials, instance_url=self.aad_url) as client:
            print("Retrieve OpenID metadata from: ", shared_url)
            openid_metadata = await client.get_openidmetadata()
            print(" Certificate URI: ", openid_metadata["jwks_uri"])
            print(" Issuer: ", openid_metadata["issuer"])
Пример #13
0
 def from_credentials_data(credentials: dict,
                           scopes: Optional[List[str]] = None):
     credential = ClientSecretCredential(
         tenant_id=credentials['tenant'],
         client_id=credentials['appId'],
         client_secret=credentials['password'])
     return AzureCredentials(credential, scopes)
    async def create_attestation_client_aad(self):
        """
        Instantiate an attestation client using client secrets.
        """

        write_banner("create_attestation_client_aad")
        # [START client_create]

        tenant_id = os.getenv("ATTESTATION_TENANT_ID")
        client_id = os.getenv("ATTESTATION_CLIENT_ID")
        secret = os.getenv("ATTESTATION_CLIENT_SECRET")

        if not tenant_id or not client_id or not secret:
            raise Exception("Must provide client credentials.")

        # Create azure-identity class
        from azure.identity.aio import ClientSecretCredential

        from azure.security.attestation.aio import AttestationClient

        async with ClientSecretCredential(
                tenant_id=tenant_id, client_id=client_id,
                client_secret=secret) as credentials, AttestationClient(
                    credentials, instance_url=self.aad_url) as client:
            print("Retrieve OpenID metadata from: ", self.aad_url)
            openid_metadata = await client.get_openidmetadata()
            print(" Certificate URI: ", openid_metadata["jwks_uri"])
            print(" Issuer: ", openid_metadata["issuer"])
            await client.close()
Пример #15
0
 def from_file(credentials_file: str, scopes: Optional[List[str]] = None):
     with open(credentials_file, 'r') as f:
         data = json.loads(f.read())
         credential = ClientSecretCredential(tenant_id=data['tenant'],
                                             client_id=data['appId'],
                                             client_secret=data['password'])
         return AzureCredentials(credential, scopes)
    async def test_multitenant_authentication(self, client, is_hsm, **kwargs):
        if not self.is_live:
            pytest.skip("This test is incompatible with vcrpy in playback")

        client_id = os.environ.get("KEYVAULT_CLIENT_ID")
        client_secret = os.environ.get("KEYVAULT_CLIENT_SECRET")
        if not (client_id and client_secret):
            pytest.skip(
                "Values for KEYVAULT_CLIENT_ID and KEYVAULT_CLIENT_SECRET are required"
            )

        # we set up a client for this method so it gets awaited, but we actually want to create a new client
        # this new client should use a credential with an initially fake tenant ID and still succeed with a real request
        credential = ClientSecretCredential(tenant_id=str(uuid4()),
                                            client_id=client_id,
                                            client_secret=client_secret)
        vault_url = self.managed_hsm_url if is_hsm else self.vault_url
        client = KeyClient(vault_url=vault_url, credential=credential)

        if self.is_live:
            await asyncio.sleep(2)  # to avoid throttling by the service
        key_name = self.get_resource_name("multitenant-key")
        key = await client.create_rsa_key(key_name)
        assert key.id

        # try making another request with the credential's token revoked
        # the challenge policy should correctly request a new token for the correct tenant when a challenge is cached
        client._client._config.authentication_policy._token = None
        fetched_key = await client.get_key(key_name)
        assert key.id == fetched_key.id
Пример #17
0
def _credential():
    credential  = ClientSecretCredential(
        client_id = os.environ['AZURE_CLIENT_ID'],
        client_secret = os.environ['AZURE_CLIENT_SECRET'],
        tenant_id = os.environ['AZURE_TENANT_ID']
    )
    return credential
Пример #18
0
async def test_allow_multitenant_authentication():
    """When allow_multitenant_authentication is True, the credential should respect get_token(tenant_id=...)"""

    first_tenant = "first-tenant"
    first_token = "***"
    second_tenant = "second-tenant"
    second_token = first_token * 2

    async def send(request, **_):
        parsed = urlparse(request.url)
        tenant = parsed.path.split("/")[1]
        assert tenant in (
            first_tenant,
            second_tenant), 'unexpected tenant "{}"'.format(tenant)
        token = first_token if tenant == first_tenant else second_token
        return mock_response(json_payload=build_aad_response(
            access_token=token))

    credential = ClientSecretCredential(first_tenant,
                                        "client-id",
                                        "secret",
                                        allow_multitenant_authentication=True,
                                        transport=Mock(send=send))
    token = await credential.get_token("scope")
    assert token.token == first_token

    token = await credential.get_token("scope", tenant_id=first_tenant)
    assert token.token == first_token

    token = await credential.get_token("scope", tenant_id=second_tenant)
    assert token.token == second_token

    # should still default to the first tenant
    token = await credential.get_token("scope")
    assert token.token == first_token
Пример #19
0
async def test_client_secret_credential(live_service_principal):
    credential = ClientSecretCredential(
        live_service_principal["tenant_id"],
        live_service_principal["client_id"],
        live_service_principal["client_secret"],
    )
    await get_token(credential)
Пример #20
0
async def test_close():
    transport = AsyncMockTransport()
    credential = ClientSecretCredential("tenant-id", "client-id", "client-secret", transport=transport)

    await credential.close()

    assert transport.__aexit__.call_count == 1
async def test_no_scopes():
    """The credential should raise ValueError when get_token is called with no scopes"""

    credential = ClientSecretCredential("tenant-id", "client-id",
                                        "client-secret")
    with pytest.raises(ValueError):
        await credential.get_token()
async def test_persistent_cache_multiple_clients():
    """the credential shouldn't use tokens issued to other service principals"""

    access_token_a = "token a"
    access_token_b = "not " + access_token_a
    transport_a = async_validating_transport(
        requests=[Request()],
        responses=[
            mock_response(json_payload=build_aad_response(
                access_token=access_token_a))
        ])
    transport_b = async_validating_transport(
        requests=[Request()],
        responses=[
            mock_response(json_payload=build_aad_response(
                access_token=access_token_b))
        ])

    cache = TokenCache()
    with patch(
            "azure.identity._internal.persistent_cache._load_persistent_cache"
    ) as mock_cache_loader:
        mock_cache_loader.return_value = Mock(wraps=cache)
        credential_a = ClientSecretCredential("tenant-id",
                                              "client-a",
                                              "...",
                                              _enable_persistent_cache=True,
                                              transport=transport_a)
        assert mock_cache_loader.call_count == 1, "credential should load the persistent cache"
        credential_b = ClientSecretCredential("tenant-id",
                                              "client-b",
                                              "...",
                                              _enable_persistent_cache=True,
                                              transport=transport_b)
        assert mock_cache_loader.call_count == 2, "credential should load the persistent cache"

    # A caches a token
    scope = "scope"
    token_a = await credential_a.get_token(scope)
    assert token_a.token == access_token_a
    assert transport_a.send.call_count == 1

    # B should get a different token for the same scope
    token_b = await credential_b.get_token(scope)
    assert token_b.token == access_token_b
    assert transport_b.send.call_count == 1
 def generate_oauth_token(self):
     if self.is_live:
         from azure.identity.aio import ClientSecretCredential
         return ClientSecretCredential(
             os.getenv("TRANSLATION_TENANT_ID"),
             os.getenv("TRANSLATION_CLIENT_ID"),
             os.getenv("TRANSLATION_CLIENT_SECRET"),
         )
Пример #24
0
def create_client(args):

    if args.storage_conn_str:
        checkpoint_store = BlobCheckpointStore.from_connection_string(
            args.storage_conn_str, args.storage_container_name)
    else:
        checkpoint_store = None

    transport_type = TransportType.Amqp if args.transport_type == 0 else TransportType.AmqpOverWebsocket
    http_proxy = None
    if args.proxy_hostname:
        http_proxy = {
            "proxy_hostname": args.proxy_hostname,
            "proxy_port": args.proxy_port,
            "username": args.proxy_username,
            "password": args.proxy_password,
        }

    if args.conn_str:
        client = EventHubConsumerClientTest.from_connection_string(
            args.conn_str,
            args.consumer_group,
            eventhub_name=args.eventhub,
            checkpoint_store=checkpoint_store,
            load_balancing_interval=args.load_balancing_interval,
            auth_timeout=args.auth_timeout,
            http_proxy=http_proxy,
            transport_type=transport_type,
            logging_enable=args.uamqp_logging_enable)
    elif args.hostname:
        client = EventHubConsumerClientTest(
            fully_qualified_namespace=args.hostname,
            eventhub_name=args.eventhub,
            consumer_group=args.consumer_group,
            credential=EventHubSharedKeyCredential(args.sas_policy,
                                                   args.sas_key),
            checkpoint_store=checkpoint_store,
            load_balancing_interval=args.load_balancing_interval,
            auth_timeout=args.auth_timeout,
            http_proxy=http_proxy,
            transport_type=transport_type,
            logging_enable=args.uamqp_logging_enable)
    elif args.aad_client_id:
        credential = ClientSecretCredential(args.tenant_id, args.aad_client_id,
                                            args.aad_secret)
        client = EventHubConsumerClientTest(
            fully_qualified_namespace=args.hostname,
            eventhub_name=args.eventhub,
            consumer_group=args.consumer_group,
            credential=credential,
            checkpoint_store=checkpoint_store,
            load_balancing_interval=args.load_balancing_interval,
            auth_timeout=args.auth_timeout,
            http_proxy=http_proxy,
            transport_type=transport_type,
            logging_enable=args.uamqp_logging_enable)

    return client
 def generate_oauth_token(self):
     if self.is_live:
         from azure.identity.aio import ClientSecretCredential
         return ClientSecretCredential(
             self.get_settings_value("AZURE_TENANT_ID"),
             self.get_settings_value("AZURE_CLIENT_ID"),
             self.get_settings_value("AZURE_CLIENT_SECRET"),
         )
     return self.generate_fake_token()
Пример #26
0
async def test_user_agent():
    transport = async_validating_transport(
        requests=[Request(required_headers={"User-Agent": USER_AGENT})],
        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
    )

    credential = ClientSecretCredential("tenant-id", "client-id", "client-secret", transport=transport)

    await credential.get_token("scope")
Пример #27
0
async def test_context_manager():
    transport = AsyncMockTransport()
    credential = ClientSecretCredential("tenant-id", "client-id", "client-secret", transport=transport)

    async with credential:
        assert transport.__aenter__.call_count == 1

    assert transport.__aenter__.call_count == 1
    assert transport.__aexit__.call_count == 1
Пример #28
0
 def generate_oauth_token(self):
     if self.is_live:
         from azure.identity.aio import ClientSecretCredential
         return ClientSecretCredential(
             os.getenv("FORMRECOGNIZER_TENANT_ID"),
             os.getenv("FORMRECOGNIZER_CLIENT_ID"),
             os.getenv("FORMRECOGNIZER_CLIENT_SECRET"),
         )
     return self.generate_fake_token()
Пример #29
0
async def test_client_secret_credential(live_identity_settings):
    credential = ClientSecretCredential(
        live_identity_settings["client_id"],
        live_identity_settings["client_secret"],
        live_identity_settings["tenant_id"],
    )
    token = await credential.get_token(ARM_SCOPE)
    assert token
    assert token.token
    assert token.expires_on
 def get_credential(self, authority=None, **kwargs):
     if self.is_live:
         if authority != AzureAuthorityHosts.AZURE_PUBLIC_CLOUD:
             return ClientSecretCredential(
                 tenant_id=os.environ["CONTAINERREGISTRY_TENANT_ID"],
                 client_id=os.environ["CONTAINERREGISTRY_CLIENT_ID"],
                 client_secret=os.
                 environ["CONTAINERREGISTRY_CLIENT_SECRET"],
                 authority=authority)
         return DefaultAzureCredential(**kwargs)
     return AsyncFakeTokenCredential()