Esempio n. 1
0
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

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

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

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

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

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

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

    print("\nrun_sample done")
    await credential.close()
    await client.close()
    def __init__(self):

        credential = self.get_default_credential()
        self.key_client = KeyClient(vault_url=os.environ["AZURE_PROJECT_URL"],
                                    credential=credential)

        self.key_name = "key-name-" + uuid.uuid1().hex
Esempio n. 3
0
    async def test_example_selective_key_restore(self, container_uri,
                                                 sas_token):
        # create a key to selectively restore
        key_client = KeyClient(self.managed_hsm["url"], self.credential)
        key_name = self.get_resource_name("selective-restore-test-key")
        await key_client.create_rsa_key(key_name)

        backup_client = KeyVaultBackupClient(self.managed_hsm["url"],
                                             self.credential)
        backup_poller = await backup_client.begin_backup(
            container_uri, sas_token)
        backup_operation = await backup_poller.result()
        folder_url = backup_operation.folder_url

        # [START begin_selective_restore]
        # begin a restore of a single key from a backed up vault
        restore_poller = await backup_client.begin_restore(folder_url,
                                                           sas_token,
                                                           key_name=key_name)

        # check if the restore completed
        done = backup_poller.done()

        # wait for the restore to complete
        await restore_poller.wait()
Esempio n. 4
0
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_endpoint=VAULT_ENDPOINT, credential=credential)
    try:
        # Let's create a Key of type RSA.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n.. Create Key")
        key = await client.create_key("keyName", "RSA")
        print("Key with name '{0}' created with key type '{1}'".format(key.name, key.key_type))

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

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

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

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

    finally:
        print("\nrun_sample done")
    async def test_multitenant_authentication(self, client, is_hsm, **kwargs):
        if not self.is_live:
            pytest.skip("This test is incompatible with vcrpy in playback")

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

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

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

        # try making another request with the credential's token revoked
        # the challenge policy should correctly request a new token for the correct tenant when a challenge is cached
        client._client._config.authentication_policy._token = None
        fetched_key = await client.get_key(key_name)
        assert key.id == fetched_key.id
def test_custom_hook_policy():
    class CustomHookPolicy(SansIOHTTPPolicy):
        pass

    client = KeyClient("...", object(), custom_hook_policy=CustomHookPolicy())
    assert isinstance(client._client._config.custom_hook_policy,
                      CustomHookPolicy)
Esempio n. 7
0
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

    # Let's create an RSA key with size 2048, hsm disabled and optional key_operations of encrypt, decrypt.
    # if the key already exists in the Key Vault, then a new version of the key is created.
    print("\n.. Create an RSA Key")
    key_size = 2048
    key_ops = ["encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"]
    key_name = "rsaKeyName"
    rsa_key = await client.create_rsa_key(key_name,
                                          size=key_size,
                                          key_operations=key_ops)
    print("RSA Key with name '{0}' created of type '{1}'.".format(
        rsa_key.name, rsa_key.key_type))

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

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

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

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

    print("\nrun_sample done")
    await credential.close()
    await client.close()
def test_service_headers_allowed_in_logs():
    service_headers = {
        "x-ms-keyvault-network-info", "x-ms-keyvault-region",
        "x-ms-keyvault-service-version"
    }
    client = KeyClient("...", object())
    assert service_headers.issubset(
        client._client._config.http_logging_policy.allowed_header_names)
async def test_key_client_close():
    transport = AsyncMockTransport()
    client = KeyClient(vault_url="https://localhost",
                       credential=object(),
                       transport=transport)

    await client.close()
    assert transport.__aenter__.call_count == 0
    assert transport.__aexit__.call_count == 1
