Ejemplo n.º 1
0
def get_credential_for_shared_cache_test(expected_refresh_token,
                                         expected_access_token, cache,
                                         **kwargs):
    exclude_other_credentials = {
        option: True
        for option in ("exclude_environment_credential",
                       "exclude_managed_identity_credential")
    }

    # validating transport will raise if the shared cache credential isn't used, or selects the wrong refresh token
    transport = async_validating_transport(
        requests=[
            Request(required_data={"refresh_token": expected_refresh_token})
        ],
        responses=[
            mock_response(json_payload=build_aad_response(
                access_token=expected_access_token))
        ],
    )

    # this credential uses a mock shared cache, so it works on all platforms
    with patch.object(SharedTokenCacheCredential, "supported", lambda: True):
        return DefaultAzureCredential(_cache=cache,
                                      transport=transport,
                                      **exclude_other_credentials,
                                      **kwargs)
Ejemplo n.º 2
0
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_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = CertificateClient(vault_endpoint=VAULT_ENDPOINT, credential=credential)
    try:
        contact_list = [
            Contact(email="*****@*****.**", name="John Doe", phone="1111111111"),
            Contact(email="*****@*****.**", name="John Doe2", phone="2222222222"),
        ]

        # Creates and sets the certificate contacts for this key vault.
        await client.create_contacts(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")
Ejemplo n.º 3
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)

        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
Ejemplo n.º 4
0
    async def delete_old_tags(self):
        from azure.containerregistry import TagOrder
        from azure.containerregistry.aio import (
            ContainerRegistryClient,
            ContainerRepositoryClient,
        )
        from azure.identity.aio import DefaultAzureCredential

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

        async for repository in client.list_repository_names():
            repository_client = ContainerRepositoryClient(account_url, repository, credential)
            # [END list_repository_names]

            # [START list_tags]
            tag_count = 0
            async for tag in repository_client.list_tags(order_by=TagOrder.LAST_UPDATE_TIME_DESCENDING):
                tag_count += 1
                if tag_count > 3:
                    await repository_client.delete_tag(tag.name)
            # [END list_tags]

        await client.close()
Ejemplo n.º 5
0
    async def create_repository_client(self):
        # Instantiate the ContainerRegistryClient
        # [START create_repository_client]
        from azure.containerregistry.aio import ContainerRepository
        from azure.identity.aio import DefaultAzureCredential

        client = ContainerRepository(self.account_url, "my_repository", DefaultAzureCredential())
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_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = SecretClient(vault_endpoint=VAULT_ENDPOINT, credential=credential)
    try:
        # Let's create a secret holding bank account credentials valid for 1 year.
        # if the secret already exists in the key vault, then a new version of the secret is created.
        print("\n.. Create Secret")
        expires_on = datetime.datetime.utcnow() + datetime.timedelta(days=365)
        secret = await client.set_secret("helloWorldSecretName",
                                         "helloWorldSecretValue",
                                         expires_on=expires_on)
        print("Secret with name '{0}' created with value '{1}'".format(
            secret.name, secret.value))
        print("Secret with name '{0}' expires on '{1}'".format(
            secret.name, secret.properties.expires_on))

        # Let's get the bank secret using its name
        print("\n.. Get a Secret by name")
        bank_secret = await client.get_secret(secret.name)
        print("Secret with name '{0}' was found with value '{1}'.".format(
            bank_secret.name, bank_secret.value))

        # After one year, the bank account is still active, we need to update the expiry time of the secret.
        # The update method can be used to update the expiry attribute of the secret. It cannot be used to update
        # the value of the secret.
        print("\n.. Update a Secret by name")
        expires_on = bank_secret.properties.expires_on + datetime.timedelta(
            days=365)
        updated_secret_properties = await client.update_secret_properties(
            secret.name, expires_on=expires_on)
        print("Secret with name '{0}' was updated on date '{1}'".format(
            updated_secret_properties.name,
            updated_secret_properties.updated_on))
        print("Secret with name '{0}' was updated to expire on '{1}'".format(
            updated_secret_properties.name,
            updated_secret_properties.expires_on))

        # Bank forced a password update for security purposes. Let's change the value of the secret in the key vault.
        # To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot
        # change the value of the secret.
        new_secret = await client.set_secret(secret.name, "newSecretValue")
        print("Secret with name '{0}' created with value '{1}'".format(
            new_secret.name, new_secret.value))

        # The bank account was closed, need to delete its credentials from the Key Vault.
        print("\n.. Deleting Secret...")
        deleted_secret = await client.delete_secret(secret.name)
        print("Secret with name '{0}' was deleted.".format(
            deleted_secret.name))

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

    finally:
        print("\nrun_sample done")
