def test_2016_10_01_models(self, azure_keyvault_url, **kwargs):
        client = self.create_client(azure_keyvault_url,
                                    api_version=ApiVersion.V2016_10_01)
        """The client should correctly deserialize version 2016-10-01 models"""

        cert_name = self.get_resource_name("cert")
        cert = client.begin_create_certificate(
            cert_name, CertificatePolicy.get_default()).result()

        # these properties don't exist in version 2016-10-01
        assert cert.policy.key_curve_name is None
        assert cert.policy.certificate_transparency is None
Beispiel #2
0
    def test_get_pending_certificate_signing_request(self, client, **kwargs):
        cert_name = self.get_resource_name("unknownIssuerCert")

        # get pending certificate signing request
        certificate = client.begin_create_certificate(
            certificate_name=cert_name,
            policy=CertificatePolicy.get_default()).wait()
        pending_version_csr = client.get_certificate_operation(
            certificate_name=cert_name).csr
        self.assertEqual(
            client.get_certificate_operation(certificate_name=cert_name).csr,
            pending_version_csr)
Beispiel #3
0
    def test_async_request_cancellation_and_deletion(self, client, **kwargs):
        cert_name = self.get_resource_name("asyncCanceledDeletedCert")
        cert_policy = CertificatePolicy.get_default()
        # create certificate
        create_certificate_poller = client.begin_create_certificate(
            certificate_name=cert_name, policy=cert_policy)

        # cancel certificate operation
        cancel_operation = client.cancel_certificate_operation(
            certificate_name=cert_name)
        self.assertTrue(hasattr(cancel_operation, "cancellation_requested"))
        self.assertTrue(cancel_operation.cancellation_requested)
        self._validate_certificate_operation(
            pending_cert_operation=cancel_operation,
            vault=client.vault_url,
            cert_name=cert_name,
            original_cert_policy=cert_policy,
        )

        self.assertEqual(create_certificate_poller.result().status.lower(),
                         "cancelled")

        retrieved_operation = client.get_certificate_operation(cert_name)
        self.assertTrue(hasattr(retrieved_operation, "cancellation_requested"))
        self.assertTrue(retrieved_operation.cancellation_requested)
        self._validate_certificate_operation(
            pending_cert_operation=retrieved_operation,
            vault=client.vault_url,
            cert_name=cert_name,
            original_cert_policy=cert_policy,
        )

        # delete certificate operation
        deleted_operation = client.delete_certificate_operation(
            certificate_name=cert_name)
        self.assertIsNotNone(deleted_operation)
        self._validate_certificate_operation(
            pending_cert_operation=deleted_operation,
            vault=client.vault_url,
            cert_name=cert_name,
            original_cert_policy=cert_policy,
        )

        try:
            client.get_certificate_operation(certificate_name=cert_name)
            self.fail("Get should fail")
        except Exception as ex:
            if not hasattr(ex,
                           "message") or "not found" not in ex.message.lower():
                raise ex

        # delete cancelled certificate
        client.begin_delete_certificate(cert_name).wait()
    async def test_crud_operations(self, azure_keyvault_url, **kwargs):
        client = self.create_client(azure_keyvault_url)

        cert_name = self.get_resource_name("cert")
        lifetime_actions = [LifetimeAction(lifetime_percentage=80, action=CertificatePolicyAction.auto_renew)]
        cert_policy = CertificatePolicy(
            issuer_name="Self",
            subject="CN=DefaultPolicy",
            exportable=True,
            key_type=KeyType.rsa,
            key_size=2048,
            reuse_key=False,
            content_type=CertificateContentType.pkcs12,
            lifetime_actions=lifetime_actions,
            validity_in_months=12,
            key_usage=[KeyUsageType.digital_signature, KeyUsageType.key_encipherment],
        )

        # create certificate
        cert = await client.create_certificate(certificate_name=cert_name, policy=CertificatePolicy.get_default())

        self._validate_certificate_bundle(cert=cert, cert_name=cert_name, cert_policy=cert_policy)

        self.assertEqual(
            (await client.get_certificate_operation(certificate_name=cert_name)).status.lower(), "completed"
        )

        # get certificate
        cert = await client.get_certificate(certificate_name=cert_name)
        self._validate_certificate_bundle(cert=cert, cert_name=cert_name, cert_policy=cert_policy)

        # update certificate, ensuring the new updated_on value is at least one second later than the original
        if self.is_live:
            await asyncio.sleep(1)
        tags = {"tag1": "updated_value1"}
        updated_cert = await client.update_certificate_properties(cert_name, tags=tags)
        self._validate_certificate_bundle(cert=updated_cert, cert_name=cert_name, cert_policy=cert_policy)
        self.assertEqual(tags, updated_cert.properties.tags)
        self.assertEqual(cert.id, updated_cert.id)
        self.assertNotEqual(cert.properties.updated_on, updated_cert.properties.updated_on)

        # delete certificate
        deleted_cert_bundle = await client.delete_certificate(certificate_name=cert_name)
        self._validate_certificate_bundle(cert=deleted_cert_bundle, cert_name=cert_name, cert_policy=cert_policy)

        # get certificate returns not found
        try:
            await client.get_certificate_version(cert_name, deleted_cert_bundle.properties.version)
            self.fail("Get should fail")
        except Exception as ex:
            if not hasattr(ex, "message") or "not found" not in ex.message.lower():
                raise ex