async def test_key_client_context_manager():
    transport = AsyncMockTransport()
    client = KeyClient(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 test_create_key_client():
    vault_url = "vault_url"
    # pylint:disable=unused-variable
    # [START create_key_client]
    from azure.identity.aio import DefaultAzureCredential
    from azure.keyvault.keys.aio import KeyClient

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

        self.key_name = "key-name-" + uuid.uuid1().hex
Esempio n. 13
0
    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.key_client = KeyClient(vault_url=os.environ["AZURE_PROJECT_URL"],
                                    credential=credential)

        self.key_name = "key-name-" + uuid.uuid1().hex
Esempio n. 14
0
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create keys with RSA and EC type. If the key
        # already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create Key")
        rsa_key = await client.create_rsa_key("rsaKeyName", hsm=False)
        ec_key = await client.create_ec_key("ecKeyName", hsm=False)
        print("Key with name '{0}' was created of type '{1}'.".format(rsa_key.name, rsa_key.key_material.kty))
        print("Key with name '{0}' was created of type '{1}'.".format(ec_key.name, ec_key.key_material.kty))

        # The ec key is no longer needed. Need to delete it from the Key Vault.
        print("\n2. Delete a Key")
        key = await client.delete_key(rsa_key.name)
        await asyncio.sleep(30)
        print("Key with name '{0}' was deleted on date {1}.".format(key.name, key.deleted_date))

        # We accidentally deleted the rsa key. Let's recover it.
        # A deleted key can only be recovered if the Key Vault is soft-delete enabled.
        print("\n3. Recover Deleted  Key")
        recovered_key = await client.recover_deleted_key(rsa_key.name)
        print("Recovered Key with name '{0}'.".format(recovered_key.name))

        # Let's delete ec key now.
        # If the keyvault is soft-delete enabled, then for permanent deletion deleted key needs to be purged.
        await client.delete_key(ec_key.name)

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

        # To ensure permanent deletion, we might need to purge the key.
        print("\n4. Purge Deleted Key")
        await client.purge_deleted_key(ec_key.name)
        print("EC Key has been permanently deleted.")

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

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

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

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

        # deleting the recovered key so it doesn't outlast this script
        # If the keyvault is soft-delete enabled, then for permanent deletion, the deleted key needs to be purged.
        await client.delete_key(recovered_key.name)

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

    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")
        await credential.close()
        await client.close()
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create an RSA key with size 2048, hsm disabled and optional key_operations of encrypt, decrypt.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create an RSA Key")
        key_size = 2048
        key_ops = ["encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"]
        key_name = "rsaKeyName"
        rsa_key = await client.create_rsa_key(key_name, size=key_size, hsm=False, key_operations=key_ops)
        print("RSA Key with name '{0}' created of type '{1}'.".format(rsa_key.name, rsa_key.key_material.kty))

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

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

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

        # The RSA key is no longer used, need to delete it from the Key Vault.
        print("\n4. Delete Key")
        deleted_key = await client.delete_key(rsa_key.name)
        print("Deleting Key..")
        print("Key with name '{0}' was deleted.".format(deleted_key.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
async def test_create_key_client():
    vault_url = "vault_url"
    # pylint:disable=unused-variable
    # [START create_key_client]
    from azure.identity.aio import DefaultAzureCredential
    from azure.keyvault.keys.aio import KeyClient

    # Create a KeyClient using default Azure credentials
    credential = DefaultAzureCredential()
    key_client = KeyClient(vault_url, credential)

    # the client and credential should be closed when no longer needed
    # (both are also async context managers)
    await key_client.close()
    await credential.close()
Esempio n. 18
0
 def __init__(self,
              vault_url: str,
              credential: "TokenCredential",
              transport: HttpTransport = None,
              api_version: str = None,
              **kwargs: Any) -> None:
     super(VaultClient, self).__init__(vault_url,
                                       credential,
                                       transport=transport,
                                       api_version=api_version,
                                       **kwargs)
     self._keys = KeyClient(self.vault_url,
                            credential,
                            generated_client=self._client,
                            **kwargs)
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_ENDPOINT = os.environ["VAULT_ENDPOINT"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_endpoint=VAULT_ENDPOINT, credential=credential)
    try:
        print("\n.. Create keys")
        rsa_key = await client.create_rsa_key("rsaKeyName", hsm=False)
        ec_key = await client.create_ec_key("ecKeyName", hsm=False)
        print("Created key '{0}' of type '{1}'.".format(
            rsa_key.name, rsa_key.key_material.kty))
        print("Created key '{0}' of type '{1}'.".format(
            ec_key.name, ec_key.key_material.kty))

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

        await asyncio.sleep(20)

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

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

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

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

    finally:
        print("\nrun_sample done")
Esempio n. 20
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._credential = credential
     self._keys = KeyClient(self.vault_url, credential, generated_client=self._client, **kwargs)
     if not is_live:
         # ensure pollers don't sleep during playback
         self._keys.delete_key = functools.partial(self._keys.delete_key, _polling_interval=0)
         self._keys.recover_deleted_key = functools.partial(self._keys.recover_deleted_key, _polling_interval=0)
    async def test_selective_key_restore(self, container_uri, sas_token):
        # create a key to selectively restore
        key_client = KeyClient(self.managed_hsm["url"], self.credential)
        key_name = self.get_resource_name("selective-restore-test-key")
        await key_client.create_rsa_key(key_name)

        # backup the vault
        backup_client = KeyVaultBackupClient(self.managed_hsm["url"],
                                             self.credential)
        backup_poller = await backup_client.begin_full_backup(
            container_uri, sas_token)

        # check backup status and result
        job_id = backup_poller.polling_method().resource().id
        backup_status = await backup_client.get_backup_status(job_id)
        assert_in_progress_operation(backup_status)
        backup_operation = await backup_poller.result()
        assert_successful_operation(backup_operation)
        backup_status = await backup_client.get_backup_status(job_id)
        assert_successful_operation(backup_status)

        # restore the key
        folder_name = backup_operation.azure_storage_blob_container_uri.split(
            "/")[-1]
        restore_poller = await backup_client.begin_selective_restore(
            container_uri, sas_token, folder_name, key_name)

        # check restore status and result
        job_id = restore_poller.polling_method().resource().id
        restore_status = await backup_client.get_restore_status(job_id)
        assert_in_progress_operation(restore_status)
        restore_operation = await restore_poller.result()
        assert_successful_operation(restore_operation)
        restore_status = await backup_client.get_restore_status(job_id)
        assert_successful_operation(restore_status)

        # delete the key
        await self._poll_until_no_exception(
            key_client.delete_key,
            key_name,
            expected_exception=ResourceExistsError)
        await key_client.purge_deleted_key(key_name)
Esempio n. 22
0
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

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

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

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

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

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

    print("\nrun_sample done")
    await credential.close()
    await client.close()
Esempio n. 23
0
    async def test_selective_key_restore(self, container_uri, sas_token):
        # create a key to selectively restore
        key_client = KeyClient(self.managed_hsm["url"], self.credential)
        key_name = self.get_resource_name("selective-restore-test-key")
        await key_client.create_rsa_key(key_name)

        # backup the vault
        backup_client = KeyVaultBackupClient(self.managed_hsm["url"],
                                             self.credential)
        backup_poller = await backup_client.begin_backup(
            container_uri, sas_token)
        backup_operation = await backup_poller.result()

        # restore the key
        restore_poller = await backup_client.begin_restore(
            backup_operation.folder_url, sas_token, key_name=key_name)
        await restore_poller.wait()

        # delete the key
        await self._poll_until_no_exception(
            key_client.delete_key,
            key_name,
            expected_exception=ResourceExistsError)
        await key_client.purge_deleted_key(key_name)
Esempio n. 24
0
    async def test_selective_key_restore(self, container_uri, sas_token):
        # create a key to selectively restore
        key_client = KeyClient(self.managed_hsm["url"], self.credential)
        key_name = self.get_resource_name("selective-restore-test-key")
        await key_client.create_rsa_key(key_name)

        # backup the vault
        backup_client = KeyVaultBackupClient(self.managed_hsm["url"],
                                             self.credential)
        backup_poller = await backup_client.begin_full_backup(
            container_uri, sas_token)
        backup_operation = await backup_poller.result()
        assert_successful_operation(backup_operation)

        # restore the key
        folder_name = backup_operation.azure_storage_blob_container_uri.split(
            "/")[-1]
        restore_poller = await backup_client.begin_selective_restore(
            container_uri, sas_token, folder_name, key_name)
        restore_operation = await restore_poller.result()
        assert_successful_operation(restore_operation)

        await key_client.delete_key(key_name)
        await key_client.purge_deleted_key(key_name)
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

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

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

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

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

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

    print("\nrun_sample done")
    await credential.close()
    await client.close()
Esempio n. 26
0
 def __init__(self):
     args = self.get_client_args()
     self.key_client = KeyClient(**args)
     self.key_name = "key-name-" + uuid.uuid1().hex
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

    # First, create a key
    key_name = "rotation-sample-key"
    key = await client.create_rsa_key(key_name)
    print("\nCreated a key; new version is {}".format(key.properties.version))

    # Set the key's automated rotation policy to rotate the key two months after the key was created
    actions = [
        KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE,
                                  time_after_create="P2M")
    ]
    updated_policy = await client.update_key_rotation_policy(
        key_name, lifetime_actions=actions)

    # The created policy should only have one action
    assert len(updated_policy.lifetime_actions
               ) == 1, "There should be exactly one rotation policy action"
    policy_action = updated_policy.lifetime_actions[0]
    print("\nCreated a new key rotation policy: {} after {}".format(
        policy_action.action, policy_action.time_after_create))

    # Get the key's current rotation policy
    current_policy = await client.get_key_rotation_policy(key_name)
    policy_action = current_policy.lifetime_actions[0]
    print("\nCurrent rotation policy: {} after {}".format(
        policy_action.action, policy_action.time_after_create))

    # Update the key's automated rotation policy to notify 30 days before the key expires
    new_actions = [
        KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY,
                                  time_before_expiry="P30D")
    ]
    # You may also specify the duration after which the newly rotated key will expire
    # In this example, any new key versions will expire after 90 days
    new_policy = await client.update_key_rotation_policy(
        key_name, expires_in="P90D", lifetime_actions=new_actions)

    # The updated policy should only have one action
    assert len(new_policy.lifetime_actions
               ) == 1, "There should be exactly one rotation policy action"
    policy_action = new_policy.lifetime_actions[0]
    print("\nUpdated rotation policy: {} {} before expiry".format(
        policy_action.action, policy_action.time_before_expiry))

    # Finally, you can rotate a key on-demand by creating a new version of the key
    rotated_key = await client.rotate_key(key_name)
    print("\nRotated the key on-demand; new version is {}".format(
        rotated_key.properties.version))

    # To clean up, delete the key
    await client.delete_key(key_name)
    print("\nDeleted the key")

    await credential.close()
    await client.close()
async def test_positive_bytes_count_required():
    client = KeyClient("...", object())
    with pytest.raises(ValueError):
        await client.get_random_bytes(count=0)
    with pytest.raises(ValueError):
        await client.get_random_bytes(count=-1)
async def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)

    # First, create a key
    key_name = "rotation-sample-key"
    key = await client.create_rsa_key(key_name)
    print("\nCreated a key; new version is {}".format(key.properties.version))

    # Set the key's automated rotation policy to rotate the key two months after the key was created.
    # If you pass an empty KeyRotationPolicy() as the `policy` parameter, the rotation policy will be set to the
    # default policy. Any keyword arguments will update specified properties of the policy.
    actions = [KeyRotationLifetimeAction(KeyRotationPolicyAction.rotate, time_after_create="P2M")]
    updated_policy = await client.update_key_rotation_policy(
        key_name, KeyRotationPolicy(), expires_in="P90D", lifetime_actions=actions
    )
    assert updated_policy.expires_in == "P90D"

    # The updated policy should have the specified lifetime action
    policy_action = None
    for i in range(len(updated_policy.lifetime_actions)):
        if updated_policy.lifetime_actions[i].action == KeyRotationPolicyAction.rotate:
            policy_action = updated_policy.lifetime_actions[i]
    assert policy_action, "The specified action should exist in the key rotation policy"
    assert policy_action.time_after_create == "P2M", "The action should have the specified time_after_create"
    assert policy_action.time_before_expiry is None, "The action shouldn't have a time_before_expiry"
    print(
        "\nCreated a new key rotation policy: {} after {}".format(policy_action.action, policy_action.time_after_create)
    )

    # Get the key's current rotation policy
    current_policy = await client.get_key_rotation_policy(key_name)
    policy_action = None
    for i in range(len(current_policy.lifetime_actions)):
        if current_policy.lifetime_actions[i].action == KeyRotationPolicyAction.rotate:
            policy_action = current_policy.lifetime_actions[i]
    print("\nCurrent rotation policy: {} after {}".format(policy_action.action, policy_action.time_after_create))

    # Update the key's automated rotation policy to notify 10 days before the key expires
    new_actions = [KeyRotationLifetimeAction(KeyRotationPolicyAction.notify, time_before_expiry="P10D")]
    # To preserve an existing rotation policy, pass in the existing policy as the `policy` parameter.
    # Any property specified as a keyword argument will be overridden completely by the provided value.
    # In this case, the rotate action we created earlier will be removed from the policy.
    new_policy = await client.update_key_rotation_policy(key_name, current_policy, lifetime_actions=new_actions)
    assert new_policy.expires_in == "P90D", "The key's expiry time should have been preserved"

    # The updated policy should include the new notify action
    notify_action = None
    for i in range(len(new_policy.lifetime_actions)):
        if new_policy.lifetime_actions[i].action == KeyRotationPolicyAction.notify:
            notify_action = new_policy.lifetime_actions[i]

    assert notify_action, "The specified action should exist in the key rotation policy"
    assert notify_action.time_after_create is None, "The action shouldn't have a time_after_create"
    assert notify_action.time_before_expiry == "P10D", "The action should have the specified time_before_expiry"
    print("\nNew policy action: {} {} before expiry".format(notify_action.action, notify_action.time_before_expiry))

    # Finally, you can rotate a key on-demand by creating a new version of the key
    rotated_key = await client.rotate_key(key_name)
    print("\nRotated the key on-demand; new version is {}".format(rotated_key.properties.version))

    # To clean up, delete the key
    await client.delete_key(key_name)
    print("\nDeleted the key")

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


async def delete_keys_and_secrets():