Ejemplo n.º 7
0
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_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = CertificateClient(vault_endpoint=VAULT_ENDPOINT,
                               credential=credential)
    try:
        # First we specify the AdministratorDetails for our issuers.
        admin_details = [
            AdministratorDetails(first_name="John",
                                 last_name="Doe",
                                 email="*****@*****.**",
                                 phone="4255555555")
        ]

        # Next we create an issuer with these administrator details
        # The name field refers to the name you would like to get the issuer. There are also pre-set names, such as 'Self' and 'Unknown'
        await client.create_issuer(name="issuer1",
                                   provider="Test",
                                   account_id="keyvaultuser",
                                   admin_details=admin_details,
                                   enabled=True)

        # Now we get this issuer by name
        issuer1 = await client.get_issuer(name="issuer1")

        print(issuer1.name)
        print(issuer1.properties.provider)
        print(issuer1.account_id)

        for admin_detail in issuer1.admin_details:
            print(admin_detail.first_name)
            print(admin_detail.last_name)
            print(admin_detail.email)
            print(admin_detail.phone)

        # Now we will list all of the certificate issuers for this key vault. To better demonstrate this, we will first create another issuer.
        await client.create_issuer(name="issuer2",
                                   provider="Test",
                                   account_id="keyvaultuser",
                                   enabled=True)

        issuers = client.list_issuers()

        async for issuer in issuers:
            print(issuer.name)
            print(issuer.provider)

        # Finally, we delete our first issuer by name.
        await client.delete_issuer(name="issuer1")

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

    finally:
        print("\nrun_sample done")
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_endpoint = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = CertificateClient(vault_endpoint=vault_endpoint,
                               credential=credential)
    try:

        print("\n.. Create Certificate")
        cert_name = "BackupRestoreCertificate"

        # Let's create a certificate for your key vault.
        # if the certificate already exists in the Key Vault, then a new version of the certificate is created.
        # An async poller is returned.
        create_certificate_poller = await client.create_certificate(
            name=cert_name)

        # Awaiting the poller will return a certificate if creation is successful, and will return the failed
        # CertificateOperation if not.
        await create_certificate_poller
        print("Certificate with name '{0}' created.".format(cert_name))

        # Backups are good to have, if in case certificates 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 certificate")
        certificate_backup = await client.backup_certificate(name=cert_name)
        print("Backup created for certificate with name '{0}'.".format(
            cert_name))

        # The storage account certificate is no longer in use, so you can delete it.
        await client.delete_certificate(name=cert_name)
        # To ensure certificate is deleted on the server side.
        await asyncio.sleep(30)
        print("Deleted Certificate with name '{0}'".format(cert_name))

        # Even though the certificate is deleted, it can still be recovered so its name cannot be reused.
        # In order to be able to reuse the name during restoration, we must purge the certificate
        # after the initial deletion.
        print("\nPurging certificate...")
        await client.purge_deleted_certificate(name=cert_name)
        # To ensure certificate is purged on the server side.
        await asyncio.sleep(30)
        print("Purged Certificate with name '{0}'".format(cert_name))

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

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

    finally:
        print("\nrun_sample done")