Beispiel #5
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()
    async def test_get_pending_certificate_signing_request(
            self, client, **kwargs):
        cert_name = "unknownIssuerCert"

        # get pending certificate signing request
        await client.create_certificate(certificate_name=cert_name,
                                        policy=CertificatePolicy.get_default())
        operation = await client.get_certificate_operation(
            certificate_name=cert_name)
        pending_version_csr = operation.csr
        self.assertEqual(
            (await
             client.get_certificate_operation(certificate_name=cert_name)).csr,
            pending_version_csr)
Beispiel #7
0
    def test_get_pending_certificate_signing_request(self, vault_client,
                                                     **kwargs):
        self.assertIsNotNone(vault_client)
        client = vault_client.certificates
        cert_name = "unknownIssuerCert"

        # get pending certificate signing request
        certificate = client.begin_create_certificate(
            certificate_name=cert_name,
            policy=CertificatePolicy.get_default()).wait()
        pending_version_csr = client.get_certificate_operation(
            certificate_name=cert_name).csr
        self.assertEqual(
            client.get_certificate_operation(certificate_name=cert_name).csr,
            pending_version_csr)
    def test_get_pending_certificate_signing_request(self, azure_keyvault_url,
                                                     **kwargs):
        self._skip_if_not_configured(**kwargs)
        client = self.create_client(azure_keyvault_url, **kwargs)

        cert_name = self.get_resource_name("unknownIssuerCert")

        # get pending certificate signing request
        certificate = client.begin_create_certificate(
            certificate_name=cert_name,
            policy=CertificatePolicy.get_default()).wait()
        pending_version_csr = client.get_certificate_operation(
            certificate_name=cert_name).csr
        self.assertEqual(
            client.get_certificate_operation(certificate_name=cert_name).csr,
            pending_version_csr)
Beispiel #9
0
    async def test_get_pending_certificate_signing_request(self, vault_client, **kwargs):
        self.assertIsNotNone(vault_client)
        client = vault_client.certificates
        cert_name = "unknownIssuerCert"

        polling_interval = 0 if self.is_playback() else None

        # get pending certificate signing request
        await client.create_certificate(
            certificate_name=cert_name,
            policy=CertificatePolicy.get_default(),
            _polling_interval=polling_interval
        )
        operation = await client.get_certificate_operation(certificate_name=cert_name)
        pending_version_csr = operation.csr
        self.assertEqual((await client.get_certificate_operation(certificate_name=cert_name)).csr, pending_version_csr)
Beispiel #10
0
    def backup_restore_certificate(self):
        """
        backs up a key vault certificate and restores it to another key vault
        """
        # create a key vault
        first_vault = self.create_vault()

        # create a certificate client
        credential = DefaultAzureCredential()
        first_certificate_client = CertificateClient(
            vault_url=first_vault.properties.vault_uri, credential=credential)

        # add a certificate to the vault
        certificate_name = get_name('certificate')

        certificate = first_certificate_client.begin_create_certificate(
            certificate_name, CertificatePolicy.get_default()).result()
        print('created certificate {}'.format(certificate.name))

        # list the certificates in the vault
        certificate_properties = first_certificate_client.list_properties_of_certificates(
        )
        print("all of the certificates in the client's vault:")
        for certificate_property in certificate_properties:
            print(certificate_property.name)

        # backup the certificate
        backup = first_certificate_client.backup_certificate(certificate_name)
        print('backed up certificate {}'.format(certificate_name))

        # create a second vault
        second_vault = self.create_vault()

        # create a certificate client
        second_certificate_client = CertificateClient(
            vault_url=second_vault.properties.vault_uri, credential=credential)

        # restore the certificate to the new vault
        restored = second_certificate_client.restore_certificate_backup(backup)
        print('restored certificate {}'.format(restored.name))

        # list the certificates in the new vault
        certificate_properties = second_certificate_client.list_properties_of_certificates(
        )
        print("all of the certificates in the new vault:")
        for certificate_property in certificate_properties:
            print(certificate_property.name)
