Skip to content
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

Certs Final PR #7076

Merged
merged 13 commits into from
Sep 6, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions sdk/keyvault/azure-keyvault-certificates/HISTORY.md
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
6 changes: 6 additions & 0 deletions sdk/keyvault/azure-keyvault-certificates/MANIFEST.in
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
324 changes: 324 additions & 0 deletions sdk/keyvault/azure-keyvault-certificates/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,324 @@
# Azure Key Vault Certificates client library for Python
Azure Key Vault helps solve the following problems:
- Cryptographic key management (this library) - create, store, and control
access to the keys used to encrypt your data
- Secrets management
([`azure-keyvault-secrets`](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-secrets)) -
securely store and control access to tokens, passwords, certificates, API keys,
and other secrets
- Certificate management
([`azure-keyvault-certificates`](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates)) -
create, manage, and deploy public and private SSL/TLS 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.
* A 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>
```

Output:
```json
{
"id": "...",
"location": "westus2",
"name": "<your key vault name>",
"properties": {
"accessPolicies": [...],
"createMode": null,
"enablePurgeProtection": null,
"enableSoftDelete": null,
"enabledForDeployment": false,
"enabledForDiskEncryption": null,
"enabledForTemplateDeployment": null,
"networkAcls": null,
"provisioningState": "Succeeded",
"sku": { "name": "standard" },
"tenantId": "...",
"vaultUri": "https://<your key vault name>.vault.azure.net/"
},
"resourceGroup": "<your resource group name>",
"type": "Microsoft.KeyVault/vaults"
}
```

> The `"vaultUri"` property is the `vault_url` used by `KeyClient`.

### Authenticate the client
In order to interact with a Key Vault's certificates, you'll need an instance of the [CertificateClient][certificate_client_docs]
class. Creating one requires a **vault url** and
**credential**. This document demonstrates using `DefaultAzureCredential` as
the credential, authenticating with a service principal's client id, secret,
and tenant id. Other authentication methods are supported. See the
[azure-identity][azure_identity] documentation for more details.

#### Create a service principal
Use this [Azure Cloud Shell][azure_cloud_shell] snippet to create a
service principal:

* 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": "your-application-name",
"name": "http://your-application-name",
"password": "random password",
"tenant": "tenant id"
}
```

* Use the output to set **AZURE_CLIENT_ID** (appId), **AZURE_CLIENT_SECRET**
(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"
```

* Authorize the service principal to perform key operations in your Key Vault:
```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
```
> Possible certificate permissions: backup, create, delete, deleteissuers, get, getissuers, import, list, listissuers, managecontacts, manageissuers, purge, recover, restore, setissuers, update

#### Create a client
After setting the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET** and
**AZURE_TENANT_ID** environment variables, 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
With a `CertificateClient` you can get certificates from the vault, create new certificates and
new versions of existing certificates, update certificate metadata, and delete certificates. You
can also manage certificate issuers, contacts, and management policies of certificates. This is
illustrated in the [examples](#examples) below..

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

## Examples
This section contains code snippets covering common tasks:
* [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.
```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)
```

### Async operations
This library includes a complete async API supported on Python 3.5+. To use it, you must
first install an async transport, such as [`aiohttp`](https://pypi.org/project/aiohttp/).
See
[azure-core documentation](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/README.md#transport)
for more information.

### Asynchronously 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 an async long running operation poller.
```python
create_certificate_poller = await certificate_client.create_certificate(name="cert-name")

create_certificate_result = await create_certificate_poller
print(create_certificate_result)
```

### Asynchronously list keys
iscai-msft marked this conversation as resolved.
Show resolved Hide resolved
This example lists all the certificates in the client's vault:
```python
certificates = certificate_client.list_certificates()

async for certificate in certificates:
print(certificate.name)
```

## Troubleshooting
### General
Key Vault clients raise exceptions defined in [`azure-core`][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 HttpResponseError
try:
certificate_client.get_certificate(name="deleted_certificate", version="deleted_certificate_version")
except HttpResponseError as e:
print(e.message)

Output: "certificate not found:deleted_certificate"
```
### Logging
Network trace logging is disabled by default for this library. When enabled,
HTTP requests will be logged at DEBUG level using the `logging` library. You
can configure logging to print debugging information to stdout or write it
to a file:

```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.
config = CertificateClient.create_config(credential=credential, logging_enable=True)
client = CertificateClient(vault_url=url, credential=credential, config=config)
```

Network trace logging can also be enabled for any single operation:
```python
certificate = certificate_client.get_certificate_with_policy(name="cert-name", logging_enable=True)
```

## Next steps
Several samples are available in the Azure SDK for Python GitHub repository. These samples provide example code for additional Key Vault scenarios:
* [test_examples_certificates.py][test_example_certificates] and
[test_examples_certificates_async.py][test_example_certificates_async] - code snippets from
the library's documentation
* [hello_world.py][hello_world_sample] and [hello_world_async.py][hello_world_async_sample] - create/get/update/delete certificates
* [backup_restore_operations.py][backup_operations_sample] and [backup_restore_operations_async.py][backup_operations_async_sample] - backup and
recover certificates

### 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 [email protected] with any
additional questions or comments.

[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_examples_certificates.py
[test_example_certificates_async]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-certificates/tests/test_examples_certificates_async.py

![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Fkeyvault%2Fazure-keyvault-certificates%2FFREADME.png)
6 changes: 6 additions & 0 deletions sdk/keyvault/azure-keyvault-certificates/azure/__init__.py
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
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
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"
]
Loading