Ejemplo n.º 9
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)

    # 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))

    print("\nrun_sample done")
    await credential.close()
    await client.close()
    def credential(self):
        if self.is_live:
            return DefaultAzureCredential()

        async def get_token(*_, **__):
            return AccessToken("secret", time.time() + 3600)

        return mock.Mock(get_token=get_token)
async def authentication_administration_client_with_aad_async():
    # [START authentication_administration_client_with_aad_async]
    from azure.identity.aio import DefaultAzureCredential
    from azure.ai.metricsadvisor.aio import MetricsAdvisorAdministrationClient

    service_endpoint = os.getenv("METRICS_ADVISOR_ENDPOINT")
    credential = DefaultAzureCredential()
    client = MetricsAdvisorAdministrationClient(service_endpoint, credential)
Ejemplo n.º 12
0
 async def create_registry_client(self):
     # Instantiate the ContainerRegistryClient
     # [START create_registry_client]
     account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
     audience = "https://management.azure.com"
     client = ContainerRegistryClient(account_url,
                                      DefaultAzureCredential(),
                                      audience=audience)
    async def create_registry_client(self):
        # Instantiate the ContainerRegistryClient
        # [START create_registry_client]
        from azure.containerregistry.aio import ContainerRegistryClient
        from azure.identity.aio import DefaultAzureCredential
        account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]

        client = ContainerRegistryClient(account_url, DefaultAzureCredential())
async def test_iterates_only_once():
    """When a credential succeeds, DefaultAzureCredential should use that credential thereafter, ignoring the others"""

    unavailable_credential = Mock(get_token=Mock(side_effect=CredentialUnavailableError(message="...")))
    successful_credential = Mock(get_token=Mock(return_value=get_completed_future(AccessToken("***", 42))))

    credential = DefaultAzureCredential()
    credential.credentials = [
        unavailable_credential,
        successful_credential,
        Mock(get_token=Mock(side_effect=Exception("iteration didn't stop after a credential provided a token"))),
    ]

    for n in range(3):
        await credential.get_token("scope")
        assert unavailable_credential.get_token.call_count == 1
        assert successful_credential.get_token.call_count == n + 1