Beispiel #11
0
def pkcs12_cert():
    """Demonstrates creating a CertificateCredential with a Key Vault certificate stored in PKCS12 (default) format"""

    # Creating a self-signed cert to work with
    create_cert_poller = CERT_CLIENT.begin_create_certificate(
        "azure-identity-sample-default", CertificatePolicy.get_default())
    cert = create_cert_poller.result()

    # CertificateCredential requires the certificate and its private key in PEM format.
    # The certificate as returned by begin_create_certificate() or get_certificate() contains
    # only the public portion of the certificate. Key Vault will release the private key only
    # if the certificate's policy indicates it's exportable (certs are exportable by default).
    policy = CERT_CLIENT.get_certificate_policy(cert.name)
    assert policy.exportable, "Expected an exportable certificate because that's Key Vault's default"

    # The policy's content_type indicates whether the certificate is stored in PEM or PKCS12 format
    assert policy.content_type == CertificateContentType.pkcs12, "Expected PKCS12 because that's Key Vault's default"

    # Key Vault stores the complete certificate, with its private key, as a secret sharing the certificate's name
    # Because this certificate is stored in PKCS12 format, the secret's value is base64 encoded bytes
    encoded_cert = SECRET_CLIENT.get_secret(cert.name).value
    pkcs12_bytes = base64.b64decode(encoded_cert)

    # cryptography can convert PKCS12 to PEM
    def pkcs12_to_pem(pkcs12_bytes):
        """Convert certificate bytes from PKCS12 format to PEM using the "cryptography" library"""
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.serialization import Encoding, pkcs12, PrivateFormat, NoEncryption

        private_key, cert, additional_certs = pkcs12.load_key_and_certificates(
            pkcs12_bytes, password=None, backend=default_backend())

        # using NoEncryption because the certificate created above is not password protected
        private_bytes = private_key.private_bytes(Encoding.PEM,
                                                  PrivateFormat.PKCS8,
                                                  NoEncryption())
        pem_sections = [private_bytes] + [
            c.public_bytes(Encoding.PEM) for c in [cert] + additional_certs
        ]
        return b"".join(pem_sections)

    pem_bytes = pkcs12_to_pem(pkcs12_bytes)

    # This credential will load the certificate but can't actually authenticate. Authentication requires real
    # tenant and client IDs for a service principal configured to accept the certificate.
    CertificateCredential("tenant-id", "client-id", certificate_data=pem_bytes)
Beispiel #12
0
    async def test_backup_restore(self, client, **kwargs):
        cert_name = self.get_resource_name("cert")
        policy = CertificatePolicy.get_default()
        policy._san_user_principal_names = ["*****@*****.**"]

        # create certificate
        await client.create_certificate(certificate_name=cert_name, policy=policy)

        # create a backup
        certificate_backup = await client.backup_certificate(certificate_name=cert_name)

        # delete the certificate
        await client.delete_certificate(certificate_name=cert_name)

        # restore certificate
        restored_certificate = await client.restore_certificate_backup(backup=certificate_backup)
        self._validate_certificate_bundle(cert=restored_certificate, cert_name=cert_name, cert_policy=policy)
    def test_parse_certificate_id_with_version(self, client):
        cert_name = self.get_resource_name("cert")
        # create certificate
        certificate = client.begin_create_certificate(
            cert_name, CertificatePolicy.get_default()).result()

        # [START parse_key_vault_certificate_id]
        cert = client.get_certificate(cert_name)
        parsed_certificate_id = parse_key_vault_certificate_id(cert.id)

        print(parsed_certificate_id.name)
        print(parsed_certificate_id.vault_url)
        print(parsed_certificate_id.version)
        print(parsed_certificate_id.source_id)
        # [END parse_key_vault_certificate_id]
        assert parsed_certificate_id.name == cert_name
        assert parsed_certificate_id.vault_url == client.vault_url
        assert parsed_certificate_id.version == cert.properties.version
        assert parsed_certificate_id.source_id == cert.id
