Ejemplo n.º 1
0
    async def test_revoke_tokens_from_managed_identity(
            self, communication_livetest_dynamic_connection_string):
        endpoint, access_key = parse_connection_str(
            communication_livetest_dynamic_connection_string)
        from devtools_testutils import is_live
        if not is_live():
            credential = FakeTokenCredential()
        else:
            credential = DefaultAzureCredential()
        identity_client = CommunicationIdentityClient(
            endpoint,
            credential,
            http_logging_policy=get_http_logging_policy())
        async with identity_client:
            user = await identity_client.create_user()
            token_response = await identity_client.get_token(
                user, scopes=[CommunicationTokenScope.CHAT])
            await identity_client.revoke_tokens(user)

        assert user.properties.get('id') is not None
        assert token_response.token is not None
    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]
        # Import default credential and Attestation client
        from azure.identity.aio import DefaultAzureCredential
        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 DefaultAzureCredential() as credentials, AttestationClient(
                self.aad_url, credentials) as client:
            print("Retrieve OpenID metadata from: ", shared_url)
            openid_metadata = await client.get_open_id_metadata()
            print(" Certificate URI: ", openid_metadata["jwks_uri"])
            print(" Issuer: ", openid_metadata["issuer"])
Ejemplo n.º 3
0
    async def basic_sample(self):

        from azure.containerregistry.aio import ContainerRegistryClient
        from azure.identity.aio import DefaultAzureCredential

        # Instantiate the client
        client = ContainerRegistryClient(self.account_url, DefaultAzureCredential())
        async with client:
            # Iterate through all the repositories
            async for repository_name in client.list_repository_names():
                if repository_name == "hello-world":
                    # Create a repository client from the registry client
                    repository_client = client.get_repository(repository_name)

                    async with repository_client:
                        # Show all tags
                        async for tag in repository_client.list_tags():
                            print(tag.digest)

                    # [START delete_repository]
                    await client.delete_repository("hello-world")
Ejemplo n.º 4
0
    async def authentication_with_azure_active_directory_async(self):
        """DefaultAzureCredential will use the values from the environment
        variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
        """
        # [START create_ta_client_with_aad_async]
        from azure.ai.textanalytics.aio import TextAnalyticsClient
        from azure.identity.aio import DefaultAzureCredential

        endpoint = os.getenv("AZURE_TEXT_ANALYTICS_ENDPOINT")
        credential = DefaultAzureCredential()

        text_analytics_client = TextAnalyticsClient(endpoint,
                                                    credential=credential)
        # [END create_ta_client_with_aad_async]

        doc = ["I need to take my cat to the veterinarian."]
        async with text_analytics_client:
            result = await text_analytics_client.detect_languages(doc)

        print("Language detected: {}".format(result[0].primary_language.name))
        print("Confidence score: {}".format(result[0].primary_language.score))
Ejemplo n.º 5
0
    async def test_send_sms_from_managed_identity_async(self):
        endpoint, access_key = parse_connection_str(self.connection_str)
        from devtools_testutils import is_live
        if not is_live():
            credential = FakeTokenCredential()
        else:
            credential = DefaultAzureCredential()
        sms_client = SmsClient(endpoint,
                               credential,
                               http_logging_policy=get_http_logging_policy())

        async with sms_client:
            # calling send() with sms values
            sms_responses = await sms_client.send(
                from_=self.phone_number,
                to=[self.phone_number],
                message="Hello World via SMS")

            assert len(sms_responses) == 1

            self.verify_successful_sms_response(sms_responses[0])