Ejemplo n.º 15
0
async def default_credentials():
    """
    Context manager which yields the default credentials.
    """
    credential = DefaultAzureCredential(
        managed_identity_client_id=config.MANAGED_IDENTITY_CLIENT_ID)
    yield credential
    await credential.close()
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_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = SecretClient(vault_endpoint=VAULT_ENDPOINT, 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("recoverPurgeBankSecretName",
                                              "recoverPurgeSecretValue1")
        storage_secret = await client.set_secret(
            "recoverPurgeStorageSecretName", "recoverPurgeSecretValue2")
        print("Secret with name '{0}' was created.".format(bank_secret.name))
        print("Secret with name '{0}' was created.".format(
            storage_secret.name))

        # The storage account was closed, need to delete its credentials from the Key Vault.
        print("\n.. Delete a Secret")
        secret = await client.delete_secret(bank_secret.name)
        await asyncio.sleep(20)
        print("Secret with name '{0}' was deleted on date {1}.".format(
            secret.name, secret.deleted_date))

        # We accidentally deleted the bank account secret. Let's recover it.
        # A deleted secret can only be recovered if the Key Vault is soft-delete enabled.
        print("\n.. Recover Deleted  Secret")
        recovered_secret = await client.recover_deleted_secret(bank_secret.name
                                                               )
        print("Recovered Secret with name '{0}'.".format(
            recovered_secret.name))

        # Let's delete storage account now.
        # If the keyvault is soft-delete enabled, then for permanent deletion deleted secret needs to be purged.
        await client.delete_secret(storage_secret.name)

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

        # To ensure permanent deletion, we might need to purge the secret.
        print("\n.. Purge Deleted Secret")
        await client.purge_deleted_secret(storage_secret.name)
        print("Secret has been permanently deleted.")

    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")
    async def exercise_credentials(authority_kwarg, expected_authority=None):
        expected_authority = expected_authority or authority_kwarg

        async def send(request, **_):
            url = urlparse(request.url)
            assert url.scheme == "https", "Unexpected scheme '{}'".format(url.scheme)
            assert url.netloc == expected_authority, "Expected authority '{}', actual was '{}'".format(
                expected_authority, url.netloc
            )
            return response

        # environment credential configured with client secret should respect authority
        environment = {
            EnvironmentVariables.AZURE_CLIENT_ID: "client_id",
            EnvironmentVariables.AZURE_CLIENT_SECRET: "secret",
            EnvironmentVariables.AZURE_TENANT_ID: "tenant_id",
        }
        with patch("os.environ", environment):
            transport = Mock(send=send)
            if authority_kwarg:
                credential = DefaultAzureCredential(authority=authority_kwarg, transport=transport)
            else:
                credential = DefaultAzureCredential(transport=transport)
            access_token, _ = await credential.get_token("scope")
            assert access_token == expected_access_token

        # managed identity credential should ignore authority
        with patch("os.environ", {EnvironmentVariables.MSI_ENDPOINT: "https://some.url"}):
            transport = Mock(send=wrap_in_future(lambda *_, **__: response))
            if authority_kwarg:
                credential = DefaultAzureCredential(authority=authority_kwarg, transport=transport)
            else:
                credential = DefaultAzureCredential(transport=transport)
            access_token, _ = await credential.get_token("scope")
            assert access_token == expected_access_token

        # shared cache credential should respect authority
        upn = os.environ.get(EnvironmentVariables.AZURE_USERNAME, "spam@eggs")  # preferring environment values to
        tenant = os.environ.get(EnvironmentVariables.AZURE_TENANT_ID, "tenant")  # prevent failure during live runs
        account = get_account_event(username=upn, uid="guid", utid=tenant, authority=authority_kwarg)
        cache = populated_cache(account)
        with patch.object(SharedTokenCacheCredential, "supported"):
            credential = DefaultAzureCredential(_cache=cache, authority=authority_kwarg, transport=Mock(send=send))
        access_token, _ = await credential.get_token("scope")
        assert access_token == expected_access_token
async def test_default_credential_shared_cache_use():
    with patch(
            "azure.identity.aio._credentials.default.SharedTokenCacheCredential"
    ) as mock_credential:
        mock_credential.supported = Mock(return_value=False)

        # unsupported platform -> default credential shouldn't use shared cache
        credential = DefaultAzureCredential()
        assert mock_credential.call_count == 0
        assert mock_credential.supported.call_count == 1
        mock_credential.supported.reset_mock()

        # unsupported platform, $AZURE_USERNAME set, $AZURE_PASSWORD not set -> default credential shouldn't use shared cache
        credential = DefaultAzureCredential()
        assert mock_credential.call_count == 0
        assert mock_credential.supported.call_count == 1

        mock_credential.supported = Mock(return_value=True)

        # supported platform, $AZURE_USERNAME not set -> default credential shouldn't use shared cache
        credential = DefaultAzureCredential()
        assert mock_credential.call_count == 0
        assert mock_credential.supported.call_count == 1
        mock_credential.supported.reset_mock()

        # supported platform, $AZURE_USERNAME and $AZURE_PASSWORD set -> default credential shouldn't use shared cache
        # (EnvironmentCredential should be used when both variables are set)
        with patch.dict("os.environ", {
                "AZURE_USERNAME": "******",
                "AZURE_PASSWORD": "******"
        }):
            credential = DefaultAzureCredential()
            assert mock_credential.call_count == 0

        # supported platform, $AZURE_USERNAME set, $AZURE_PASSWORD not set -> default credential should use shared cache
        with patch.dict("os.environ", {"AZURE_USERNAME": "******"}):
            expected_token = AccessToken("***", 42)
            mock_credential.return_value = Mock(
                get_token=asyncio.coroutine(lambda *_: expected_token))

            credential = DefaultAzureCredential()
            assert mock_credential.call_count == 1

            token = await credential.get_token("scope")
            assert token == expected_token
async def test_default_credential_shared_cache_use():
    with patch(DefaultAzureCredential.__module__ +
               ".SharedTokenCacheCredential") as mock_credential:
        mock_credential.supported = Mock(return_value=False)

        # unsupported platform -> default credential shouldn't use shared cache
        credential = DefaultAzureCredential()
        assert mock_credential.call_count == 0
        assert mock_credential.supported.call_count == 1
        mock_credential.supported.reset_mock()

        mock_credential.supported = Mock(return_value=True)

        # supported platform -> default credential should use shared cache
        credential = DefaultAzureCredential()
        assert mock_credential.call_count == 1
        assert mock_credential.supported.call_count == 1
        mock_credential.supported.reset_mock()
Ejemplo n.º 20
0
def create_client():
    # [START create_sr_client_async]
    SCHEMAREGISTRY_FQN = os.environ["SCHEMAREGISTRY_FULLY_QUALIFIED_NAMESPACE"]
    token_credential = DefaultAzureCredential()
    schema_registry_client = SchemaRegistryClient(
        fully_qualified_namespace=SCHEMAREGISTRY_FQN,
        credential=token_credential)
    # [END create_sr_client_async]
    return schema_registry_client, token_credential
Ejemplo n.º 21
0
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)

    # Let's create certificates holding storage and bank accounts credentials. If the certificate
    # already exists in the Key Vault, then a new version of the certificate is created.
    print("\n.. Create Certificates")
    bank_cert_name = "BankRecoverCertificate"
    storage_cert_name = "ServerRecoverCertificate"

    bank_certificate = await client.create_certificate(
        certificate_name=bank_cert_name,
        policy=CertificatePolicy.get_default())
    storage_certificate = await client.create_certificate(
        certificate_name=storage_cert_name,
        policy=CertificatePolicy.get_default())

    print("Certificate with name '{0}' was created.".format(
        bank_certificate.name))
    print("Certificate with name '{0}' was created.".format(
        storage_certificate.name))

    # The storage account was closed, need to delete its credentials from the Key Vault.
    print("\n.. Delete a Certificate")
    deleted_bank_certificate = await client.delete_certificate(bank_cert_name)
    # To ensure certificate is deleted on the server side.
    await asyncio.sleep(30)

    print("Certificate with name '{0}' was deleted on date {1}.".format(
        deleted_bank_certificate.name, deleted_bank_certificate.deleted_on))

    # We accidentally deleted the bank account certificate. Let's recover it.
    # A deleted certificate can only be recovered if the Key Vault is soft-delete enabled.
    print("\n.. Recover Deleted Certificate")
    recovered_bank_certificate = await client.recover_deleted_certificate(
        deleted_bank_certificate.name)
    print("Recovered Certificate with name '{0}'.".format(
        recovered_bank_certificate.name))

    # Let's delete storage account now.
    # If the keyvault is soft-delete enabled, then for permanent deletion deleted certificate needs to be purged.
    await client.delete_certificate(storage_cert_name)

    # Certificates will still purge eventually on their scheduled purge date, but calling `purge_deleted_certificate` immediately
    # purges.
    print("\n.. Purge Deleted Certificate")
    await client.purge_deleted_certificate(storage_cert_name)
    print("Certificate has been permanently deleted.")

    print("\nrun_sample done")
    await credential.close()
    await client.close()
