|
1 | | -# Azure KeyVault keys client library for Rust |
| 1 | +# Azure Key Vault keys client library for Rust |
2 | 2 |
|
3 | | -Azure Key Vault is a cloud service that provides secure storage and management of sensitive information such as API keys, passwords, certificates, and cryptographic keys. The `azure_security_keyvault_keys` crate provides a client library for interacting with the Azure Key Vault Keys service. |
| 3 | +Azure Key Vault is a cloud service that provides secure storage of keys for encrypting your data. Multiple keys, and multiple versions of the same key, can be kept in the Azure Key Vault. Cryptographic keys in Azure Key Vault are represented as [JSON Web Key (JWK)](https://tools.ietf.org/html/rfc7517) objects. |
| 4 | + |
| 5 | +Azure Key Vault Managed HSM is a fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs. |
| 6 | + |
| 7 | +The Azure Key Vault keys library client supports RSA keys and Elliptic Curve (EC) keys, each with corresponding support in hardware security modules (HSM). It offers operations to create, retrieve, update, delete, purge, backup, restore, and list the keys and its versions. |
| 8 | + |
| 9 | +[Source code] | [Package (crates.io)] | [API reference documentation] | [Product documentation] |
4 | 10 |
|
5 | 11 | ## Getting started |
6 | 12 |
|
7 | | -### Install the crate |
| 13 | +### Install the package |
8 | 14 |
|
9 | | -Install the Azure Key Vault keys library for Rust with cargo: |
| 15 | +Install the Azure Key Vault keys client library for Rust with [Cargo]: |
10 | 16 |
|
11 | | -```bash |
| 17 | +```sh |
12 | 18 | cargo add azure_security_keyvault_keys |
13 | 19 | ``` |
14 | 20 |
|
15 | 21 | ### Prerequisites |
16 | 22 |
|
17 | | -- An [Azure subscription](https://azure.microsoft.com/free/) |
18 | | -- A [Key Vault resource](https://docs.microsoft.com/azure/key-vault/quick-create-portal) |
| 23 | +* An [Azure subscription]. |
| 24 | +* An existing Azure Key Vault. If you need to create an Azure Key Vault, you can use the Azure Portal or [Azure CLI]. |
| 25 | +* Authorization to an existing Azure Key Vault using either [RBAC] (recommended) or [access control]. |
| 26 | + |
| 27 | +If you use the Azure CLI, replace `<your-resource-group-name>` and `<your-key-vault-name>` with your own, unique names: |
| 28 | + |
| 29 | +```azurecli |
| 30 | +az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name> |
| 31 | +``` |
| 32 | + |
| 33 | +### Install dependencies |
| 34 | + |
| 35 | +Add the following crates to your project: |
| 36 | + |
| 37 | +```sh |
| 38 | +cargo add azure_identity tokio |
| 39 | +``` |
| 40 | + |
| 41 | +### Authenticate the client |
| 42 | + |
| 43 | +In order to interact with the Azure Key Vault service, you'll need to create an instance of the `KeyClient`. You need a **vault url**, which you may see as "DNS Name" in the portal, and credentials to instantiate a client object. |
| 44 | + |
| 45 | +The example shown below uses a `DefaultAzureCredential`, which is appropriate for local development environments. We recommend using a managed identity for authentication in production environments. You can find more information on different ways of authenticating and their corresponding credential types in the [Azure Identity] documentation. |
| 46 | + |
| 47 | +The `DefaultAzureCredential` will automatically pick up on an Azure CLI authentication. Ensure you are logged in with the Azure CLI: |
| 48 | + |
| 49 | +```azurecli |
| 50 | +az login |
| 51 | +``` |
| 52 | + |
| 53 | +Instantiate a `DefaultAzureCredential` to pass to the client. The same instance of a token credential can be used with multiple clients if they will be authenticating with the same identity. |
| 54 | + |
| 55 | +#### Activate your Managed HSM |
19 | 56 |
|
20 | | -### Authentication |
| 57 | +This section only applies if you are creating a Managed HSM. All data plane commands are disabled until the HSM is activated. You will not be able to create keys or assign roles. Only the designated administrators that were assigned during the create command can activate the HSM. To activate the HSM you must download the security domain. |
21 | 58 |
|
22 | | -This crate uses the [azure_identity](https://crates.io/crates/azure_identity) crate for authentication. You can authenticate using a variety of methods, including environment variables, managed identity, and more. |
| 59 | +To activate your HSM you need: |
| 60 | + |
| 61 | +* Minimum 3 RSA key-pairs (maximum 10) |
| 62 | +* Specify minimum number of keys required to decrypt the security domain (quorum) |
| 63 | + |
| 64 | +To activate the HSM you send at least 3 (maximum 10) RSA public keys to the HSM. The HSM encrypts the security domain with these keys and sends it back. Once this security domain is successfully downloaded, your HSM is ready to use. You also need to specify quorum, which is the minimum number of private keys required to decrypt the security domain. |
| 65 | + |
| 66 | +The example below shows how to use openssl to generate 3 self-signed certificate. |
| 67 | + |
| 68 | +```sh |
| 69 | +openssl req -newkey rsa:2048 -nodes -keyout cert_0.key -x509 -days 365 -out cert_0.cer |
| 70 | +openssl req -newkey rsa:2048 -nodes -keyout cert_1.key -x509 -days 365 -out cert_1.cer |
| 71 | +openssl req -newkey rsa:2048 -nodes -keyout cert_2.key -x509 -days 365 -out cert_2.cer |
| 72 | +``` |
| 73 | + |
| 74 | +Use the `az keyvault security-domain download` command to download the security domain and activate your managed HSM. The example below uses 3 RSA key pairs (only public keys are needed for this command) and sets the quorum to 2. |
| 75 | + |
| 76 | +```azurecli |
| 77 | +az keyvault security-domain download --hsm-name <your-key-vault-name> --sd-wrapping-keys ./certs/cert_0.cer ./certs/cert_1.cer ./certs/cert_2.cer --sd-quorum 2 --security-domain-file ContosoHSM-SD.json |
| 78 | +``` |
23 | 79 |
|
24 | 80 | ## Key concepts |
25 | 81 |
|
| 82 | +### KeyBundle |
| 83 | + |
| 84 | +Azure Key Vault supports multiple key types and algorithms, and enables the use of hardware security modules (HSM) for high value keys. |
| 85 | + |
26 | 86 | ### KeyClient |
27 | 87 |
|
28 | | -The `KeyClient` struct provides methods to manage keys in the Azure Key Vault. You can create, retrieve, update, and delete keys, as well as perform cryptographic operations. |
| 88 | +The `KeyClient` provides asynchronous operations for working with Key Vault keys. |
| 89 | + |
| 90 | +### Thread safety |
| 91 | + |
| 92 | +We guarantee that all client instance methods are thread-safe and independent of each other. This ensures that the recommendation of reusing client instances is always safe, even across threads. |
29 | 93 |
|
30 | 94 | ## Examples |
31 | 95 |
|
32 | | -### Creating a key |
| 96 | +The following section provides several code snippets using the `KeyClient`, covering some of the most common Azure Key Vault keys service related tasks: |
| 97 | + |
| 98 | +* [Create a key](#create-a-key) |
| 99 | +* [Retrieve a key](#retrieve-a-key) |
| 100 | +* [Update an existing key](#update-an-existing-key) |
| 101 | +* [Delete a key](#delete-a-key) |
| 102 | +* [List keys](#list-keys) |
| 103 | + |
| 104 | +### Create a key |
| 105 | + |
| 106 | +`create_key` creates a Key Vault key to be stored in the Azure Key Vault. If a key with the same name already exists, then a new version of the key is created. |
33 | 107 |
|
34 | 108 | ```rust no_run |
35 | 109 | use azure_identity::DefaultAzureCredential; |
36 | | -use azure_security_keyvault_keys::{models::KeyCreateParameters, KeyClient}; |
| 110 | +use azure_security_keyvault_keys::{ |
| 111 | + models::{KeyBundle, KeyCreateParameters, JsonWebKeyCurveName, JsonWebKeyType}, |
| 112 | + ResourceExt, KeyClient, |
| 113 | +}; |
37 | 114 |
|
38 | 115 | #[tokio::main] |
39 | 116 | async fn main() -> Result<(), Box<dyn std::error::Error>> { |
40 | 117 | let credential = DefaultAzureCredential::new()?; |
| 118 | + let client = KeyClient::new( |
| 119 | + "https://your-key-vault-name.vault.azure.net/", |
| 120 | + credential.clone(), |
| 121 | + None, |
| 122 | + )?; |
| 123 | + |
| 124 | + // Create an EC key. |
| 125 | + let body = KeyCreateParameters { |
| 126 | + kty: Some(JsonWebKeyType::EC), |
| 127 | + curve: Some(JsonWebKeyCurveName::P256), |
| 128 | + ..Default::default() |
| 129 | + }; |
| 130 | + |
| 131 | + let key = client |
| 132 | + .create_key("key-name", body.try_into()?, None) |
| 133 | + .await? |
| 134 | + .into_body() |
| 135 | + .await?; |
| 136 | + |
| 137 | + println!( |
| 138 | + "Key Name: {:?}, Type: {:?}, Version: {:?}", |
| 139 | + key.resource_id()?.name, |
| 140 | + key.key.as_ref().map(|k| k.kty.as_ref()), |
| 141 | + key.resource_id()?.version, |
| 142 | + ); |
| 143 | + |
| 144 | + Ok(()) |
| 145 | +} |
| 146 | +``` |
| 147 | + |
| 148 | +### Retrieve a key |
| 149 | + |
| 150 | +`get_key` retrieves a public key (or only metadata for symmetric keys) previously stored in the Azure Key Vault. Setting the `key-version` to an empty string will return the latest version. |
41 | 151 |
|
| 152 | +```rust no_run |
| 153 | +use azure_identity::DefaultAzureCredential; |
| 154 | +use azure_security_keyvault_keys::{models::KeyBundle, KeyClient}; |
| 155 | + |
| 156 | +#[tokio::main] |
| 157 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 158 | + let credential = DefaultAzureCredential::new()?; |
42 | 159 | let client = KeyClient::new( |
43 | | - "https://<your-key-vault-name>.vault.azure.net", |
| 160 | + "https://your-key-vault-name.vault.azure.net/", |
44 | 161 | credential.clone(), |
45 | 162 | None, |
46 | 163 | )?; |
47 | 164 |
|
| 165 | + // Retrieve a public key as a JWK using the key client. |
48 | 166 | let key = client |
49 | | - .create_key("my-key", KeyCreateParameters::default().try_into()?, None) |
| 167 | + .get_key("key-name".into(), "key-version".into(), None) |
| 168 | + .await? |
| 169 | + .into_body() |
| 170 | + .await?; |
| 171 | + |
| 172 | + println!("Key: {:#?}", key.key); |
| 173 | + |
| 174 | + Ok(()) |
| 175 | +} |
| 176 | +``` |
| 177 | + |
| 178 | +### Update an existing key |
| 179 | + |
| 180 | +`update_key` updates a key previously stored in the Azure Key Vault. Only the attributes of the key are updated. To update the value, call `KeyClient::create_key` on a key with the same name. |
| 181 | + |
| 182 | +```rust no_run |
| 183 | +use azure_identity::DefaultAzureCredential; |
| 184 | +use azure_security_keyvault_keys::{ |
| 185 | + models::{KeyAttributes, KeyUpdateParameters}, |
| 186 | + KeyClient, |
| 187 | +}; |
| 188 | +use std::collections::HashMap; |
| 189 | + |
| 190 | +#[tokio::main] |
| 191 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 192 | + let credential = DefaultAzureCredential::new()?; |
| 193 | + let client = KeyClient::new( |
| 194 | + "https://your-key-vault-name.vault.azure.net/", |
| 195 | + credential.clone(), |
| 196 | + None, |
| 197 | + )?; |
| 198 | + |
| 199 | + // Update a key using the key client. |
| 200 | + let key_update_parameters = KeyUpdateParameters { |
| 201 | + tags: Some(HashMap::from_iter(vec![( |
| 202 | + "tag-name".into(), |
| 203 | + "tag-value".into(), |
| 204 | + )])), |
| 205 | + ..Default::default() |
| 206 | + }; |
| 207 | + |
| 208 | + client |
| 209 | + .update_key( |
| 210 | + "key-name".into(), |
| 211 | + "".into(), |
| 212 | + key_update_parameters.try_into()?, |
| 213 | + None, |
| 214 | + ) |
50 | 215 | .await? |
51 | 216 | .into_body() |
52 | 217 | .await?; |
53 | | - |
54 | | - println!("Created key: {:?}", key); |
55 | 218 |
|
56 | 219 | Ok(()) |
57 | 220 | } |
58 | 221 | ``` |
59 | 222 |
|
| 223 | +### Delete a key |
| 224 | + |
| 225 | +`delete_key` will tell Key Vault to delete a key but it is not deleted immediately. It will not be deleted until the service-configured data retention period - the default is 90 days - or until you call `purge_key` on the returned `DeletedKeyBundle.id`. |
| 226 | + |
| 227 | +```rust no_run |
| 228 | +use azure_identity::DefaultAzureCredential; |
| 229 | +use azure_security_keyvault_keys::KeyClient; |
| 230 | + |
| 231 | +#[tokio::main] |
| 232 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 233 | + let credential = DefaultAzureCredential::new()?; |
| 234 | + let client = KeyClient::new( |
| 235 | + "https://your-key-vault-name.vault.azure.net/", |
| 236 | + credential.clone(), |
| 237 | + None, |
| 238 | + )?; |
| 239 | + |
| 240 | + // Delete a key using the key client. |
| 241 | + client |
| 242 | + .delete_key("key-name".into(), None) |
| 243 | + .await?; |
| 244 | + |
| 245 | + Ok(()) |
| 246 | +} |
| 247 | +``` |
| 248 | + |
| 249 | +### List keys |
| 250 | + |
| 251 | +This example lists all the keys in the specified Azure Key Vault. |
| 252 | + |
| 253 | +```rust no_run |
| 254 | +use azure_identity::DefaultAzureCredential; |
| 255 | +use azure_security_keyvault_keys::{ResourceExt, KeyClient}; |
| 256 | +use futures::TryStreamExt; |
| 257 | + |
| 258 | +#[tokio::main] |
| 259 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 260 | + // Create a new key client |
| 261 | + let credential = DefaultAzureCredential::new()?; |
| 262 | + let client = KeyClient::new( |
| 263 | + "https://your-key-vault-name.vault.azure.net/", |
| 264 | + credential.clone(), |
| 265 | + None, |
| 266 | + )?; |
| 267 | + |
| 268 | + let mut pager = client.get_keys(None)?.into_stream(); |
| 269 | + while let Some(keys) = pager.try_next().await? { |
| 270 | + let Some(keys) = keys.into_body().await?.value else { |
| 271 | + continue; |
| 272 | + }; |
| 273 | + |
| 274 | + for key in keys { |
| 275 | + // Get the key name from the ID. |
| 276 | + let name = key.resource_id()?.name; |
| 277 | + println!("Found Key with Name: {}", name); |
| 278 | + } |
| 279 | + } |
| 280 | + |
| 281 | + Ok(()) |
| 282 | +} |
| 283 | +``` |
| 284 | + |
| 285 | +## Troubleshooting |
| 286 | + |
| 287 | +### General |
| 288 | + |
| 289 | +When you interact with the Azure Key Vault keys client library using the Rust SDK, errors returned by the service correspond to the same HTTP status codes returned for [REST API] requests. |
| 290 | + |
| 291 | +For example, if you try to retrieve a key that doesn't exist in your Azure Key Vault, a `404` error is returned, indicating `Not Found`. |
| 292 | + |
| 293 | +```rust no_run |
| 294 | +use azure_identity::DefaultAzureCredential; |
| 295 | +use azure_security_keyvault_keys::KeyClient; |
| 296 | + |
| 297 | + |
| 298 | +#[tokio::main] |
| 299 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 300 | + let credential = DefaultAzureCredential::new()?; |
| 301 | + let client = KeyClient::new( |
| 302 | + "https://ronnieg-keyvault.vault.azure.net/", |
| 303 | + credential.clone(), |
| 304 | + None, |
| 305 | + )?; |
| 306 | + |
| 307 | + match client |
| 308 | + .get_key( |
| 309 | + "key-name".into(), |
| 310 | + "".into(), |
| 311 | + None, |
| 312 | + ) |
| 313 | + .await |
| 314 | + { |
| 315 | + Ok(response) => println!("Key: {:#?}", response.into_body().await?.key), |
| 316 | + Err(err) => println!("Error: {:#?}", err.into_inner()?), |
| 317 | + } |
| 318 | + |
| 319 | + Ok(()) |
| 320 | +} |
| 321 | +``` |
| 322 | + |
| 323 | +You will notice that additional information is logged, like the Client Request ID of the operation. |
| 324 | + |
| 325 | +```text |
| 326 | +Error: HttpError { |
| 327 | + status: NotFound, |
| 328 | + details: ErrorDetails { |
| 329 | + code: Some( |
| 330 | + "KeyNotFound", |
| 331 | + ), |
| 332 | + message: Some( |
| 333 | + "A key with (name/id) key-name1 was not found in this key vault. If you recently deleted this key you may be able to recover it using the correct recovery command. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125182", |
| 334 | + ), |
| 335 | + }, |
| 336 | + .. |
| 337 | +} |
| 338 | +``` |
| 339 | + |
60 | 340 | ## Contributing |
61 | 341 |
|
62 | | -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](https://cla.microsoft.com). |
| 342 | +See the [CONTRIBUTING.md] for details on building, testing, and contributing to these libraries. |
| 343 | + |
| 344 | +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://opensource.microsoft.com/cla/>. |
63 | 345 |
|
64 | 346 | 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. |
65 | 347 |
|
66 | | -This project has adopted the [Microsoft Open Source Code of Conduct ](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. |
| 348 | +This project has adopted the [Microsoft Open Source Code of Conduct ]. For more information see the [Code of Conduct FAQ ] or contact <[email protected]> with any additional questions or comments. |
| 349 | + |
| 350 | +<!-- LINKS --> |
| 351 | +[API reference documentation]: https://docs.rs/azure_security_keyvault_keys/latest/azure_security_keyvault_keys |
| 352 | +[Azure CLI]: https://learn.microsoft.com/cli/azure |
| 353 | +[Azure subscription]: https://azure.microsoft.com/free/ |
| 354 | +[Azure Identity]: https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/identity/azure_identity |
| 355 | +[Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/ |
| 356 | +[Product documentation]: https://learn.microsoft.com/azure/key-vault/ |
| 357 | +[REST API]: https://learn.microsoft.com/rest/api/keyvault/ |
| 358 | +[Cargo]: https://crates.io/ |
| 359 | +[Package (crates.io)]: https://crates.io/crates/azure_security_keyvault_keys |
| 360 | +[Source code]: https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/keyvault/azure_security_keyvault_keys/src |
| 361 | +[CONTRIBUTING.md]: https://github.com/Azure/azure-sdk-for-rust/blob/main/CONTRIBUTING.md |
| 362 | +[Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/ |
| 363 | +[access control]: https://learn.microsoft.com/azure/key-vault/general/assign-access-policy |
| 364 | +[RBAC]: https://learn.microsoft.com/azure/key-vault/general/rbac-guide |
0 commit comments