-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Certs Final PR #7076
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Certs Final PR #7076
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
4a1db9a
keyvault certificate implementation
iscai-msft 5ff9a32
got rid of error mapping, README uses HttpResponseError instead
iscai-msft 1e8ea7e
updated README to conform to Charles' new README standard
iscai-msft 984891a
Merge branch 'master' of github.com:Azure/azure-sdk-for-python into c…
iscai-msft 4b820f1
added samples for issuers and contacts
iscai-msft e01fef0
switched from PFX to PKCS12 for SecretContentType enum
iscai-msft edefc1b
fixed key vault overview
iscai-msft 6e73f2e
got rid of adding RUN_IDENTIFIER to vault name
iscai-msft b54b39d
Merge branch 'certs_final' of github.com:iscai-msft/azure-sdk-for-pyt…
iscai-msft 34662de
got rid of erroneous references to keys
iscai-msft 7c9cfb2
Delete seed.txt
iscai-msft dc9f7c6
incorporated Charles' and Johan's comments
iscai-msft bdc7d8a
Merge branch 'certs_final' of github.com:iscai-msft/azure-sdk-for-pyt…
iscai-msft File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| # Release History | ||
|
|
||
| ## 4.0.0b1 (2019-06-28) | ||
| For release notes and more information please visit | ||
| https://aka.ms/azure-sdk-preview1-python |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| include *.md | ||
| include azure/__init__.py | ||
| include azure/keyvault/__init__.py | ||
| include azure/keyvault/certificates/__init__.py | ||
| include azure/keyvault/certificates/_generated/__init__.py | ||
| include azure/keyvault/certificates/aio/__init__.py |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,233 @@ | ||
| # Azure Key Vault Certificates client library for Python | ||
| Azure Key Vault is a cloud service that provides a secure management of certificates, which are built on top of keys and secrets and adds an automated renewal feature. The certificate client library allows you securely store and manage the life-cycle of your certificate, be notified about certificate life-cycle events, and supports automatic renewal with selected issuers. This library offers operations to create, retrieve, update, delete, purge, backup, restore, and list the certificates and its versions, and offers CRUD operations for the certificate issuers, contacts, and management policies of the certificates.. | ||
|
|
||
| [Source code][certificates_client_src] | [Package (PyPI)][pypi_package_certificates] | [API reference documentation][reference_docs] | [Product documentation][keyvault_docs] | [Samples][certificates_samples] | ||
| ## Getting started | ||
| ### Install the package | ||
| Install the Azure Key Vault client library for Python with [pip][pip]: | ||
|
|
||
| ```Bash | ||
| pip install azure-keyvault-certificates | ||
| ``` | ||
|
|
||
| ### Prerequisites | ||
| * An [Azure subscription][azure_sub]. | ||
| * Python 2.7, 3.5.3, or later to use this package. | ||
| * An existing Key Vault. If you need to create a Key Vault, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `<your-resource-group-name>` and `<your-key-vault-name>` with your own unique names: | ||
|
|
||
| ```Bash | ||
| az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name> | ||
| ``` | ||
|
|
||
| ### Authenticate the client | ||
| In order to interact with the Key Vault service, you'll need to create an instance of the [CertificateClient][certificate_client_docs] class. You would need a **vault url** and **client certificate credentials (client id, client secret, tenant id)** to instantiate a client object for using the `DefaultAzureCredential` examples in the README. `DefaultAzureCredential` authentication is achieved by providing client certificate credentials as seen in this getting started section, but you can find more ways to authenticate with [azure-identity][azure_identity]. | ||
|
|
||
| #### Create/Get credentials | ||
| Use the [Azure Cloud Shell][azure_cloud_shell] snippet below to create/get client certificate credentials. | ||
|
|
||
| * Create a service principal and configure its access to Azure resources: | ||
| ```Bash | ||
| az ad sp create-for-rbac -n <your-application-name> --skip-assignment | ||
| ``` | ||
| Output: | ||
| ```json | ||
| { | ||
| "appId": "generated-app-ID", | ||
| "displayName": "dummy-app-name", | ||
| "name": "http://dummy-app-name", | ||
| "password": "random-password", | ||
| "tenant": "tenant-ID" | ||
| } | ||
| ``` | ||
| * Use the credentials returned above to set **AZURE_CLIENT_ID**(appId), **AZURE_CLIENT_SECRET**(password) and (password) and **AZURE_TENANT_ID**(tenant) environment variables. The following example shows a way to do this in Bash: | ||
| ```Bash | ||
| export AZURE_CLIENT_ID="generated-app-ID" | ||
| export AZURE_CLIENT_SECRET="random-password" | ||
| export AZURE_TENANT_ID="tenant-ID" | ||
| ``` | ||
|
|
||
| * Grant the above mentioned application authorization to perform certificate operations on the keyvault: | ||
| ```Bash | ||
| az keyvault set-policy --name <your-key-vault-name> --spn $AZURE_CLIENT_ID --certificate-permissions backup create delete get import list purge recover restore update | ||
| ``` | ||
| > --certificate-permissions: | ||
| > Accepted values: backup, create, delete, deleteissuers, get, getissuers, import, list, listissuers, managecontacts, manageissuers, purge, recover, restore, setissuers, update | ||
|
|
||
| * Use the above mentioned Key Vault name to retrieve details of your Vault which also contains your Key Vault URL: | ||
| ```Bash | ||
| az keyvault show --name <your-key-vault-name> | ||
| ``` | ||
|
|
||
| #### Create Certificate client | ||
| Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET** and **AZURE_TENANT_ID** environment variables and replaced **your-vault-url** with the above returned URI, you can create the [CertificateClient][certificate_client_docs]: | ||
|
|
||
| ```python | ||
| from azure.identity import DefaultAzureCredential | ||
| from azure.keyvault.certificates import CertificateClient | ||
|
|
||
| credential = DefaultAzureCredential() | ||
|
|
||
| # Create a new certificate client using the default credential | ||
| certificate_client = CertificateClient(vault_url=<your-vault-url>, credential=credential) | ||
| ``` | ||
| ## Key concepts | ||
| ### Certificate | ||
| A certificate is the fundamental resource within Azure KeyVault. From a developer's perspective, Key Vault APIs accept and return certificates as the Certificate type. In addition to the certificate data, the following attributes may be specified: | ||
| * expires: Identifies the expiration time on or after which the certificate data should not be retrieved. | ||
| * not_before: Identifies the time after which the certificate will be active. | ||
| * enabled: Specifies whether the certificate data can be retrieved. | ||
| * created: Indicates when this version of the certificate was created. | ||
| * updated: Indicates when this version of the certificate was updated. | ||
|
|
||
| ### Certificate Client: | ||
| The Certificate client performs the interactions with the Azure Key Vault service for getting, setting, updating, deleting, and listing certificates and their versions. An asynchronous and synchronous CertificateClient exists in the SDK allowing for selection of a client based on an application's use case. Once you've initialized a CertificateClient, you can interact with the primary resource types in Key Vault. | ||
|
|
||
| ## Examples | ||
| The following section provides several code snippets using the above created `certificate_client`, covering some of the most common Azure Key Vault Certificate service related tasks, including: | ||
| * [Create a Certificate](#create-a-certificate) | ||
| * [Retrieve a Certificate](#retrieve-a-certificate) | ||
| * [Update an existing Certificate](#update-an-existing-certificate) | ||
| * [Delete a Certificate](#delete-a-certificate) | ||
| * [List Certificates](#list-certificates) | ||
| * | ||
|
|
||
| ### Create a Certificate | ||
| `create_certificate` creates a Certificate to be stored in the Azure Key Vault. If a certificate with the same name already exists, then a new version of the certificate is created. | ||
| Before creating a certificate, a management policy for the certificate can be created or our default policy will be used. The `create_certificate` operation returns a long running operation poller in both the synchronous and asynchronous method. | ||
| ```python | ||
| create_certificate_poller = certificate_client.create_certificate(name="cert-name") | ||
|
|
||
| create_certificate_poller.wait() | ||
| print(create_certificate_poller.result()) | ||
| ``` | ||
|
|
||
| ### Retrieve a Certificate | ||
| `get_certificate_with_policy` retrieves a certificate previously stored in the Key Vault without having to specify version. | ||
| ```python | ||
| certificate = certificate_client.get_certificate_with_policy(name="cert-name") | ||
|
|
||
| print(certificate.name) | ||
| print(certificate.version) | ||
| ``` | ||
|
|
||
| ### Update an existing Certificate | ||
| `update_certificate` updates a certificate previously stored in the Key Vault. | ||
| ```python | ||
| # You can specify additional application-specific metadata in the form of tags. | ||
| tags = {"foo": "updated tag"} | ||
|
|
||
| updated_certificate= certificate_client.update_certificate(name="cert-name", tags=tags) | ||
|
|
||
| print(updated_certificate.name) | ||
| print(updated_certificate.version) | ||
| print(updated_certificate.updated) | ||
| print(updated_certificate.tags) | ||
|
|
||
| ``` | ||
|
|
||
| ### Delete a Certificate | ||
| `delete_certificate` deletes a certificate previously stored in the Key Vault. When [soft-delete][soft_delete] is not enabled for the Key Vault, this operation permanently deletes the certificate. | ||
| ```python | ||
| deleted_certificate = certificate_client.delete_certificate(name="cert-name") | ||
|
|
||
| print(deleted_certificate.name) | ||
| print(deleted_certificate.deleted_date) | ||
| ``` | ||
| ### List Certificates | ||
| This example lists all the certificates in the specified Key Vault. | ||
| ```python | ||
| certificates = certificate_client.list_certificates() | ||
|
|
||
| for certificate in certificates: | ||
| # this list doesn't include versions of the certificates | ||
| print(certificate.name) | ||
| ``` | ||
|
|
||
| ## Troubleshooting | ||
| ### General | ||
| Key Vault clients raise exceptions defined in azure-core. For more detailed information about exceptions and how to deal with them, see [Azure Core exceptions][azure_core_exceptions]. | ||
|
|
||
| For example, if you try to retrieve a certificate after it is deleted a `404` error is returned, indicating resource not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. | ||
| ```python | ||
| from azure.core.exceptions import ResourceNotFoundError | ||
| try: | ||
| certificate_client.get_certificate(name="deleted_certificate", version="deleted_certificate_version") | ||
| except ResourceNotFoundError as e: | ||
| print(e.message) | ||
|
|
||
| Output: "certificate not found:deleted_certificate" | ||
| ``` | ||
| ### Logging | ||
| Network trace logging is disabled by default for this library. When enabled, this will be logged at DEBUG level. The logging policy is used to output the HTTP network trace to the configured logger. You can configure logging to print out debugging information to the stdout or write it to a file using the following example: | ||
|
|
||
| ```python | ||
| import sys | ||
| import logging | ||
| # Create a logger for the 'azure' SDK | ||
| logger = logging.getLogger(__name__) | ||
| logger.setLevel(logging.DEBUG) | ||
| # Configure a console output | ||
| handler = logging.StreamHandler(stream=sys.stdout) | ||
| logger.addHandler(handler) | ||
| # Configure a file output | ||
| file_handler = logging.FileHandler(filename) | ||
| logger.addHandler(file_handler) | ||
|
|
||
| # Enable network trace logging. This will be logged at DEBUG level. | ||
| # By default, network trace logging is disabled. | ||
| config = CertificateClient.create_config(credential=credential, logging_enable=True) | ||
| client = CertificateClient(vault_url=url, credential=credential, config=config) | ||
| ``` | ||
| The logger can also be enabled per operation. | ||
|
|
||
| ```python | ||
| certificate = certificate_client.get_certificate_with_policy(name="cert-name", logging_enable=True) | ||
| ``` | ||
|
|
||
| ## Next steps | ||
| Several KeyVault Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Key Vault: | ||
| * [test_examples_certificates.py][test_examples_certificates] - Contains the code snippets working with Key Vault certificates. | ||
| * [hello_world.py][hello_world_sample] and [hello_world_async.py][hello_world_async_sample] - Python code for working with Azure Key Vault, including: | ||
| * Create a new certificate | ||
| * Get an existing certificate | ||
| * Update an existing certificate | ||
| * Delete certificate | ||
| * [backup_restore_operations.py][backup_operations_sample] and [backup_restore_operations_async.py][backup_operations_async_sample] - Example code for working with Key Vault certficates backup and recovery, including: | ||
| * Create certificate | ||
| * Backup a certificate | ||
| * Delete the certificate | ||
| * Use backed up certificate bytes to restore the deleted certificate | ||
|
|
||
| ### Additional Documentation | ||
| For more extensive documentation on Azure Key Vault, see the [API reference documentation][reference_docs]. | ||
|
|
||
| ## Contributing | ||
| This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. | ||
|
|
||
| When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. | ||
|
|
||
| This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. | ||
|
|
||
| <!-- LINKS --> | ||
| [asyncio_package]: https://docs.python.org/3/library/asyncio.html | ||
| [azure_cloud_shell]: https://shell.azure.com/bash | ||
| [azure_core_exceptions]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/docs/exceptions.md | ||
| [azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity | ||
| [azure_sub]: https://azure.microsoft.com/free/ | ||
| [code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ | ||
| [backup_operations_sample]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations.py | ||
| [backup_operations_async_sample]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations_async.py | ||
| [hello_world_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-certificates/samples/hello_world.py | ||
| [hello_world_async_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-certificates/samples/hello_world_async.py | ||
| [certificate_client_docs]: https://azure.github.io/azure-sdk-for-python/ref/azure.keyvault.certificates.html#azure.keyvault.certificates.CertificateClient | ||
| [keyvault_docs]: https://docs.microsoft.com/en-us/azure/key-vault/ | ||
| [list_operations_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-certificates/samples/list_operations.py | ||
| [pip]: https://pypi.org/project/pip/ | ||
| [pypi_package_certificates]: https://pypi.org/project/azure-keyvault-certificates/ | ||
| [reference_docs]: https://azure.github.io/azure-sdk-for-python/ref/azure.keyvault.certificates.html | ||
| [certificates_client_src]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault/azure/keyvault/certificates | ||
| [certificates_samples]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates/samples | ||
| [soft_delete]: https://docs.microsoft.com/en-us/azure/key-vault/key-vault-ovw-soft-delete | ||
| [test_example_certificates]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-certificates/tests/test_example_certificates.py | ||
|
|
||
|  |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
| # pylint:disable=missing-docstring | ||
| __path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore |
6 changes: 6 additions & 0 deletions
6
sdk/keyvault/azure-keyvault-certificates/azure/keyvault/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
| # pylint:disable=missing-docstring | ||
| __path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore |
27 changes: 27 additions & 0 deletions
27
sdk/keyvault/azure-keyvault-certificates/azure/keyvault/certificates/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
| from .client import CertificateClient | ||
| from .enums import ActionType, JsonWebKeyCurveName, JsonWebKeyType, SecretContentType, KeyUsageType | ||
| from .models import ( | ||
| AdministratorDetails, | ||
| CertificatePolicy, | ||
| Contact, | ||
| KeyProperties, | ||
| LifetimeAction | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "ActionType", | ||
| "AdministratorDetails", | ||
| "CertificateClient", | ||
| "CertificatePolicy", | ||
| "Contact", | ||
| "JsonWebKeyCurveName", | ||
| "JsonWebKeyType", | ||
| "KeyProperties", | ||
| "KeyUsageType", | ||
| "LifetimeAction", | ||
| "SecretContentType" | ||
| ] |
63 changes: 63 additions & 0 deletions
63
sdk/keyvault/azure-keyvault-certificates/azure/keyvault/certificates/_polling.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # ------------------------------------------------------------------------- | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. See License.txt in the project root for | ||
| # license information. | ||
| # -------------------------------------------------------------------------- | ||
| import logging | ||
| import time | ||
|
|
||
| from azure.core.exceptions import HttpResponseError | ||
| from azure.core.polling import PollingMethod | ||
| from azure.keyvault.certificates._shared import parse_vault_id | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class CreateCertificatePoller(PollingMethod): | ||
| def __init__(self, interval=5, unknown_issuer=False): | ||
| self._command = None | ||
| self._status = None | ||
| self._certificate_id = None | ||
| self.polling_interval = interval | ||
| self.unknown_issuer = unknown_issuer | ||
|
|
||
| def _update_status(self): | ||
| # type: () -> None | ||
| pending_certificate = self._command() | ||
| self._status = pending_certificate.status.lower() | ||
| if not self._certificate_id: | ||
| self._certificate_id = parse_vault_id(pending_certificate.id) | ||
|
|
||
| def initialize(self, client, initial_response, _): | ||
| # type: (Any, Any, Callable) -> None | ||
| self._command = client | ||
| self._status = initial_response | ||
|
|
||
| def run(self): | ||
| # type: () -> None | ||
| try: | ||
| while not self.finished(): | ||
| self._update_status() | ||
| if self._status != 'completed' and self._status != 'inprogress' and self._status != 'cancelled': | ||
|
iscai-msft marked this conversation as resolved.
Outdated
|
||
| raise HttpResponseError( | ||
| 'Unknown status \'{}\' for pending certificate {}'.format(self._status, self._certificate_id)) | ||
| time.sleep(self.polling_interval) | ||
| except Exception as e: | ||
| logger.warning(str(e)) | ||
| raise | ||
|
|
||
| def finished(self): | ||
| # type: () -> bool | ||
| if self.unknown_issuer: | ||
| return True | ||
| return self._status != 'inprogress' | ||
|
iscai-msft marked this conversation as resolved.
Outdated
|
||
|
|
||
| def resource(self): | ||
| # type: () -> str | ||
| if not self.finished(): | ||
| self._update_status() | ||
| return self._status | ||
|
|
||
| def status(self): | ||
| # type: () ->str | ||
| return self._status | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.