Beispiel #14
0
    def test_backup_restore(self, client, **kwargs):
        policy = CertificatePolicy.get_default()
        policy._san_user_principal_names = ["*****@*****.**"]
        cert_name = self.get_resource_name("cert")
        # create certificate
        create_certificate_poller = client.begin_create_certificate(certificate_name=cert_name, policy=policy)
        create_certificate_poller.wait()

        # create a backup
        certificate_backup = client.backup_certificate(certificate_name=cert_name)

        # delete the certificate
        client.begin_delete_certificate(certificate_name=cert_name).wait()

        # purge the certificate
        client.purge_deleted_certificate(certificate_name=cert_name)

        # restore certificate
        restore_function = functools.partial(client.restore_certificate_backup, certificate_backup)
        restored_certificate = self._poll_until_no_exception(restore_function, ResourceExistsError)
        self._validate_certificate_bundle(cert=restored_certificate, cert_name=cert_name, cert_policy=policy)
    def test_get_certificate_version(self, client, **kwargs):
        cert_name = self.get_resource_name("cert")
        for _ in range(self.list_test_size):
            client.begin_create_certificate(cert_name, CertificatePolicy.get_default()).wait()

        for version_properties in client.list_properties_of_certificate_versions(cert_name):
            cert = client.get_certificate_version(version_properties.name, version_properties.version)

            # This isn't factored out into a helper method because the properties are not exactly equal.
            # get_certificate_version sets "recovery_days" and "recovery_level" but the list method does not.
            # (This is Key Vault's behavior, not an SDK limitation.)
            assert version_properties.created_on == cert.properties.created_on
            assert version_properties.enabled == cert.properties.enabled
            assert version_properties.expires_on == cert.properties.expires_on
            assert version_properties.id == cert.properties.id
            assert version_properties.name == cert.properties.name
            assert version_properties.not_before == cert.properties.not_before
            assert version_properties.tags == cert.properties.tags
            assert version_properties.updated_on == cert.properties.updated_on
            assert version_properties.vault_url == cert.properties.vault_url
            assert version_properties.version == cert.properties.version
            assert version_properties.x509_thumbprint == cert.properties.x509_thumbprint
Beispiel #16
0
    def test_backup_restore(self, vault_client, **kwargs):
        policy = CertificatePolicy.get_default()
        policy._san_user_principal_names = ["*****@*****.**"]
        self.assertIsNotNone(vault_client)
        client = vault_client.certificates
        cert_name = self.get_resource_name("cert")
        # create certificate
        create_certificate_poller = client.begin_create_certificate(
            certificate_name=cert_name, policy=policy)
        create_certificate_poller.wait()

        # create a backup
        certificate_backup = client.backup_certificate(
            certificate_name=cert_name)

        # delete the certificate
        client.begin_delete_certificate(certificate_name=cert_name).wait()

        # restore certificate
        restored_certificate = client.restore_certificate_backup(
            backup=certificate_backup)
        self._validate_certificate_bundle(cert=restored_certificate,
                                          cert_name=cert_name,
                                          cert_policy=policy)
Beispiel #17
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:
        # 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(
            name=bank_cert_name, policy=CertificatePolicy.get_default())
        storage_certificate = await client.create_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(
            name=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_date))

        # 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(name=storage_cert_name)
        # To ensure certificate is deleted on the server side.
        await asyncio.sleep(30)

        # To ensure permanent deletion, we might need to purge the secret.
        print("\n.. Purge Deleted Certificate")
        await client.purge_deleted_certificate(name=storage_cert_name)
        print("Certificate 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")
