Esempio n. 1
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 = 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.
        certificate = await create_certificate_poller
        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(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")
        await client.delete_certificate(name=cert_name)
        print("Deleted 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")
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)

    contact_list = [
        CertificateContact(email="*****@*****.**",
                           name="John Doe",
                           phone="1111111111"),
        CertificateContact(email="*****@*****.**",
                           name="John Doe2",
                           phone="2222222222"),
    ]

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

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

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

    print("\nrun_sample done")
    await credential.close()
    await client.close()
Esempio n. 4
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 = [
            CertificateContact(email="*****@*****.**", name="John Doe", phone="1111111111"),
            CertificateContact(email="*****@*****.**", name="John Doe2", phone="2222222222"),
        ]

        # Creates and sets the certificate contacts for this key vault.
        await client.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")
Esempio n. 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_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = CertificateClient(vault_endpoint=VAULT_ENDPOINT, 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_poller = await client.create_certificate(name=bank_cert_name)
        storage_certificate_poller = await client.create_certificate(name=storage_cert_name)

        bank_certificate = await bank_certificate_poller
        storage_certificate = await storage_certificate_poller
        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")
Esempio n. 6
0
def test_service_headers_allowed_in_logs():
    service_headers = {
        "x-ms-keyvault-network-info", "x-ms-keyvault-region",
        "x-ms-keyvault-service-version"
    }
    client = CertificateClient("...", object())
    assert service_headers.issubset(
        client._client._config.http_logging_policy.allowed_header_names)
Esempio n. 7
0
async def test_close():
    transport = AsyncMockTransport()
    client = CertificateClient(vault_url="https://localhost",
                               credential=object(),
                               transport=transport)

    await client.close()
    assert transport.__aenter__.call_count == 0
    assert transport.__aexit__.call_count == 1
Esempio n. 8
0
def test_custom_hook_policy():
    class CustomHookPolicy(SansIOHTTPPolicy):
        pass

    client = CertificateClient("...",
                               object(),
                               custom_hook_policy=CustomHookPolicy())
    assert isinstance(client._client._config.custom_hook_policy,
                      CustomHookPolicy)
Esempio n. 9
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()
Esempio n. 10
0
async def test_context_manager():
    transport = AsyncMockTransport()
    client = CertificateClient(vault_url="https://localhost",
                               credential=object(),
                               transport=transport)

    async with client:
        assert transport.__aenter__.call_count == 1
    assert transport.__aenter__.call_count == 1
    assert transport.__aexit__.call_count == 1
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        credential = DefaultAzureCredential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex
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)
Esempio n. 13
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()
Esempio n. 14
0
async def test_policy_expected_errors_for_create_cert():
    """Either a subject or subject alternative name property are required for creating a certificate"""
    client = CertificateClient("...", object())

    with pytest.raises(ValueError, match=NO_SAN_OR_SUBJECT):
        policy = CertificatePolicy()
        await client.create_certificate("...", policy=policy)

    with pytest.raises(ValueError, match=NO_SAN_OR_SUBJECT):
        policy = CertificatePolicy(issuer_name=WellKnownIssuerNames.self)
        await client.create_certificate("...", policy=policy)
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        authority_host = os.environ.get(
            'AZURE_AUTHORITY_HOST') or KnownAuthorities.AZURE_PUBLIC_CLOUD
        credential = DefaultAzureCredential(authority=authority_host)
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex
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.
        # An async poller is returned
        create_certificate_poller = await client.create_certificate(name=cert_name)
        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")
Esempio n. 17
0
 def __init__(self,
              vault_endpoint: str,
              credential: "TokenCredential",
              transport: HttpTransport = None,
              api_version: str = None,
              **kwargs: Any) -> None:
     super(VaultClient, self).__init__(vault_endpoint,
                                       credential,
                                       transport=transport,
                                       api_version=api_version,
                                       **kwargs)
     self._certificates = CertificateClient(self.vault_endpoint,
                                            credential,
                                            generated_client=self._client,
                                            **kwargs)
Esempio n. 18
0
async 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)

    # the client and credential should be closed when no longer needed
    # (both are also async context managers)
    await certificate_client.close()
    await credential.close()
Esempio n. 19
0
    def __init__(
        self,
        vault_url: str,
        credential: "TokenCredential",
        transport: HttpTransport = None,
        api_version: str = None,
        is_live: bool = True,
        **kwargs: Any
    ) -> None:
        super(VaultClient, self).__init__(vault_url, credential, transport=transport, api_version=api_version, **kwargs)
        self._certificates = CertificateClient(self.vault_url, credential, generated_client=self._client, **kwargs)

        if not is_live:
            # ensure pollers don't sleep during playback
            self._certificates.create_certificate = functools.partial(
                self._certificates.create_certificate, _polling_interval=0
            )
            self._certificates.delete_certificate = functools.partial(
                self._certificates.delete_certificate, _polling_interval=0
            )
            self._certificates.recover_deleted_certificate = functools.partial(
                self._certificates.recover_deleted_certificate, _polling_interval=0
            )
Esempio n. 20
0
async def run_sample():
    # Instantiate a certificate client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = CertificateClient(vault_url=VAULT_URL, credential=credential)

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

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

    await credential.close()
    await client.close()