Ejemplo n.º 22
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)

    # Let's create keys with RSA and EC type. If the key
    # already exists in the Key Vault, then a new version of the key is created.
    print("\n.. Create Key")
    rsa_key = await client.create_rsa_key("rsaKeyName")
    ec_key = await client.create_ec_key("ecKeyName")
    print("Key with name '{0}' was created of type '{1}'.".format(rsa_key.name, rsa_key.key_type))
    print("Key with name '{0}' was created of type '{1}'.".format(ec_key.name, ec_key.key_type))

    # You need to check the type of all the keys in the vault.
    # Let's list the keys and print their key types.
    # List operations don 't return the keys with their type information.
    # So, for each returned key we call get_key to get the key with its type information.
    print("\n.. List keys from the Key Vault")
    keys = client.list_properties_of_keys()
    async for key in keys:
        retrieved_key = await client.get_key(key.name)
        print(
            "Key with name '{0}' with type '{1}' was found.".format(
                retrieved_key.name, retrieved_key.key_type
            )
        )

    # The rsa key size now should now be 3072, default - 2048. So you want to update the key in Key Vault to ensure
    # it reflects the new key size. Calling create_rsa_key on an existing key creates a new version of the key in
    # the Key Vault with the new key size.
    new_key = await client.create_rsa_key(rsa_key.name, size=3072)
    print("New version was created for Key with name '{0}' with the updated size.".format(new_key.name))

    # You should have more than one version of the rsa key at this time. Lets print all the versions of this key.
    print("\n.. List versions of the key using its name")
    key_versions = client.list_properties_of_key_versions(rsa_key.name)
    async for key in key_versions:
        print("RSA Key with name '{0}' has version: '{1}'".format(key.name, key.version))

    # Both the rsa key and ec key are not needed anymore. Let's delete those keys.
    print("\n..Deleting keys...")
    await client.delete_key(rsa_key.name)
    await client.delete_key(ec_key.name)

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

    print("\nrun_sample done")
    await credential.close()
    await client.close()
 def create_mgmt_aio_client(self, client, **kwargs):
     if self.is_live:
         from azure.identity.aio import DefaultAzureCredential
         credential = DefaultAzureCredential()
     else:
         credential = Mock(get_token=asyncio.coroutine(
             lambda _: AccessToken("fake-token", 0)))
     return client(credential=credential,
                   subscription_id=self.settings.SUBSCRIPTION_ID)