Beispiel #18
0
# 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:
    # Let's create a certificate for 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 Certificate")
    bank_cert_name = "BankListCertificate"
    storage_cert_name = "StorageListCertificate"

    bank_certificate_poller = client.begin_create_certificate(
        name=bank_cert_name, policy=CertificatePolicy.get_default())
    storage_certificate_poller = client.begin_create_certificate(
        name=storage_cert_name, policy=CertificatePolicy.get_default())

    # await the creation of the bank and storage certificate
    bank_certificate = bank_certificate_poller.result()
    storage_certificate = storage_certificate_poller.result()

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

    # Let's list the certificates.
    print("\n.. List certificates from the Key Vault")
    certificates = client.list_properties_of_certificates()
    def deleted_certificate_recovery(self):
        """
        a sample of enumerating, retrieving, recovering and purging deleted certificates from a key vault 
        """
        # create a vault enabling the soft delete feature
        vault = self.create_vault()

        # create a certificate client
        credential = DefaultAzureCredential()
        certificate_client = CertificateClient(
            vault_url=vault.properties.vault_uri, credential=credential)

        # create certificates in the vault
        cert_to_recover = get_name('cert')
        cert_to_purge = get_name('cert')

        create_certificate_poller = certificate_client.begin_create_certificate(
            cert_to_recover, policy=CertificatePolicy.get_default())
        created_certificate = create_certificate_poller.result()
        print('created certificate {}'.format(created_certificate.name))

        create_certificate_poller = certificate_client.begin_create_certificate(
            cert_to_purge, policy=CertificatePolicy.get_default())
        created_certificate = create_certificate_poller.result()
        print('created certificate {}'.format(created_certificate.name))

        # list the vault certificates
        certificates = certificate_client.list_properties_of_certificates()
        print('list the vault certificates')
        for certificate in certificates:
            print(certificate.name)

        # delete the certificates
        deleted_certificate_poller = certificate_client.begin_delete_certificate(
            cert_to_recover)
        deleted_certificate = deleted_certificate_poller.result()
        deleted_certificate_poller.wait()
        print('deleted certificate {}'.format(deleted_certificate.name))

        deleted_certificate_poller = certificate_client.begin_delete_certificate(
            cert_to_purge)
        deleted_certificate = deleted_certificate_poller.result()
        deleted_certificate_poller.wait()
        print('deleted certificate {}'.format(deleted_certificate.name))

        # list the deleted certificates
        deleted_certs = certificate_client.list_deleted_certificates()
        print('deleted certificates:')
        for deleted_cert in deleted_certs:
            print(deleted_cert.name)

        # recover a deleted certificate
        recovered_certificate_poller = certificate_client.begin_recover_deleted_certificate(
            cert_to_recover)
        recovered_certificate_certificate = recovered_certificate_poller.result(
        )
        print('recovered certificate {}'.format(
            recovered_certificate_certificate.name))

        # purge a deleted certificate
        certificate_client.purge_deleted_certificate(cert_to_purge)
        time.sleep(50)
        print('purged certificate {}'.format(cert_to_purge))

        # list the vault certificates
        certificates = certificate_client.list_properties_of_certificates()
        print("all of the certificates in the client's vault:")
        for certificate in certificates:
            print(certificate.name)
# 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_poller = client.begin_create_certificate(
    certificate_name=bank_cert_name, policy=CertificatePolicy.get_default()
)
storage_certificate_poller = client.begin_create_certificate(
    certificate_name=storage_cert_name, policy=CertificatePolicy.get_default()
)