Esempio 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)

    # First we specify the AdministratorContact for our issuers.
    admin_contacts = [
        AdministratorContact(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(issuer_name="issuer1",
                               provider="Test",
                               account_id="keyvaultuser",
                               admin_contacts=admin_contacts,
                               enabled=True)

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

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

    for contact in issuer1.admin_contacts:
        print(contact.first_name)
        print(contact.last_name)
        print(contact.email)
        print(contact.phone)

    # Now we update the admnistrator contact for this issuer
    admin_contacts = [
        AdministratorContact(first_name="Jane",
                             last_name="Doe",
                             email="*****@*****.**",
                             phone="4255555555")
    ]
    issuer1 = await client.update_issuer(issuer_name="issuer1",
                                         admin_contacts=admin_contacts)

    for contact in issuer1.admin_contacts:
        print(contact.first_name)
        print(contact.last_name)
        print(contact.email)
        print(contact.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(issuer_name="issuer2",
                               provider="Test",
                               account_id="keyvaultuser",
                               enabled=True)

    issuers = client.list_properties_of_issuers()

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

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

    print("\nrun_sample done")
    await credential.close()
    await client.close()
Esempio n. 22
0
    def __init__(self):
        credential = self.get_default_credential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex
Esempio n. 23
0
 def __init__(self):
     args = self.get_client_args()
     self.certificate_client = CertificateClient(**args)
     self.certificate_name = "cert-name-" + uuid.uuid1().hex
Esempio n. 24
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 a certificate for holding bank account credentials valid for 1 year.
        # 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 you specify the properties of the key, secret, and issuer backing your certificate,
        # the X509 component of your certificate, and any lifetime actions you would like to be taken
        # on your certificate

        # Alternatively, if you would like to use our default policy, don't pass a policy parameter to
        # our certificate creation method
        cert_policy = CertificatePolicy(
            exportable=True,
            key_type="RSA",
            key_size=2048,
            reuse_key=False,
            content_type=SecretContentType.PKCS12,
            issuer_name=WellKnownIssuerNames.Self,
            subject_name="CN=*.microsoft.com",
            validity_in_months=24,
            san_dns_names=["sdk.azure-int.net"],
        )
        cert_name = "HelloWorldCertificate"

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

        # Let's get the bank certificate using its name
        print("\n.. Get a Certificate by name")
        bank_certificate = await client.get_certificate(cert_name)
        print("Certificate with name '{0}' was found.".format(
            bank_certificate.name))

        # After one year, the bank account is still active, and we have decided to update the tags.
        print("\n.. Update a Certificate by name")
        tags = {"a": "b"}
        updated_certificate = await client.update_certificate_properties(
            certificate_name=bank_certificate.name, tags=tags)
        print("Certificate with name '{0}' was updated on date '{1}'".format(
            bank_certificate.name, updated_certificate.properties.updated_on))
        print("Certificate with name '{0}' was updated with tags '{1}'".format(
            bank_certificate.name, updated_certificate.properties.tags))

        # The bank account was closed, need to delete its credentials from the Key Vault.
        print("\n.. Delete Certificate")
        deleted_certificate = await client.delete_certificate(
            bank_certificate.name)
        print("Deleting Certificate..")
        print("Certificate with name '{0}' was deleted.".format(
            deleted_certificate.name))

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

    finally:
        print("\nrun_sample done")
Esempio n. 25
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()
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_poller = await client.create_certificate(name=bank_cert_name)
        storage_certificate_poller = await client.create_certificate(name=storage_cert_name)

        # await the creation of the bank and storage certificate
        await bank_certificate_poller
        await storage_certificate_poller

        print("Certificate with name '{0}' was created.".format(bank_cert_name))
        print("Certificate with name '{0}' was created.".format(storage_cert_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, tags=tags)
        await updated_bank_certificate_poller
        print(
            "Certificate with name '{0}' was created again with tags '{1}'".format(bank_cert_name, 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")
Esempio n. 27
0
if "AZURE_KEYVAULT_URL" not in os.environ:
    raise EnvironmentError("Missing a Key Vault URL")
if "KEYVAULT_TENANT_ID" not in os.environ:
    raise EnvironmentError("Missing a tenant ID for Key Vault")
if "KEYVAULT_CLIENT_ID" not in os.environ:
    raise EnvironmentError("Missing a client ID for Key Vault")
if "KEYVAULT_CLIENT_SECRET" not in os.environ:
    raise EnvironmentError("Missing a client secret for Key Vault")

credential = ClientSecretCredential(
    tenant_id=os.environ["KEYVAULT_TENANT_ID"],
    client_id=os.environ["KEYVAULT_CLIENT_ID"],
    client_secret=os.environ["KEYVAULT_CLIENT_SECRET"])

cert_client = CertificateClient(os.environ["AZURE_KEYVAULT_URL"], credential)
key_client = KeyClient(os.environ["AZURE_KEYVAULT_URL"], credential)
secret_client = SecretClient(os.environ["AZURE_KEYVAULT_URL"], credential)


async def delete_certificates():
    coroutines = []

    test_certificates = cert_client.list_properties_of_certificates()
    async for certificate in test_certificates:
        if certificate.name.startswith("livekvtest"):
            coroutines.append(cert_client.delete_certificate(certificate.name))

    return await asyncio.gather(*coroutines)