async def run_sample():
    MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]

    # Instantiate an access control client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    credential = DefaultAzureCredential()
    client = KeyVaultAccessControlClient(vault_url=MANAGED_HSM_URL, credential=credential)
    
    # Let's first create a custom role definition. This role permits creating keys in a Managed HSM.
    # We'll provide a friendly role name, and let a unique role definition name (a GUID) be generated for us.
    print("\n.. Create a role definition")
    role_name = "customRole"
    scope = KeyVaultRoleScope.GLOBAL
    permissions = [KeyVaultPermission(data_actions=[KeyVaultDataAction.CREATE_HSM_KEY])]
    role_definition = await client.set_role_definition(scope=scope, role_name=role_name, permissions=permissions)
    print("Role definition '{}' created successfully.".format(role_definition.role_name))

    # Let's update our role definition to allow reading keys, but not allow creating keys.
    # To update an existing definition, pass the name keyword argument to set_role_definition. This is the unique
    # name of the role definition, which is stored in KeyVaultRoleDefinition.name.
    print("\n.. Update a role definition")
    new_permissions = [
        KeyVaultPermission(
            data_actions=[KeyVaultDataAction.READ_HSM_KEY],
            not_data_actions=[KeyVaultDataAction.CREATE_HSM_KEY]
        )
    ]
    unique_definition_name = role_definition.name
    updated_definition = await client.set_role_definition(
        scope=scope, name=unique_definition_name, role_name=role_name, permissions=new_permissions
    )
    print("Role definition '{}' updated successfully.".format(updated_definition.role_name))

    # Now let's create a role assignment to apply our role definition to our service principal.
    # Since we don't provide the name keyword argument to create_role_definition, a unique role assignment name
    # (a GUID) is generated for us.
    print("\n.. Create a role assignment")
    principal_id = os.environ["AZURE_CLIENT_ID"]
    definition_id = updated_definition.id
    role_assignment = await client.create_role_assignment(
        scope=scope, definition_id=definition_id, principal_id=principal_id
    )
    print("Role assignment created successfully.")

    # Let's delete the role assignment.
    print("\n.. Delete a role assignment")
    await client.delete_role_assignment(scope=scope, name=role_assignment.name)
    print("Role assignment deleted successfully.")

    # Finally, let's delete the role definiton as well.
    print("\n.. Delete a role definition")
    await client.delete_role_definition(scope=scope, name=definition_id)
    print("Role definition deleted successfully.")

    await credential.close()
    await client.close()