bank_certificate = bank_certificate_poller.result()
storage_certificate = storage_certificate_poller.result()
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_poller = client.begin_delete_certificate(bank_cert_name)
deleted_bank_certificate = deleted_bank_poller.result()
# To ensure certificate is deleted on the server side.
Beispiel #21
0
    async def test_crud_operations(self, vault_client, **kwargs):
        self.assertIsNotNone(vault_client)
        client = vault_client.certificates
        cert_name = self.get_resource_name("cert")
        lifetime_actions = [
            LifetimeAction(trigger=Trigger(lifetime_percentage=80),
                           action=Action(action_type=ActionType.auto_renew))
        ]
        cert_policy = CertificatePolicyGenerated(
            key_properties=KeyProperties(exportable=True,
                                         key_type="RSA",
                                         key_size=2048,
                                         reuse_key=False),
            secret_properties=SecretProperties(
                content_type="application/x-pkcs12"),
            issuer_parameters=IssuerParameters(name="Self"),
            lifetime_actions=lifetime_actions,
            x509_certificate_properties=X509CertificateProperties(
                subject="CN=DefaultPolicy",
                validity_in_months=12,
                key_usage=["digitalSignature", "keyEncipherment"]),
        )

        polling_interval = 0 if self.is_playback() else None
        # create certificate
        cert = await client.create_certificate(
            certificate_name=cert_name,
            policy=CertificatePolicy.get_default(),
            _polling_interval=polling_interval)

        self._validate_certificate_bundle(cert=cert,
                                          vault=client.vault_url,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)

        self.assertEqual(
            (await
             client.get_certificate_operation(certificate_name=cert_name
                                              )).status.lower(), "completed")

        # get certificate
        cert = await client.get_certificate(certificate_name=cert_name)
        self._validate_certificate_bundle(cert=cert,
                                          vault=client.vault_url,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)

        # update certificate
        tags = {"tag1": "updated_value1"}
        cert_bundle = await client.update_certificate_properties(cert_name,
                                                                 tags=tags)
        self._validate_certificate_bundle(cert=cert_bundle,
                                          vault=client.vault_url,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)
        self.assertEqual(tags, cert_bundle.properties.tags)
        self.assertEqual(cert.id, cert_bundle.id)
        self.assertNotEqual(cert.properties.updated_on,
                            cert_bundle.properties.updated_on)

        # delete certificate
        deleted_cert_bundle = await client.delete_certificate(
            certificate_name=cert_name, _polling_interval=polling_interval)
        self._validate_certificate_bundle(cert=deleted_cert_bundle,
                                          vault=client.vault_url,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)

        # get certificate returns not found
        try:
            await client.get_certificate_version(
                cert_name, deleted_cert_bundle.properties.version)
            self.fail("Get should fail")
        except Exception as ex:
            if not hasattr(ex,
                           "message") or "not found" not in ex.message.lower():
                raise ex
Beispiel #22
0
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
certificate_client = CertificateClient(vault_url=VAULT_URL, credential=credential)