Ejemplo n.º 6
0
async def run_sample():
    # Instantiate a secret client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = SecretClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create a secret holding storage account credentials.
        # if the secret already exists in the Key Vault, then a new version of the secret is created.
        print("\n.. Create Secret")
        secret = await client.set_secret("backupRestoreSecretName",
                                         "backupRestoreSecretValue")
        print("Secret with name '{0}' created with value '{1}'".format(
            secret.name, secret.value))

        # Backups are good to have, if in case secrets gets deleted accidentally.
        # For long term storage, it is ideal to write the backup to a file.
        print("\n.. Create a backup for an existing Secret")
        secret_backup = await client.backup_secret(secret.name)
        print("Backup created for secret with name '{0}'.".format(secret.name))

        # The storage account secret is no longer in use, so you delete it.
        print("\n.. Deleting secret...")
        await client.delete_secret(secret.name)
        print("Deleted Secret with name '{0}'".format(secret.name))

        # In future, if the secret is required again, we can use the backup value to restore it in the Key Vault.
        print("\n.. Restore the secret using the backed up secret bytes")
        secret = await client.restore_secret_backup(secret_backup)
        print("Restored Secret with name '{0}'".format(secret.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
        await credential.close()
        await client.close()
Ejemplo n.º 7
0
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_endpoint=VAULT_ENDPOINT, credential=credential)
    try:
        print("\n.. Create keys")
        rsa_key = await client.create_rsa_key("rsaKeyName")
        ec_key = await client.create_ec_key("ecKeyName")
        print("Created key '{0}' of type '{1}'.".format(rsa_key.name, rsa_key.key_type))
        print("Created key '{0}' of type '{1}'.".format(ec_key.name, ec_key.key_type))

        print("\n.. Delete the keys")
        for key_name in (ec_key.name, rsa_key.name):
            deleted_key = await client.delete_key(key_name)
            print("Deleted key '{0}'".format(deleted_key.name))

        print("\n.. Recover a deleted key")
        recovered_key = await client.recover_deleted_key(rsa_key.name)
        print("Recovered key '{0}'".format(recovered_key.name))

        # deleting the recovered key so it doesn't outlast this script
        await client.delete_key(recovered_key.name)

        print("\n.. Purge keys")
        for key_name in (ec_key.name, rsa_key.name):
            await client.purge_deleted_key(key_name)
            print("Purged '{}'".format(key_name))

    except HttpResponseError as e:
        if "(NotSupported)" in e.message:
            print("\n{0} Please enable soft delete on Key Vault to perform this operation.".format(e.message))
        else:
            print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
Ejemplo n.º 8
0
    async def attest_open_enclave_with_draft_failing_policy(self):
        """
        Sets a draft policy which is guaranteed to fail attestation with the
        sample test collateral to show how to manage attestation failures.
        """
        write_banner("attest_open_enclave_with_draft_failing_policy")
        oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
        runtime_data = base64.urlsafe_b64decode(sample_runtime_data)

        draft_policy = """
version= 1.0;
authorizationrules
{
    [ type=="x-ms-sgx-is-debuggable", value == false] => deny();
    [ type=="x-ms-sgx-product-id", value==1 ] &&
    [ type=="x-ms-sgx-svn", value>= 0 ] &&
    [ type=="x-ms-sgx-mrsigner", value=="2c1a44952ae8207135c6c29b75b8c029372ee94b677e15c20bd42340f10d41aa"]
        => permit();
};
issuancerules {
    c:[type=="x-ms-sgx-mrsigner"] => issue(type="My-MrSigner", value=c.value);
};
"""

        print("Attest Open enclave using ", self.shared_url)
        print("Using draft policy which will fail.:", draft_policy)
        try:
            async with DefaultAzureCredential(
            ) as credential, AttestationClient(self.shared_url,
                                               credential) as attest_client:
                await attest_client.attest_open_enclave(
                    oe_report,
                    runtime_data=runtime_data,
                    draft_policy=draft_policy)
                print("Unexpectedly passed attestation.")
        except HttpResponseError as err:
            print("Caught expected exception: ", err.message)
            print("Error is:", err.error.code)
            pass
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

    # Let's create a Key of type RSA.
    # if the key already exists in the Key Vault, then a new version of the key is created.
    print("\n.. Create Key")
    key = await client.create_key("keyName", "RSA")
    print("Key with name '{0}' created with key type '{1}'".format(
        key.name, key.key_type))

    # Backups are good to have, if in case keys gets deleted accidentally.
    # For long term storage, it is ideal to write the backup to a file.
    print("\n.. Create a backup for an existing Key")
    key_backup = await client.backup_key(key.name)
    print("Backup created for key with name '{0}'.".format(key.name))

    # The rsa key is no longer in use, so you delete it.
    deleted_key = await client.delete_key(key.name)
    print("Deleted key with name '{0}'".format(deleted_key.name))

    # Purge the deleted key.
    # The purge will take some time, so wait before restoring the backup to avoid a conflict.
    print("\n.. Purge the key")
    await client.purge_deleted_key(key.name)
    await asyncio.sleep(60)
    print("Purged key with name '{0}'".format(deleted_key.name))

    # In the future, if the key is required again, we can use the backup value to restore it in the Key Vault.
    print("\n.. Restore the key using the backed up key bytes")
    key = await client.restore_key_backup(key_backup)
    print("Restored key with name '{0}'".format(key.name))

    print("\nrun_sample done")
    await credential.close()
    await client.close()
    async def delete_tags(self):
        # [START list_repository_names]
        audience = "https://management.azure.com"
        endpoint = os.environ["CONTAINERREGISTRY_ENDPOINT"]
        credential = DefaultAzureCredential()
        client = ContainerRegistryClient(endpoint,
                                         credential,
                                         audience=audience)

        async with client:
            async for repository in client.list_repository_names():
                print(repository)
                # [END list_repository_names]

                # Keep the three most recent tags, delete everything else
                tag_count = 0
                async for tag in client.list_tag_properties(
                        repository,
                        order_by=ArtifactTagOrder.LAST_UPDATED_ON_DESCENDING):
                    tag_count += 1
                    if tag_count > 3:
                        await client.delete_tag(repository, tag.name)
Ejemplo n.º 11
0
    def _prepare_credentials(self, config):
        from azure.identity.aio import DefaultAzureCredential

        login_info = {}
        login_info["connection_string"] = config.get(
            "connection_string",
            self._az_config.get("storage", "connection_string", None),
        )
        login_info["account_name"] = config.get(
            "account_name", self._az_config.get("storage", "account", None))
        login_info["account_key"] = config.get(
            "account_key", self._az_config.get("storage", "key", None))
        login_info["sas_token"] = config.get(
            "sas_token", self._az_config.get("storage", "sas_token", None))
        login_info["tenant_id"] = config.get("tenant_id")
        login_info["client_id"] = config.get("client_id")
        login_info["client_secret"] = config.get("client_secret")

        if not any(login_info.values()):
            login_info["credentials"] = DefaultAzureCredential()

        for login_method, required_keys in [  # noqa
            ("connection string", ["connection_string"]),
            (
                "AD service principal",
                ["tenant_id", "client_id", "client_secret"],
            ),
            ("account key", ["account_name", "account_key"]),
            ("SAS token", ["account_name", "sas_token"]),
            ("anonymous login", ["account_name"]),
            (f"default credentials ({_DEFAULT_CREDS_STEPS})", ["credentials"]),
        ]:
            if all(login_info.get(key) is not None for key in required_keys):
                break
        else:
            login_method = None

        self.login_method = login_method
        return login_info
Ejemplo n.º 12
0
async def logs_query():
    credential = DefaultAzureCredential()

    client = LogsQueryClient(credential)

    query = """AppRequests | take 5"""

    try:
        response = await client.query_workspace(
            os.environ['LOGS_WORKSPACE_ID'], query, timespan=timedelta(days=1))
        if response.status == LogsQueryStatus.PARTIAL:
            error = response.partial_error
            data = response.partial_data
            print(error.message)
        elif response.status == LogsQueryStatus.SUCCESS:
            data = response.tables
        for table in data:
            df = pd.DataFrame(data=table.rows, columns=table.columns)
            print(df)
    except HttpResponseError as err:
        print("something fatal happened")
        print(err)
def test_vscode_arguments(monkeypatch):
    monkeypatch.delenv(EnvironmentVariables.AZURE_AUTHORITY_HOST,
                       raising=False)
    monkeypatch.delenv(EnvironmentVariables.AZURE_TENANT_ID, raising=False)

    credential = DefaultAzureCredential.__module__ + ".VisualStudioCodeCredential"

    # DefaultAzureCredential shouldn't specify a default authority or tenant to VisualStudioCodeCredential
    with patch(credential) as mock_credential:
        DefaultAzureCredential()
    mock_credential.assert_called_once_with()

    tenant = {"tenant_id": "the-tenant"}

    with patch(credential) as mock_credential:
        DefaultAzureCredential(
            visual_studio_code_tenant_id=tenant["tenant_id"])
    mock_credential.assert_called_once_with(**tenant)

    # tenant id can also be specified in $AZURE_TENANT_ID
    with patch.dict(
            os.environ,
        {EnvironmentVariables.AZURE_TENANT_ID: tenant["tenant_id"]}):
        with patch(credential) as mock_credential:
            DefaultAzureCredential()
    mock_credential.assert_called_once_with(**tenant)

    # keyword argument should override environment variable
    with patch.dict(
            os.environ,
        {EnvironmentVariables.AZURE_TENANT_ID: "not-" + tenant["tenant_id"]}):
        with patch(credential) as mock_credential:
            DefaultAzureCredential(
                visual_studio_code_tenant_id=tenant["tenant_id"])
    mock_credential.assert_called_once_with(**tenant)

    # DefaultAzureCredential should pass the authority kwarg along
    authority = {"authority": "the-authority"}
    with patch(credential) as mock_credential:
        DefaultAzureCredential(**authority)
    mock_credential.assert_called_once_with(**authority)

    with patch(credential) as mock_credential:
        DefaultAzureCredential(
            visual_studio_code_tenant_id=tenant["tenant_id"], **authority)
    mock_credential.assert_called_once_with(**dict(authority, **tenant))
async def run_sample():
    # Instantiate a certificate client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = CertificateClient(vault_url=VAULT_URL, credential=credential)
    try:
        contact_list = [
            CertificateContact(email="*****@*****.**",
                               name="John Doe",
                               phone="1111111111"),
            CertificateContact(email="*****@*****.**",
                               name="John Doe2",
                               phone="2222222222"),
        ]

        # Creates and sets the certificate contacts for this key vault.
        await client.set_contacts(contact_list)

        # Gets the certificate contacts for this key vault.
        contacts = await client.get_contacts()
        for contact in contacts:
            print(contact.name)
            print(contact.email)
            print(contact.phone)

        # Deletes all of the certificate contacts for this key vault.
        await client.delete_contacts()

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
        await credential.close()
        await client.close()
Ejemplo n.º 15
0
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create a Key of type RSA.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create Key")
        key = await client.create_key("keyName", "RSA")
        print("Key with name '{0}' created with key type '{1}'".format(key.name, key.key_material.kty))

        # Backups are good to have, if in case keys gets deleted accidentally.
        # For long term storage, it is ideal to write the backup to a file.
        print("\n1. Create a backup for an existing Key")
        key_backup = await client.backup_key(key.name)
        print("Backup created for key with name '{0}'.".format(key.name))

        # The rsa key is no longer in use, so you delete it.
        await client.delete_key(key.name)

        # To ensure key is deleted on the server side.
        print("\nDeleting key...")
        print("Deleted Key with name '{0}'".format(key.name))

        # In future, if the key is required again, we can use the backup value to restore it in the Key Vault.
        print("\n2. Restore the key using the backed up key bytes")
        key = await client.restore_key(key_backup)
        print("Restored Key with name '{0}'".format(key.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
Ejemplo n.º 16
0
async def run_sample():
    # Instantiate a certificate client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = CertificateClient(vault_url=VAULT_URL, credential=credential)

    # Let's import a PFX certificate first.
    # Assuming you already have a PFX containing your key pair, you can import it into Key Vault.
    # You can do this without setting a policy, but the policy is needed if you want the private key to be exportable
    # or to configure actions when a certificate is close to expiration.
    pfx_cert_name = "pfxCert"
    with open(os.environ["PFX_CERT_PATH"], "rb") as f:
        pfx_cert_bytes = f.read()
    imported_pfx_cert = await client.import_certificate(
        certificate_name=pfx_cert_name, certificate_bytes=pfx_cert_bytes)
    print("PFX certificate '{}' imported successfully.".format(
        imported_pfx_cert.name))

    # Now let's import a PEM-formatted certificate.
    # To import a PEM-formatted certificate, you must provide a CertificatePolicy that sets the content_type to
    # CertificateContentType.pem or the certificate will fail to import (the default content type is PFX).
    pem_cert_name = "pemCert"
    with open(os.environ["PEM_CERT_PATH"], "rb") as f:
        pem_cert_bytes = f.read()
    pem_cert_policy = CertificatePolicy(
        issuer_name=WellKnownIssuerNames.self,
        content_type=CertificateContentType.pem)
    imported_pem_cert = await client.import_certificate(
        certificate_name=pem_cert_name,
        certificate_bytes=pem_cert_bytes,
        policy=pem_cert_policy)
    print("PEM-formatted certificate '{}' imported successfully.".format(
        imported_pem_cert.name))

    await credential.close()
    await client.close()
Ejemplo n.º 17
0
    async def attest_open_enclave_with_draft_policy(self):
        """
        Calls attest_open_enclave specifying a draft attestation policy.

        This functionality can be used to test attestation policies against real attestation
        collateral. This can be extremely helpful in debugging attestation policies.
        """
        write_banner("attest_open_enclave_with_draft_policy")
        oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
        runtime_data = base64.urlsafe_b64decode(sample_runtime_data)

        # [START attest_open_enclave_shared_draft]
        draft_policy = """
        version= 1.0;
        authorizationrules
        {
            [ type=="x-ms-sgx-is-debuggable", value==false ] &&
            [ type=="x-ms-sgx-product-id", value==1 ] &&
            [ type=="x-ms-sgx-svn", value>= 0 ] &&
            [ type=="x-ms-sgx-mrsigner", value=="2c1a44952ae8207135c6c29b75b8c029372ee94b677e15c20bd42340f10d41aa"]
                => permit();
        };
        issuancerules {
            c:[type=="x-ms-sgx-mrsigner"] => issue(type="My-MrSigner", value=c.value);
        };
        """
        print("Attest Open enclave using ", self.shared_url)
        print("Using draft policy:", draft_policy)
        async with DefaultAzureCredential() as credential, AttestationClient(
                self.shared_url, credential) as attest_client:
            response, token = await attest_client.attest_open_enclave(
                oe_report,
                runtime_data=runtime_data,
                draft_policy=draft_policy)

            print("Token algorithm", token.algorithm)
            print("Issuer of token is: ", response.issuer)
Ejemplo n.º 18
0
    async def delete_old_tags(self):
        from azure.containerregistry import TagOrder
        from azure.containerregistry.aio import (
            ContainerRegistryClient,
        )
        from azure.identity.aio import DefaultAzureCredential

        # [START list_repository_names]
        account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
        credential = DefaultAzureCredential()
        client = ContainerRegistryClient(account_url, credential)

        async with client:
            async for repository in client.list_repository_names():
                print(repository)
                # [END list_repository_names]

                # [START list_tag_properties]
                # Keep the three most recent tags, delete everything else
                tag_count = 0
                async for tag in client.list_tag_properties(repository, order_by=TagOrder.LAST_UPDATE_TIME_DESCENDING):
                    tag_count += 1
                    if tag_count > 3:
                        await client.delete_tag(repository, tag.name)
Ejemplo n.º 19
0
    async def sms_token_credential_auth_async(self):
        # To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have
        # AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
        endpoint, _ = parse_connection_str(self.connection_string)
        sms_client = SmsClient(endpoint, DefaultAzureCredential())

        async with sms_client:
            try:
                # calling send() with sms values
                sms_responses = await sms_client.send(
                    from_=self.phone_number,
                    to=self.phone_number,
                    message="Hello World via SMS")
                sms_response = sms_responses[0]
                
                if (sms_response.successful):
                    print("Message with message id {} was successful sent to {}"
                    .format(sms_response.message_id, sms_response.to))
                else:
                    print("Message failed to send to {} with the status code {} and error: {}"
                    .format(sms_response.to, sms_response.http_status_code, sms_response.error_message))
            except Exception:
                print(Exception)
                pass
Ejemplo n.º 20
0
    async def delete_images(self):
        # [START list_repository_names]
        audience = "https://management.azure.com"
        endpoint = os.environ["CONTAINERREGISTRY_ENDPOINT"]
        credential = DefaultAzureCredential()
        client = ContainerRegistryClient(endpoint,
                                         credential,
                                         audience=audience)

        async with client:
            async for repository in client.list_repository_names():
                print(repository)
                # [END list_repository_names]

                # [START list_manifest_properties]
                # Keep the three most recent images, delete everything else
                manifest_count = 0
                async for manifest in client.list_manifest_properties(
                        repository,
                        order_by=ManifestOrder.LAST_UPDATE_TIME_DESCENDING):
                    manifest_count += 1
                    if manifest_count > 3:
                        await client.delete_manifest(repository,
                                                     manifest.digest)
    async def get_token_for_teams_user(self):
        if (os.getenv("SKIP_INT_IDENTITY_EXCHANGE_TOKEN_TEST") == "true"):
            print("Skipping the Get Access Token for Teams User sample")
            return
        from azure.communication.identity.aio import CommunicationIdentityClient
        if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None:
            from azure.identity.aio import DefaultAzureCredential
            endpoint, _ = parse_connection_str(self.connection_string)
            identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential())
        else:
            identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string)

        async with identity_client:    
            msal_app = PublicClientApplication(client_id=self.m365_app_id, authority="{}/{}".format(self.m365_aad_authority, self.m365_aad_tenant))
            result = msal_app.acquire_token_by_username_password(
                username=self.msal_username,
                password=self.msal_password,
                scopes=[self.m365_scope])
            add_token =  result["access_token"]
            print("AAD access token of a Teams User: "******"AAD access token of a Teams User: "******"Token issued with value: " + tokenresponse.token)
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

    print("\n.. Create keys")
    rsa_key = await client.create_rsa_key("rsaKeyName")
    ec_key = await client.create_ec_key("ecKeyName")
    print("Created key '{0}' of type '{1}'.".format(rsa_key.name, rsa_key.key_type))
    print("Created key '{0}' of type '{1}'.".format(ec_key.name, ec_key.key_type))

    print("\n.. Delete the keys")
    for key_name in (ec_key.name, rsa_key.name):
        deleted_key = await client.delete_key(key_name)
        print("Deleted key '{0}'".format(deleted_key.name))

    # A deleted key can only be recovered if the Key Vault is soft-delete enabled.
    print("\n.. Recover a deleted key")
    recovered_key = await client.recover_deleted_key(rsa_key.name)
    print("Recovered key '{0}'".format(recovered_key.name))

    # To permanently delete the key, the deleted key needs to be purged.
    await client.delete_key(recovered_key.name)

    # Keys will still purge eventually on their scheduled purge date, but calling `purge_deleted_key` immediately
    # purges.
    print("\n.. Purge keys")
    for key_name in (ec_key.name, rsa_key.name):
        await client.purge_deleted_key(key_name)
        print("Purged '{}'".format(key_name))

    print("\nrun_sample done")
    await credential.close()
    await client.close()
Ejemplo n.º 23
0
from azure.mgmt.media.aio import AzureMediaServices
from azure.mgmt.media.models import (
    Asset, IPRange, IPAccessControl, LiveEvent, LiveEventInputAccessControl,
    LiveEventPreviewAccessControl, LiveEventPreview, LiveEventInput,
    LiveOutput, LiveEventEncoding, LiveEventEncodingType,
    LiveEventInputProtocol, StreamOptionsFlag, LiveEventTranscription,
    LiveEventOutputTranscriptionTrack, Hls, StreamingLocator)
import os
import random

# Get the environment variables
load_dotenv()

# This sample uses the default Azure Credential object, which relies on the environment variable settings.
# Get the default Azure credential from the environment variables AZURE_CLIENT_ID and AZURE_CLIENT_SECRET and AZURE_TENTANT_ID
default_credential = DefaultAzureCredential()

# Get the environment variables SUBSCRIPTIONID, RESOURCEGROUP and ACCOUNTNAME
subscription_id = os.getenv('SUBSCRIPTIONID')
resource_group = os.getenv('RESOURCEGROUP')
account_name = os.getenv('ACCOUNTNAME')

# This is a random string that will be added to the naming of things so that you don't have to keep doing this during testing
uniqueness = random.randint(0, 9999)
live_event_name = f'liveEvent-{uniqueness}'  # WARNING: Be careful not to leak live events using this sample!
asset_name = f'archiveAsset-{uniqueness}'
live_output_name = f'liveOutput-{uniqueness}'
streaming_locator_name = f'liveStreamLocator-{uniqueness}'
streaming_endpoint_name = 'default'  # Change this to your specific streaming endpoint name if not using "default"
manifest_name = "output"
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_endpoint=VAULT_ENDPOINT, credential=credential)
    try:
        # Let's create an RSA key with size 2048, hsm disabled and optional key_operations of encrypt, decrypt.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n.. Create an RSA Key")
        key_size = 2048
        key_ops = [
            "encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"
        ]
        key_name = "rsaKeyName"
        rsa_key = await client.create_rsa_key(key_name,
                                              size=key_size,
                                              key_operations=key_ops)
        print("RSA Key with name '{0}' created of type '{1}'.".format(
            rsa_key.name, rsa_key.key_type))

        # Let's create an Elliptic Curve key with algorithm curve type P-256.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n.. Create an EC Key")
        key_curve = "P-256"
        key_name = "ECKeyName"
        ec_key = await client.create_ec_key(key_name, curve=key_curve)
        print("EC Key with name '{0}' created of type {1}.".format(
            ec_key.name, ec_key.key_type))

        # Let's get the rsa key details using its name
        print("\n.. Get a Key using it's name")
        rsa_key = await client.get_key(rsa_key.name)
        print("Key with name '{0}' was found.".format(rsa_key.name))

        # Let's say we want to update the expiration time for the EC key and disable the key to be usable
        # for cryptographic operations. The update method allows the user to modify the metadata (key attributes)
        # associated with a key previously stored within Key Vault.
        print("\n.. Update a Key by name")
        expires_on = datetime.datetime.utcnow() + datetime.timedelta(days=365)
        updated_ec_key = await client.update_key_properties(
            ec_key.name,
            version=ec_key.properties.version,
            expires_on=expires_on,
            enabled=False)
        print("Key with name '{0}' was updated on date '{1}'".format(
            updated_ec_key.name, updated_ec_key.properties.updated_on))
        print("Key with name '{0}' was updated to expire on '{1}'".format(
            updated_ec_key.name, updated_ec_key.properties.expires_on))

        # The keys are no longer used, let's delete them
        print("\n.. Deleting keys")
        for key_name in (ec_key.name, rsa_key.name):
            deleted_key = await client.delete_key(key_name)
            print("\nDeleted '{}'".format(deleted_key.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
Ejemplo n.º 25
0
    def _prepare_credentials(self, **config):
        from azure.identity.aio import DefaultAzureCredential

        # Disable spam from failed cred types for DefaultAzureCredential
        logging.getLogger("azure.identity.aio").setLevel(logging.ERROR)

        login_info = {}
        login_info["connection_string"] = config.get(
            "connection_string",
            _az_config().get("storage", "connection_string", None),
        )
        login_info["account_name"] = config.get(
            "account_name", _az_config().get("storage", "account", None)
        )
        login_info["account_key"] = config.get(
            "account_key", _az_config().get("storage", "key", None)
        )
        login_info["sas_token"] = config.get(
            "sas_token", _az_config().get("storage", "sas_token", None)
        )
        login_info["tenant_id"] = config.get("tenant_id")
        login_info["client_id"] = config.get("client_id")
        login_info["client_secret"] = config.get("client_secret")

        if not (login_info["account_name"] or login_info["connection_string"]):
            raise AzureAuthError(
                "Authentication to Azure Blob Storage requires either "
                "account_name or connection_string.\nLearn more about "
                "configuration settings at "
                + format_link("https://man.dvc.org/remote/modify")
            )

        any_secondary = any(
            value for key, value in login_info.items() if key != "account_name"
        )
        if (
            login_info["account_name"]
            and not any_secondary
            and not config.get("allow_anonymous_login", False)
        ):
            with fsspec_loop():
                login_info["credential"] = DefaultAzureCredential(
                    exclude_interactive_browser_credential=False,
                    exclude_environment_credential=config.get(
                        "exclude_environment_credential", False
                    ),
                    exclude_visual_studio_code_credential=config.get(
                        "exclude_visual_studio_code_credential", False
                    ),
                    exclude_shared_token_cache_credential=config.get(
                        "exclude_shared_token_cache_credential", False
                    ),
                    exclude_managed_identity_credential=config.get(
                        "exclude_managed_identity_credential", False
                    ),
                )

        for login_method, required_keys in [  # noqa
            ("connection string", ["connection_string"]),
            (
                "AD service principal",
                ["tenant_id", "client_id", "client_secret"],
            ),
            ("account key", ["account_name", "account_key"]),
            ("SAS token", ["account_name", "sas_token"]),
            (
                f"default credentials ({_DEFAULT_CREDS_STEPS})",
                ["account_name", "credential"],
            ),
            ("anonymous login", ["account_name"]),
        ]:
            if all(login_info.get(key) is not None for key in required_keys):
                break
        else:
            login_method = None

        self.login_method = login_method
        return login_info
def test_unexpected_kwarg():
    """the credential shouldn't raise when given an unexpected keyword argument"""
    DefaultAzureCredential(foo=42)
Ejemplo n.º 27
0
 def __init__(self, method_name):
     super(TestMetricsAdvisorAdministrationClientBaseAsync,
           self).__init__(method_name)
     self.vcr.match_on = ["path", "method", "query"]
     if self.is_live:
         service_endpoint = self.get_settings_value(
             "METRICS_ADVISOR_ENDPOINT")
         self.sql_server_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_SQL_SERVER_CONNECTION_STRING")
         self.azure_table_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_AZURE_TABLE_CONNECTION_STRING")
         self.azure_blob_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_AZURE_BLOB_CONNECTION_STRING")
         self.azure_cosmosdb_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_COSMOS_DB_CONNECTION_STRING")
         self.application_insights_api_key = self.get_settings_value(
             "METRICS_ADVISOR_APPLICATION_INSIGHTS_API_KEY")
         self.azure_data_explorer_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_AZURE_DATA_EXPLORER_CONNECTION_STRING")
         self.influxdb_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_INFLUX_DB_CONNECTION_STRING")
         self.influxdb_password = self.get_settings_value(
             "METRICS_ADVISOR_INFLUX_DB_PASSWORD")
         self.azure_datalake_account_key = self.get_settings_value(
             "METRICS_ADVISOR_AZURE_DATALAKE_ACCOUNT_KEY")
         self.mongodb_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_AZURE_MONGO_DB_CONNECTION_STRING")
         self.mysql_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_MYSQL_CONNECTION_STRING")
         self.postgresql_connection_string = self.get_settings_value(
             "METRICS_ADVISOR_POSTGRESQL_CONNECTION_STRING")
         self.anomaly_detection_configuration_id = self.get_settings_value(
             "METRICS_ADVISOR_ANOMALY_DETECTION_CONFIGURATION_ID")
         self.data_feed_id = self.get_settings_value(
             "METRICS_ADVISOR_DATA_FEED_ID")
         self.metric_id = self.get_settings_value(
             "METRICS_ADVISOR_METRIC_ID")
         credential = DefaultAzureCredential()
         self.scrubber.register_name_pair(self.sql_server_connection_string,
                                          "connectionstring")
         self.scrubber.register_name_pair(
             self.azure_table_connection_string, "connectionstring")
         self.scrubber.register_name_pair(self.azure_blob_connection_string,
                                          "connectionstring")
         self.scrubber.register_name_pair(
             self.azure_cosmosdb_connection_string, "connectionstring")
         self.scrubber.register_name_pair(self.application_insights_api_key,
                                          "connectionstring")
         self.scrubber.register_name_pair(
             self.azure_data_explorer_connection_string, "connectionstring")
         self.scrubber.register_name_pair(self.influxdb_connection_string,
                                          "connectionstring")
         self.scrubber.register_name_pair(self.influxdb_password,
                                          "connectionstring")
         self.scrubber.register_name_pair(self.azure_datalake_account_key,
                                          "connectionstring")
         self.scrubber.register_name_pair(self.mongodb_connection_string,
                                          "connectionstring")
         self.scrubber.register_name_pair(self.mysql_connection_string,
                                          "connectionstring")
         self.scrubber.register_name_pair(self.postgresql_connection_string,
                                          "connectionstring")
         self.scrubber.register_name_pair(self.metric_id, "metric_id")
         self.scrubber.register_name_pair(self.data_feed_id, "data_feed_id")
         self.scrubber.register_name_pair(
             self.anomaly_detection_configuration_id,
             "anomaly_detection_configuration_id")
     else:
         service_endpoint = "https://endpointname.cognitiveservices.azure.com"
         self.sql_server_connection_string = "SQL_SERVER_CONNECTION_STRING"
         self.azure_table_connection_string = "AZURE_TABLE_CONNECTION_STRING"
         self.azure_blob_connection_string = "AZURE_BLOB_CONNECTION_STRING"
         self.azure_cosmosdb_connection_string = "COSMOS_DB_CONNECTION_STRING"
         self.application_insights_api_key = "METRICS_ADVISOR_APPLICATION_INSIGHTS_API_KEY"
         self.azure_data_explorer_connection_string = "METRICS_ADVISOR_AZURE_DATA_EXPLORER_CONNECTION_STRING"
         self.influxdb_connection_string = "METRICS_ADVISOR_INFLUXDB_CONNECTION_STRING"
         self.influxdb_password = "******"
         self.azure_datalake_account_key = "METRICS_ADVISOR_AZURE_DATALAKE_ACCOUNT_KEY"
         self.mongodb_connection_string = "METRICS_ADVISOR_AZURE_MONGODB_CONNECTION_STRING"
         self.mysql_connection_string = "METRICS_ADVISOR_MYSQL_CONNECTION_STRING"
         self.postgresql_connection_string = "METRICS_ADVISOR_POSTGRESQL_CONNECTION_STRING"
         self.anomaly_detection_configuration_id = "anomaly_detection_configuration_id"
         self.data_feed_id = "data_feed_id"
         self.metric_id = "metric_id"
         credential = MockCredential()
     self.admin_client = MetricsAdvisorAdministrationClient(
         service_endpoint, credential)
Ejemplo n.º 28
0
 def get_credential(self):
     if self.is_live:
         return DefaultAzureCredential()
     return AsyncFakeTokenCredential()
async def run_sample():
    # Instantiate a secret client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = SecretClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create secrets holding storage and bank accounts credentials. If the secret
        # already exists in the Key Vault, then a new version of the secret is created.
        print("\n.. Create Secret")
        bank_secret = await client.set_secret("listOpsBankSecretName",
                                              "listOpsSecretValue1")
        storage_secret = await client.set_secret("listOpsStorageSecretName",
                                                 "listOpsSecretValue2")
        print("Secret with name '{0}' was created.".format(bank_secret.name))
        print("Secret with name '{0}' was created.".format(
            storage_secret.name))

        # You need to check if any of the secrets are sharing same values.
        # Let's list the secrets and print their values.
        # List operations don 't return the secrets with value information.
        # So, for each returned secret we call get_secret to get the secret with its value information.
        print("\n.. List secrets from the Key Vault")
        secrets = client.list_secrets()
        async for secret in secrets:
            retrieved_secret = await client.get_secret(secret.name)
            print("Secret with name '{0}' with value '{1}' was found.".format(
                retrieved_secret.name, retrieved_secret.value))

        # The bank account password got updated, so you want to update the secret in Key Vault to ensure it reflects the
        # new password. Calling set_secret on an existing secret creates a new version of the secret in the Key Vault
        # with the new value.
        updated_secret = await client.set_secret(bank_secret.name,
                                                 "newSecretValue")
        print("Secret with name '{0}' was updated with new value '{1}'".format(
            updated_secret.name, updated_secret.value))

        # You need to check all the different values your bank account password secret had previously. Lets print all
        # the versions of this secret.
        print("\n.. List versions of the secret using its name")
        secret_versions = client.list_secret_versions(bank_secret.name)
        async for secret in secret_versions:
            print("Bank Secret with name '{0}' has version: '{1}'".format(
                secret.name, secret.version))

        # The bank account and storage accounts got closed. Let's delete bank and storage accounts secrets.
        await client.delete_secret(bank_secret.name)
        await client.delete_secret(storage_secret.name)

        # To ensure secret is deleted on the server side.
        print("\nDeleting secrets...")
        await asyncio.sleep(20)

        # You can list all the deleted and non-purged secrets, assuming Key Vault is soft-delete enabled.
        print("\n.. List deleted secrets from the Key Vault")
        deleted_secrets = client.list_deleted_secrets()
        async for deleted_secret in deleted_secrets:
            print("Secret with name '{0}' has recovery id '{1}'".format(
                deleted_secret.name, deleted_secret.recovery_id))

    except HttpResponseError as e:
        if "(NotSupported)" in e.message:
            print(
                "\n{0} Please enable soft delete on Key Vault to perform this operation."
                .format(e.message))
        else:
            print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
def test_error_tenant_id():
    with pytest.raises(TypeError):
        DefaultAzureCredential(tenant_id="foo")