def test_managed_identity_client_id():
    """The credential should initialize ManagedIdentityCredential with the value of AZURE_CLIENT_ID"""

    expected_client_id = "the-client"
    with patch.dict(os.environ,
                    {EnvironmentVariables.AZURE_CLIENT_ID: expected_client_id},
                    clear=True):
        with patch(DefaultAzureCredential.__module__ +
                   ".ManagedIdentityCredential") as mock_credential:
            DefaultAzureCredential()

    mock_credential.assert_called_once_with(client_id=expected_client_id)

    with patch.dict(os.environ, {}, clear=True):
        with patch(DefaultAzureCredential.__module__ +
                   ".ManagedIdentityCredential") as mock_credential:
            DefaultAzureCredential()

    mock_credential.assert_called_once_with(client_id=None)
def test_create_key_client():
    vault_url = "vault_url"
    # pylint:disable=unused-variable
    # [START create_key_client]
    from azure.identity.aio import DefaultAzureCredential
    from azure.keyvault.keys.aio import KeyClient

    # Create a KeyClient using default Azure credentials
    credential = DefaultAzureCredential()
    key_client = KeyClient(vault_url, credential)
def test_create_secret_client():
    vault_url = "vault_url"
    # pylint:disable=unused-variable
    # [START create_secret_client]
    from azure.identity.aio import DefaultAzureCredential
    from azure.keyvault.secrets.aio import SecretClient

    # Create a SecretClient using default Azure credentials
    credentials = DefaultAzureCredential()
    secret_client = SecretClient(vault_url, credentials)
def test_create_certificate():
    vault_url = "vault_url"
    # pylint:disable=unused-variable
    # [START create_certificate_client]
    from azure.identity.aio import DefaultAzureCredential
    from azure.keyvault.certificates.aio import CertificateClient

    # Create a KeyVaultCertificate using default Azure credentials
    credential = DefaultAzureCredential()
    certificate_client = CertificateClient(vault_url=vault_url, credential=credential)
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        credential = DefaultAzureCredential()
        self.key_client = KeyClient(vault_url=os.environ["AZURE_PROJECT_URL"],
                                    credential=credential)

        self.key_name = "key-name-" + uuid.uuid1().hex
Ejemplo n.º 30
0
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:

        print("\n.. Create Certificate")
        cert_name = "BackupRestoreCertificate"

        # Let's create a certificate for your key vault.
        # if the certificate already exists in the Key Vault, then a new version of the certificate is created.
        # Awaiting the call returns a KeyVaultCertificate if creation is successful, and a CertificateOperation if not.
        certificate = await client.create_certificate(
            certificate_name=cert_name, policy=CertificatePolicy.get_default())

        print("Certificate with name '{0}' created.".format(certificate.name))

        # Backups are good to have, if in case certificates 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 certificate")
        certificate_backup = await client.backup_certificate(cert_name)
        print("Backup created for certificate with name '{0}'.".format(
            cert_name))

        # The storage account certificate is no longer in use, so you can delete it.
        print("\n.. Delete the certificate")
        await client.delete_certificate(cert_name)
        print("Deleted certificate with name '{0}'".format(cert_name))

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

        # In the future, if the certificate is required again, we can use the backup value to restore it in the Key Vault.
        print(
            "\n.. Restore the certificate using the backed up certificate bytes"
        )
        certificate = await client.restore_certificate_backup(
            certificate_backup)
        print("Restored certificate with name '{0}'".format(certificate.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()