# Instantiate a secret client that will be used to call the service.
# Notice that this client can reuse the credential object created above.
secret_client = SecretClient(vault_url=VAULT_URL, credential=credential)
try:
    # Let's create a certificate in the vault.
    # If the certificate already exists in the Key Vault, then a new version of the certificate is created.
    print("\n.. Create certificate")

    # Before creating your certificate, let's create the management policy for your certificate.
    # Here we use the default policy.
    cert_name = "PrivateKeyCertificate"
    cert_policy = CertificatePolicy.get_default()

    # begin_create_certificate returns a poller. Calling result() on the poller will return the certificate
    # as a KeyVaultCertificate if creation is successful, and the CertificateOperation if not. The wait()
    # call on the poller will wait until the long running operation is complete.
    created_certificate = certificate_client.begin_create_certificate(
        certificate_name=cert_name, policy=cert_policy
    ).result()
    print("Certificate with name '{}' was created".format(created_certificate.name))

    # Key Vault also creates a secret with the same name as the created certificate.
    # This secret contains the certificate's bytes, which include the private key if the certificate's
    # policy indicates that the key is exportable.
    print("\n.. Get a secret by name")
    certificate_secret = secret_client.get_secret(name=cert_name)
    print("Certificate secret with name '{}' was found.".format(certificate_secret.name))
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:
        # Let's create a certificate for 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 Certificate")
        bank_cert_name = "BankListCertificate"
        storage_cert_name = "StorageListCertificate"

        bank_certificate = await client.create_certificate(
            name=bank_cert_name, policy=CertificatePolicy.get_default())
        storage_certificate = await client.create_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))

        # Let's list the certificates.
        print("\n.. List certificates from the Key Vault")
        certificates = client.list_certificates()
        async for certificate in certificates:
            print("Certificate with name '{0}' was found.".format(
                certificate.name))

        # You've decided to add tags to the certificate you created. Calling create_certificate on an existing
        # certificate creates a new version of the certificate in the Key Vault with the new value.

        tags = {"a": "b"}

        updated_bank_certificate_poller = await client.create_certificate(
            name=bank_cert_name,
            policy=CertificatePolicy.get_default(),
            tags=tags)
        bank_certificate = await updated_bank_certificate_poller
        print("Certificate with name '{0}' was created again with tags '{1}'".
              format(bank_certificate.name, bank_certificate.properties.tags))

        # You need to check all the different tags your bank account certificate had previously. Lets print all the versions of this certificate.
        print("\n.. List versions of the certificate using its name")
        certificate_versions = client.list_certificate_versions(bank_cert_name)
        async for certificate_version in certificate_versions:
            print(
                "Bank Certificate with name '{0}' with version '{1}' has tags: '{2}'."
                .format(certificate_version.name, certificate_version.version,
                        certificate_version.tags))

        # The bank account and storage accounts got closed. Let's delete bank and storage accounts certificates.
        await client.delete_certificate(name=bank_cert_name)
        await client.delete_certificate(name=storage_cert_name)

        # You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled.
        print("\n.. List deleted certificates from the Key Vault")
        deleted_certificates = client.list_deleted_certificates()
        async for deleted_certificate in deleted_certificates:
            print("Certificate with name '{0}' has recovery id '{1}'".format(
                deleted_certificate.name, deleted_certificate.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")
    async def test_async_request_cancellation_and_deletion(
            self, client, **kwargs):
        cert_name = "asyncCanceledDeletedCert"
        cert_policy = CertificatePolicy.get_default()

        # create certificate
        await client.create_certificate(certificate_name=cert_name,
                                        policy=cert_policy)

        # cancel certificate operation
        cancel_operation = await client.cancel_certificate_operation(cert_name)
        self.assertTrue(hasattr(cancel_operation, "cancellation_requested"))
        self.assertTrue(cancel_operation.cancellation_requested)
        self._validate_certificate_operation(
            pending_cert_operation=cancel_operation,
            vault=client.vault_url,
            cert_name=cert_name,
            original_cert_policy=cert_policy,
        )

        cancelled = False
        for _ in range(10):
            if (await client.get_certificate_operation(cert_name)
                ).status.lower() == "cancelled":
                cancelled = True
                break
            await asyncio.sleep(10)
        self.assertTrue(cancelled)

        retrieved_operation = await client.get_certificate_operation(
            certificate_name=cert_name)
        self.assertTrue(hasattr(retrieved_operation, "cancellation_requested"))
        self.assertTrue(retrieved_operation.cancellation_requested)
        self._validate_certificate_operation(
            pending_cert_operation=retrieved_operation,
            vault=client.vault_url,
            cert_name=cert_name,
            original_cert_policy=cert_policy,
        )

        # delete certificate operation
        deleted_operation = await client.delete_certificate_operation(cert_name
                                                                      )
        self.assertIsNotNone(deleted_operation)
        self._validate_certificate_operation(
            pending_cert_operation=deleted_operation,
            vault=client.vault_url,
            cert_name=cert_name,
            original_cert_policy=cert_policy,
        )

        try:
            await client.get_certificate_operation(certificate_name=cert_name)
            self.fail("Get should fail")
        except Exception as ex:
            if not hasattr(ex,
                           "message") or "not found" not in ex.message.lower():
                raise ex

        # delete cancelled certificate
        await client.delete_certificate(cert_name)
# 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.
    # A long running poller is returned for the create certificate operation.
    create_certificate_poller = client.begin_create_certificate(
        name=cert_name, policy=CertificatePolicy.get_default())

    # The result call awaits the completion of the create certificate operation and returns the final result.
    # It will return a certificate if creation is successful, and will return the CertificateOperation if not.
    certificate = create_certificate_poller.result()
    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 = 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.
    print("\n.. Delete the certificate")
    client.delete_certificate(name=cert_name)
Beispiel #26
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()
    certificate_client = CertificateClient(vault_url=VAULT_URL,
                                           credential=credential)

    # Instantiate a secret client that will be used to call the service.
    # Notice that this client can reuse the credential object created above.
    secret_client = SecretClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create a certificate in the vault.
        # If the certificate already exists in the Key Vault, then a new version of the certificate is created.
        print("\n.. Create certificate")

        # Before creating your certificate, let's create the management policy for your certificate.
        # Here we use the default policy.
        cert_name = "PrivateKeyCertificate"
        cert_policy = CertificatePolicy.get_default()

        # Awaiting create_certificate will return the certificate as a KeyVaultCertificate
        # if creation is successful, and the CertificateOperation if not.
        created_certificate = await certificate_client.create_certificate(
            certificate_name=cert_name, policy=cert_policy)
        print("Certificate with name '{}' was created".format(
            created_certificate.name))

        # Key Vault also creates a secret with the same name as the created certificate.
        # This secret contains protected information about the certificate, such as its private key.
        print("\n.. Get a secret by name")
        certificate_secret = await secret_client.get_secret(name=cert_name)
        print("Certificate secret with name '{}' was found.".format(
            certificate_secret.name))

        # Now we can extract the private key and public certificate from the secret using the cryptography
        # package. `additional_certificates` will be empty since the secret only contains one certificate.
        # This example shows how to parse a certificate in PKCS12 format since it's the default in Key Vault,
        # but PEM certificates are supported as well. With a PEM certificate, you could use load_pem_private_key
        # in place of load_key_and_certificates.
        cert_bytes = base64.b64decode(certificate_secret.value)
        private_key, public_certificate, additional_certificates = pkcs12.load_key_and_certificates(
            data=cert_bytes, password=None)
        print("Certificate with name '{}' was parsed.".format(
            certificate_secret.name))

        # Now we can clean up the vault by deleting, then purging, the certificate.
        print("\n.. Delete certificate")
        deleted_certificate = await certificate_client.delete_certificate(
            certificate_name=cert_name)
        print("Certificate with name '{}' was deleted.".format(
            deleted_certificate.name))

        await certificate_client.purge_deleted_certificate(
            certificate_name=deleted_certificate.name)
        print("Certificate with name '{}' is being purged.".format(
            deleted_certificate.name))

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

    finally:
        print("\nrun_sample done")
        await credential.close()
        await certificate_client.close()
        await secret_client.close()
    def test_crud_operations(self, vault_client, **kwargs):
        self.assertIsNotNone(vault_client)
        client = vault_client.certificates
        cert_name = self.get_resource_name("cert")
        lifetime_actions = [
            LifetimeAction(lifetime_percentage=80,
                           action=CertificatePolicyAction.auto_renew)
        ]
        cert_policy = CertificatePolicy(
            issuer_name="Self",
            subject="CN=DefaultPolicy",
            exportable=True,
            key_type=KeyType.rsa,
            key_size=2048,
            reuse_key=False,
            content_type=CertificateContentType.pkcs12,
            lifetime_actions=lifetime_actions,
            validity_in_months=12,
            key_usage=[
                KeyUsageType.digital_signature, KeyUsageType.key_encipherment
            ])

        polling_interval = 0 if self.is_playback() else None

        # create certificate
        certificate = client.begin_create_certificate(
            cert_name,
            CertificatePolicy.get_default(),
            _polling_interval=polling_interval).result()

        self._validate_certificate_bundle(cert=certificate,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)

        self.assertEqual(
            client.get_certificate_operation(
                certificate_name=cert_name).status.lower(), "completed")

        # get certificate
        cert = client.get_certificate(certificate_name=cert_name)
        self._validate_certificate_bundle(cert=cert,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)

        # update certificate
        tags = {"tag1": "updated_value1"}
        cert_bundle = client.update_certificate_properties(cert_name,
                                                           tags=tags)
        self._validate_certificate_bundle(cert=cert_bundle,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)
        self.assertEqual(tags, cert_bundle.properties.tags)
        self.assertEqual(cert.id, cert_bundle.id)
        self.assertNotEqual(cert.properties.updated_on,
                            cert_bundle.properties.updated_on)

        # delete certificate
        delete_cert_poller = client.begin_delete_certificate(
            cert_name, _polling_interval=polling_interval)
        deleted_cert_bundle = delete_cert_poller.result()
        self._validate_certificate_bundle(cert=deleted_cert_bundle,
                                          cert_name=cert_name,
                                          cert_policy=cert_policy)
        delete_cert_poller.wait()

        # get certificate returns not found
        try:
            client.get_certificate_version(
                cert_name, deleted_cert_bundle.properties.version)
            self.fail("Get should fail")
        except Exception as ex:
            if not hasattr(ex,
                           "message") or "not found" not in ex.message.lower():
                raise ex
Beispiel #28
0
 async def create_certificate(self):
     print("Creating a certificate...")
     await self.certificate_client.create_certificate(
         certificate_name=self.certificate_name,
         policy=CertificatePolicy.get_default())
     print("\tdone")
Beispiel #29
0
 def create_certificate(self):
     self.certificate_client.begin_create_certificate(
         name=self.certificate_name,
         policy=CertificatePolicy.get_default()).wait()
     print("\tdone")
 async def global_setup(self):
     """The global setup is run only once."""
     await super().global_setup()
     await self.async_client.create_certificate(
         "livekvtestperfcert", CertificatePolicy.get_default())