diff --git a/sdk/keyvault/keyvault-keys/CHANGELOG.md b/sdk/keyvault/keyvault-keys/CHANGELOG.md deleted file mode 100644 index 371425b22411..000000000000 --- a/sdk/keyvault/keyvault-keys/CHANGELOG.md +++ /dev/null @@ -1,362 +0,0 @@ -# Release History - -## 4.9.1 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -- Generate code from TypeSpec. This is an internal change that should not affect customers. [#31845](https://github.com/Azure/azure-sdk-for-js/pull/31845) - -## 4.9.0 (2024-10-16) - -### Features Added - -- Add support for Continuous Access Evaluation (CAE). [#31140](https://github.com/Azure/azure-sdk-for-js/pull/31140) - -### Other Changes - -- Native ESM support has been added, and this package will now emit both CommonJS and ESM. [#31332](https://github.com/Azure/azure-sdk-for-js/pull/31332) - -## 4.8.0 (2024-02-14) - -### Features Added - -Since 4.7.2: - -- Added `hsmPlatform` property to `KeyProperties`. - -### Other Changes - -- The default service version is now `7.5`. - -## 4.8.0-beta.1 (2023-11-08) - -### Features Added - -- Added `hsmPlatform` property to `KeyProperties`. - -### Other Changes - -- The default service version is now `7.5-preview.1`. - -## 4.7.2 (2023-08-10) - -### Bugs Fixed - -- Fixed a bug where `listPropertiesOfKeysVersions` failed to retrieve the second page of results. Issue [#26547](https://github.com/Azure/azure-sdk-for-js/issues/26547); PR [#26584](https://github.com/Azure/azure-sdk-for-js/pull/26584). -- Bumped `@azure/core-rest-pipeline` dependency to version including the `isRestError` helper, which was used in PR [#26016](https://github.com/Azure/azure-sdk-for-js/issues/26016). - -## 4.7.1 (2023-06-06) - -### Bugs Fixed - -- Fixed an issue where cryptographic operations would fail if the client did not have the get permission on the key, even if it had permission for the underlying operation. Issue [#26001](https://github.com/Azure/azure-sdk-for-js/issues/26001); PR [#26016](https://github.com/Azure/azure-sdk-for-js/issues/26016) - -## 4.7.0 (2023-03-09) - -### Breaking Changes - -- Removed support for OKP key types as introduced in 4.7.0-beta.1. These changes are only breaking for customers consuming the 4.7.0-beta.1 API, and do not affect those consuming a stable release such as 4.6.0. - - Removed `OKP` and `OKP-HSM` from `KnownKeyTypes`. - - Removed `EdDSA` from `KnownSignatureAlgorithms`. - - Removed `Ed25519` from `KnownKeyCurveNames`. - -### Other Changes - -- `KeyClient` and `CryptographyClient` now support service version 7.4 by default. - -## 4.7.0-beta.1 (2022-11-10) - -- Added support for [Octet Key Pair (OKP)](https://datatracker.ietf.org/doc/html/rfc8037) key types as well as `sign`, `verify`, `signData`, and `verifyData` cryptography operations when using OKP keys. - - Added support for the Ed25519 curve for the creation of OKP keys. - -## 4.6.0 (2022-09-20) - -### Breaking Changes - -- Verify the challenge resource matches the vault domain. - This should affect few customers who can set `disableChallengeResourceVerification` in the options bag to `true` to disable. - See https://aka.ms/azsdk/blog/vault-uri for more information. - -## 4.5.0 (2022-08-09) - -### Breaking Changes - -- Migrated to the Core v2 HTTP pipeline. As a result of this migration: - - The response types no longer contain the raw response `_response`. To access the raw response, an `onResponse` callback has to be passed in the request options bag, for example: - ```ts - let rawResponse: FullOperationResponse | undefined; - await client.operationName(/* ...parameters... */, { - onResponse: (response) => (rawResponse = response), - }); - ``` - - The re-export of the `PipelineOptions` type from `@azure/core-http` has been removed. If you previously relied on this export, consider either using the more specific `CertificateClientOptions` type or importing `PipelineOptions` from `@azure/core-http` directly. - -### Other Changes - -- Documentation fixes. - -## 4.5.0-beta.1 (2022-07-07) - -### Breaking Changes - -- As a result of the migration to Core v2: - - The response types no longer contain the raw response `_response`. To access the raw response, an `onResponse` callback has to be passed in the request options bag, for example: - ```ts - let rawResponse: FullOperationResponse | undefined; - await client.operationName(/* ...parameters... */, { - onResponse: (response) => (rawResponse = response), - }); - ``` - - The re-export of the `PipelineOptions` type from `@azure/core-http` has been removed. If you previously relied on this export, consider either using the more specific `CertificateClientOptions` type or importing `PipelineOptions` from `@azure/core-http` directly. - -### Other Changes - -- Migrated the generated client to `@azure/core-rest-pipeline` ("Core v2"). See [Azure Core v1 vs v2](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-rest-pipeline/documentation/core2.md) for more on the difference and benefits of the move. - -## 4.4.0 (2022-03-24) - -### Features Added - -- Added support for `KeyClient.getRandomBytes` which, when connected to a managed HSM, can be used to generate a byte array of a given length with random values. -- Added support for Secure key Release from a Managed HSM. - - Added `KeyClient.releaseKey` to release a key from a Managed HSM. - - Added `exportable` and `releasePolicy` to `KeyVaultKey.properties`, `createKeyOptions`, and `importKeyOptions` in order to specify whether the key is exportable and to associate a release policy to a given key. -- Added support for automated key rotation in Azure Key Vault and Managed HSM. - - Added `KeyClient.rotateKey` to rotate a key on-demand. - - Added `KeyClient.updateKeyRotationPolicy` to update a key's automated rotation policy. -- Added support for `KeyClient.getCryptographyClient(keyName, options)` which provides a simple way to create a `CryptographyClient` for a given key (identified by its name). - - An optional `keyVersion` property may be used in the `options` parameter to create a cryptography client targeting a specific key version. The latest version is used by default. - -### Other Changes - -- This release updates `KeyClient` and `CryptographyClient` to support service version 7.3 by default. - -## 4.4.0-beta.4 (2022-02-08) - -### Features Added - -- Added `KeyReleasePolicy#immutable` flag to support immutable release policies. Once a release policy is marked as immutable, it can no longer be modified. - -## 4.4.0-beta.3 (2021-11-09) - -### Features Added - -- Support multi-tenant authentication against Key Vault and Managed HSM when using @azure/identity 2.0.0 or newer. - -### Breaking Changes - -- `KeyClient.getRandomBytes` will now return the generated bytes directly instead of wrapping them in a `RandomBytes` model. - - Since it's no longer used, `RandomBytes` has been removed from the public API. -- `KeyReleasePolicy.data` has been renamed to `KeyReleasePolicy.encodedPolicy`. -- `KeyClient.releaseKey`'s `target` parameter has been renamed to `targetAttestationToken`. - -## 4.4.0-beta.2 (2021-10-05) - -### Features Added - -- Added support for `KeyClient.getCryptographyClient(keyName, options)` which provides a simple way to create a `CryptographyClient` for a given key (identified by its name). - - An optional `keyVersion` property may be used in the `options` parameter to create a cryptography client targeting a specific key version. The latest version is used by default. -- Added support for automated key rotation in Azure Key Vault. - - Added `KeyClient.rotateKey` to rotate a key on-demand. - - Added `KeyClient.updateKeyRotationPolicy` to update a key's automated rotation policy. - -## 4.4.0-beta.1 (2021-08-10) - -### Features Added - -- Added support for Secure key Release from a Managed HSM. - - Added `KeyClient.releaseKey` to release a key from a Managed HSM. - - Added `exportable` and `releasePolicy` to `KeyVaultKey.properties`, `createKeyOptions`, and `importKeyOptions` in order to specify whether the key is exportable and the associated release policy. -- Added an overload to `KeyClient.updateKeyProperties` that allows the version to be omitted, updating the latest key version. -- Added support for `KeyClient.getRandomBytes` which, when connected to a managed HSM, can be used to generate a byte array of a given length with random values. -- Updated the service version to 7.3-preview. - -## 4.3.0 (2021-07-29) - -### New Features - -- Support for Node.js 8 and IE 11 has been dropped. Please see our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. -- Changed TS compilation target to ES2017 to produce smaller bundles and use more native platform features. -- Updated our internal core package dependencies to their latest versions to add support for Opentelemetry 1.0.0, which is compatible with the latest versions of our other client libraries. - -## 4.3.0-beta.1 (2021-07-07) - -### Features Added - -- With the dropping of support for Node.js versions that are no longer in LTS, the dependency on `@types/node` has been updated to version 12. Read our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. -- Added support for `KeyClient.getRandomBytes` which, when connected to a managed HSM, can be used to generate a byte array of a given length with random values. -- Updated the service version to 7.3-preview. - -## 4.2.2 (2021-07-07) - -### Key Bugs Fixed - -- Fixed an issue where `CryptographyClient.signData` and `CryptographyClient.verifyData` convenience methods would fail to find a valid hashing algorithm when using Elliptic Curve keys. - -## 4.2.1 (2021-06-15) - -### Bug Fixes - -- Fixed an issue where bundling could fail when importing this library due to an incorrectly set import. - -## 4.2.0 (2021-06-15) - -### New Features - -- Added support for local cryptography operations. If supported by the key type and algorithm, the `CryptographyClient` will attempt to perform a cryptography operation locally. -- Added support for symmetric keys in Managed HSMs including support for AES encryption algorithms to encrypt, decrypt, wrap, and unwrap using symmetric keys. -- Added support for the 7.2 version of the Key Vault service API. - -### Bug Fixes - -- Fixed a bug with `beginDeleteKey` and `beginRecoverDeletedKey` in which unknown service errors wouldn't bubble up properly to the end users. -- Fixed bug with the list operations which were returning misplaced properties. Fixes customer issue: [15353](https://github.com/Azure/azure-sdk-for-js/issues/15353). -- Fixed an issue where retrying a failed initial Key Vault request may result in an empty body. - -### Changes since 4.2.0-beta.5: - -- Removed the now obsolete `KeyOperationsOptions` and replaced it with `CryptographyOptions`. - - Introduced in 4.2.0-beta.1 to support additional encryption parameters for AES encryption, we have since moved these parameters outside of the options bag so a separate `KeyOperationsOptions` is now redundant. -- Fixed a bug with `beginDeleteKey` and `beginRecoverDeletedKey` in which unknown service errors wouldn't bubble up properly to the end users. -- Fixed bug with the list operations which were returning misplaced properties. Fixes customer issue: [15353](https://github.com/Azure/azure-sdk-for-js/issues/15353). -- Exported a method to parse Key Vault Key Ids: `parseKeyVaultKeyIdentifier`. - -## 4.2.0-beta.5 (2021-04-06) - -- Added local cryptography support for encryption / decryption for `A128CBCPAD`, `A192CBCPAD`, and `A256CBCPAD`. -- For AES-CBC encryption we will now generate an IV if the user did not pass it in, making `iv` optional for those parameters. -- Improved tracing across the various KeyVault libraries. By switching to a consistent naming convention, ensuring spans are always closed appropriately, and setting the correct status when an operation errors developers can expect an improved experience when enabling distributed tracing. - - We now ensure tracing spans are properly closed with an appropriate status when an operation throws an exception. - - If a traced operation throws an exception we will now properly record the exception message in the tracing span. - - Finally, naming conventions have been standardized across the KeyVault libraries taking the format of `Azure.KeyVault..`. -- Fixed an issue where retrying a failed initial Key Vault request may result in an empty body. -- [Breaking] Removed the now unused `LocalCryptographyAlgorithmName` type (Added in 4.2.0-beta.1 to support `LocalCryptographyClient` and unused since 4.2.0-beta.4) -- Updated `CryptographyClient` to ensure that any local cryptography error is properly handled. We will now try to perform the operation locally where we can but fallback to KeyVault if the local operation fails. - -## 4.2.0-beta.4 (2021-03-09) - -- Updated the Latest service version to 7.2. -- Added `curve` to `createKeyOptions` to be used when creating an `EC` key. -- Deprecated the current `encrypt` and `decrypt` methods in favor of the more flexible overloads that take an `{Encrypt|Decrypt}Parameters` and allow passing in algorithm specific parameters. This enables support for the various AES algorithms used in Managed HSM. The deprecated methods continue to function and there's no timeline for their removal. -- Added `additionalAuthenticatedData`, `iv`, and `authenticationTag` to `EncryptResult` in order to support AES encryption and decryption. -- Refactored the various cryptography providers and updated the error messages to be clearer and more descriptive. - -## 4.2.0-beta.3 (2021-02-09) - -- [Breaking] Removed `dist-browser` from the published package. To bundle the Azure SDK libraries for the browsers, please read our bundling guide: [link](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/Bundling.md). -- Updated the Key Vault Keys Long Running Operation Pollers to follow a more compact and meaningful approach moving forward. -- Bug fix: The logging of HTTP requests wasn't properly working - now it has been fixed and tests have been written that verify the fix. -- Added a constructor overload to `CryptographyClient` that takes a `JsonWebKey` and allows for local-only subset of operations. -- Added `KeyId` to the public API of CryptographyClient. -- [Breaking] Removed `parseKeyVaultKeysId` from the public API and made `KeyOptionsOptions.additionalAuthenticatedData` a readonly property. -- Added a `createOctKey` convenience method to create a key of type `oct` or `oct-HSM` as appropriate. - -## 4.2.0-beta.2 (2020-10-06) - -- Added the `oct-HSM` type to `KeyType`. -- Added encryption, decryption, wrapping and unwrapping service support for the algorithms "A128GCM", "A192GCM", "A256GCM", "A128KW", "A192KW", "A256KW", "A128CBC", "A192CBC", "A256CBC", "A128CBCPAD", "A192CBCPAD", "A256CBCPAD". -- The encryption, decryption, wrapping and unwrapping operations now support the following optional parameters: - - `additionalAuthenticatedData`, Additional data to authenticate but not encrypt/decrypt when using authenticated cryptography algorithms. - - `iv`, the initialization vector for symmetric algorithms. - - `tag`, the tag to authenticate when performing decryption with an authenticated algorithm. - -## 4.2.0-beta.1 (2020-09-11) - -- Added `parseKeyVaultKeysIdentifier` and `ParsedKeyVaultKeysIdentifier` to help with parsing the unique identifiers of Key Vault Keys. -- Added the basic structure of a new client to perform local cryptography operations, which is now called `LocalCryptographyClient`. - - The existing `CryptographyClient`, when initialized, will create one instance of a local cryptography client, which can be retrieved by calling to a new method that is part of the `CryptographyClient` class: `getLocalCryptographyClient()`. - - The `LocalCryptographyClient` currently has limited support of the cryptography operations available on the `CryptographyClient`. More operations will be added over time. - -## 4.1.0 (2020-08-12) - -4.1.0 had changes both relative to the last GA release, `4.0.4`, and the last preview release, `4.1.0-preview.1`. - -- Added the optional serviceVersion property to the KeyClient and CryptographyClient optional parameters to control the version of the Key Vault service being used by the clients. - - It defaults to the latest supported API version, which currently is 7.1. - - Other supported service version at the moment is 7.0. -- Added import to the list of possible values for KeyOperation. -- Added recoverableDays as an optional property to KeyProperties which denotes the number of days in which the key can be recovered after deletion. This is only applicable for Azure Key Vaults with the soft-delete setting enabled. -- Fixed bug 10352, which caused cryptography operations on RSA-HSM keys to fail. -- Renamed the apiVersion property to the KeyClient constructor as serviceVersion. -- Moved from service version 7.1-preview to 7.1. - -## 4.0.4 (2020-06-01) - -- Fixed [bug 9005](https://github.com/Azure/azure-sdk-for-js/issues/9005), which caused parallel requests to throw if one of them needed to authenticate. - -## 4.0.3 (2020-05-13) - -- Fixed [bug 8378](https://github.com/Azure/azure-sdk-for-js/issues/8378), which caused the challenge based authentication to re-authenticate on every new request. - -## 4.1.0-preview.1 (2020-03-10) - -- Added the optional `apiVersion` property to the `KeyClient` and `CryptographyClient` optional parameters. - It defaults to the latest supported API version, which currently is `7.1-preview`. -- Added `import` to the list of possible values for `KeyOperation`. -- Added `recoverableDays` as an optional property to `KeyProperties`. - -## 4.0.2 (2019-12-03) - -- Updated dependencies to their latest available versions. -- Fixed the support of dotenv while testing. -- Improved the available documentation, and added a README in the test folder. -- KeyClient's vaultUrl property is now public, but readonly. -- Updated to use OpenTelemetry 0.2 via `@azure/core-tracing`. - -## 4.0.0 (2019-10-31) - -- This release marks the general availability of the `@azure/keyvault-keys` package. -- All of the public API methods now have their custom option types. -- All of the option types can now receive a `requestOptions` parameter to customize the options sent to the HTTP client. -- Made the `getKey` method and the `key` property on the `CryptographyClient` private. -- Removed publicly accessible properties that referenced the `pipeline` and the `credential` used during the creation of both the `KeyClient` and the `CryptographyClient`. - -## 4.0.0-preview.9 (2019-10-22) - -- `deleteKey` and `recoverDeletedKey` are now out of the public API. - Use `beginDeleteKey` and `beginRecoverDeletedKey` instead. - They both return a Poller (from our package `@azure/core-lro`) that manages the long running operation. -- Renamed `Key` to `KeyVaultKey`. -- Renamed `Key.KeyMaterial` to `KeyVaultKey.Key`. -- All dates should end in "On", except for `notBefore` and `scheduledPurgedDate`. -- All options should match the method's name. -- All methods that return keyProperties (like the ones that iterate) should contain "propertiesOf" in their names. -- Flattened all the options bag to extend the `RequestOptionsBase` interface. - -## 4.0.0-preview.8 (2019-10-09) - -- Updated to use the latest version of `@azure/core-tracing`, `@azure/identity`, `@azure/core-http` and `@azure/core-arm` packages - -## 4.0.0-preview.7 (2019-10-08) - -- API Changes: - - Nested classes are now flattened into a "properties" property. - - The algorithm used and the original keyID are now available as part of the returned values from the CryptographyClient's encrypt, decrypt, wrapKey, sign, signData, verify and verifyData methods. - -## 4.0.0-preview.5 (2019-09-11) - -- Improved the tests, the README and upgraded dependencies. -- Added the browser folder to the released bundle. - -## 4.0.0-preview.3 (2019-08-06) - -- Added a new CryptographyClient to handle cryptography tasks. -- Added browser support. -- Added support for challenge-based authentication. -- Added preview capabilities for @Azure/core-tracing. - -## 4.0.0-preview.2 (2019-07-03) - -- Fix broken links for API references and samples. -- Update custom user agent string to include the right package name and version. - -## 4.0.0-preview.1 (2019-06-28) - -For release notes and more information please visit -https://aka.ms/azsdk/releases/july2019preview diff --git a/sdk/keyvault/keyvault-keys/LICENSE b/sdk/keyvault/keyvault-keys/LICENSE deleted file mode 100644 index ea8fb1516028..000000000000 --- a/sdk/keyvault/keyvault-keys/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2020 Microsoft - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/sdk/keyvault/keyvault-keys/README.md b/sdk/keyvault/keyvault-keys/README.md deleted file mode 100644 index eff2fb7d6485..000000000000 --- a/sdk/keyvault/keyvault-keys/README.md +++ /dev/null @@ -1,856 +0,0 @@ -# Azure Key Vault Key client library for JavaScript - -Azure Key Vault is a service that allows you to encrypt authentication keys, storage account keys, data encryption keys, .pfx files, and passwords by using secured keys. -If you would like to know more about Azure Key Vault, you may want to review: [What is Azure Key Vault?][keyvault] - -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. If you would like to know more about Azure Key Vault Managed HSM, you may want to review: [What is Azure Key Vault Managed HSM?][managedhsm] - -The Azure Key Vault key library client supports RSA keys, Elliptic Curve (EC) keys, as well as Symmetric (oct) keys when running against a managed HSM, 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. - -Use the client library for Azure Key Vault Keys in your Node.js application to: - -- Create keys using elliptic curve or RSA encryption, optionally backed by Hardware Security Modules (HSM). -- Import, Delete, and Update keys. -- Get one or more keys and deleted keys, with their attributes. -- Recover a deleted key and restore a backed up key. -- Get the versions of a key. - -Using the cryptography client available in this library you also have access to: - -- Encrypting -- Decrypting -- Signing -- Verifying -- Wrapping keys -- Unwrapping keys - -> Note: This package cannot be used in the browser due to Azure Key Vault service limitations, please refer to [this document][cors] for guidance. - -Key links: - -- [Source code][package-gh] -- [Package (npm)][package-npm] -- [API Reference Documentation][docs] -- [Product documentation][docs-service] -- [Samples][samples] - -## Getting started - -### Currently supported environments - -- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) - -### Prerequisites - -- An [Azure subscription](https://azure.microsoft.com/free/) -- An existing [Azure Key Vault][azure_keyvault]. If you need to create a key vault, you can do so in the Azure Portal by following the steps in [this document][azure_keyvault_portal]. Alternatively, use the Azure CLI by following [these steps][azure_keyvault_cli]. -- If using Managed HSM, an existing [Azure Key Vault Managed HSM][azure_keyvault_mhsm]. If you need to create a Managed HSM, you can do so using the Azure CLI by following the steps in [this document][azure_keyvault_mhsm_cli]. - -### Install the package - -Install the Azure Key Vault Key client library using npm - -`npm install @azure/keyvault-keys` - -### Install the identity library - -Azure Key Vault clients authenticate using the Azure identity library. Install it as well using npm - -`npm install @azure/identity` - -### Configure TypeScript - -TypeScript users need to have Node type definitions installed: - -```bash -npm install @types/node -``` - -You also need to enable `compilerOptions.allowSyntheticDefaultImports` in your tsconfig.json. Note that if you have enabled `compilerOptions.esModuleInterop`, `allowSyntheticDefaultImports` is enabled by default. See [TypeScript's compiler options handbook][tscompileroptions] for more information. - -## Key concepts - -- The **Key client** is the primary interface to interact with the API methods - related to keys in the Azure Key Vault API from a JavaScript application. - Once initialized, it provides a basic set of methods that can be used to - create, read, update and delete keys. -- A **Key version** is a version of a key in the Key Vault. - Each time a user assigns a value to a unique key name, a new **version** - of that key is created. Retrieving a key by a name will always return - the latest value assigned, unless a specific version is provided to the - query. -- **Soft delete** allows Key Vaults to support deletion and purging as two - separate steps, so deleted keys are not immediately lost. This only happens if the Key Vault - has [soft-delete][softdelete] - enabled. -- A **Key backup** can be generated from any created key. These backups come as - binary data, and can only be used to regenerate a previously deleted key. -- The **Cryptography client** is a separate interface that interacts with the - keys API methods in the Key Vault API. This client focuses only in the - cryptography operations that can be executed using a key that has been - already created in the Key Vault. More about this client in the - [Cryptography](#cryptography) section. - -## Authenticating with Azure Active Directory - -The Key Vault service relies on Azure Active Directory to authenticate requests to its APIs. The [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) package provides a variety of credential types that your application can use to do this. The [README for `@azure/identity`](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity/README.md) provides more details and samples to get you started. - -In order to interact with the Azure Key Vault service, you will need to create an instance of the `KeyClient` class, a **vault url** and a credential object. The examples shown in this document use a credential object named [`DefaultAzureCredential`][default_azure_credential], which is appropriate for most scenarios, including local development and production environments. Additionally, we recommend using a [managed identity][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][azure_identity]. - -Here's a quick example. First, import `DefaultAzureCredential` and `KeyClient`: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); -``` - -Once these are imported, we can next connect to the Key Vault service: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -// Build the URL to reach your key vault -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; // or `https://${vaultName}.managedhsm.azure.net` for managed HSM. - -// Lastly, create our keys client and connect to the service -const client = new KeyClient(url, credential); -``` - -## Specifying the Azure Key Vault service API version - -By default, this package uses the latest Azure Key Vault service version which is `7.2`. You can change the service version being used by setting the option `serviceVersion` in the client constructor as shown below: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -// Change the Azure Key Vault service API version being used via the `serviceVersion` option -const client = new KeyClient(url, credential, { - serviceVersion: "7.0", // Or 7.1 -}); -``` - -## Examples - -The following sections provide code snippets that cover some of the common -tasks using Azure Key Vault Keys. The scenarios that are covered here consist of: - -- [Creating a key](#creating-a-key). -- [Getting a key](#getting-a-key). -- [Creating and updating keys with attributes](#creating-and-updating-keys-with-attributes). -- [Deleting a key](#deleting-a-key). -- [Iterating lists of keys](#iterating-lists-of-keys). - -### Creating a key - -`createKey` creates a 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. - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const result = await client.createKey(keyName, "RSA"); - console.log("result: ", result); -} - -main(); -``` - -The second parameter sent to `createKey` is the type of the key. The type of keys that are supported will depend on the SKU and whether you are using an Azure Key Vault or an Azure Managed HSM. For an up-to-date list of supported key types please refer to [About keys][aboutkeys] - -### Getting a key - -The simplest way to read keys back from the vault is to get a key by name. This -will retrieve the most recent version of the key. You can optionally get a -different version of the key if you specify it as part of the optional -parameters. - -`getKey` retrieves a key previous stores in the Key Vault. - -```typescript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const latestKey = await client.getKey(keyName); - console.log(`Latest version of the key ${keyName}: `, latestKey); - const specificKey = await client.getKey(keyName, { version: latestKey.properties.version! }); - console.log(`The key ${keyName} at the version ${latestKey.properties.version!}: `, specificKey); -} - -main(); -``` - -### Creating and updating keys with attributes - -The following attributes can also be assigned to any key in a Key Vault: - -- `tags`: Any set of key-values that can be used to search and filter keys. -- `keyOps`: An array of the operations that this key will be able to perform (`encrypt`, `decrypt`, `sign`, `verify`, `wrapKey`, `unwrapKey`). -- `enabled`: A boolean value that determines whether the key value can be read or not. -- `notBefore`: A given date after which the key value can be retrieved. -- `expires`: A given date after which the key value cannot be retrieved. - -An object with these attributes can be sent as the third parameter of -`createKey`, right after the key's name and value, as follows: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const result = await client.createKey(keyName, "RSA", { - enabled: false, - }); - console.log("result: ", result); -} - -main(); -``` - -This will create a new version of the same key, which will have the latest -provided attributes. - -Attributes can also be updated to an existing key version with -`updateKeyProperties`, as follows: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const result = await client.createKey(keyName, "RSA"); - await client.updateKeyProperties(keyName, result.properties.version, { - enabled: false, - }); -} - -main(); -``` - -### Deleting a key - -The `beginDeleteKey` method starts the deletion of a key. -This process will happen in the background as soon as the necessary resources -are available. - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const poller = await client.beginDeleteKey(keyName); - await poller.pollUntilDone(); -} - -main(); -``` - -If [soft-delete][softdelete] -is enabled for the Key Vault, this operation will only label the key as a -_deleted_ key. A deleted key can't be updated. They can only be -read, recovered or purged. - -```typescript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const poller = await client.beginDeleteKey(keyName); - - // You can use the deleted key immediately: - const deletedKey = poller.getResult(); - - // The key is being deleted. Only wait for it if you want to restore it or purge it. - await poller.pollUntilDone(); - - // You can also get the deleted key this way: - await client.getDeletedKey(keyName); - - // Deleted keys can also be recovered or purged: - - // recoverDeletedKey also returns a poller, just like beginDeleteKey. - const recoverPoller = await client.beginRecoverDeletedKey(keyName); - await recoverPoller.pollUntilDone(); - - // And here is how to purge a deleted key - await client.purgeDeletedKey(keyName); -} - -main(); -``` - -Since Keys take some time to get fully deleted, `beginDeleteKey` -returns a Poller object that keeps track of the underlying Long Running -Operation according to our guidelines: -https://azure.github.io/azure-sdk/typescript_design.html#ts-lro - -The received poller will allow you to get the deleted key by calling to `poller.getResult()`. -You can also wait until the deletion finishes either by running individual service -calls until the key is deleted, or by waiting until the process is done: - -```typescript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const poller = await client.beginDeleteKey(keyName); - - // You can use the deleted key immediately: - let deletedKey = poller.getResult(); - - // Or you can wait until the key finishes being deleted: - deletedKey = await poller.pollUntilDone(); - console.log(deletedKey); -} - -main(); -``` - -Another way to wait until the key is fully deleted is to do individual calls, as follows: - -```typescript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); -const { delay } = require("@azure/core-util"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - const poller = await client.beginDeleteKey(keyName); - - while (!poller.isDone()) { - await poller.poll(); - await delay(5000); - } - - console.log(`The key ${keyName} is fully deleted`); -} - -main(); -``` - -### Configuring Automatic Key Rotation - -Using the KeyClient, you can configure automatic key rotation for a key by specifying the rotation policy. -In addition, KeyClient provides a method to rotate a key on-demand by creating a new version of the given key. - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const url = `https://.vault.azure.net`; -const client = new KeyClient(url, new DefaultAzureCredential()); - -async function main() { - const keyName = "MyKeyName"; - - // Set the key's automated rotation policy to rotate the key 30 days before expiry. - const policy = await client.updateKeyRotationPolicy(keyName, { - lifetimeActions: [ - { - action: "Rotate", - timeBeforeExpiry: "P30D", - }, - ], - // You may also specify the duration after which any newly rotated key will expire. - // In this case, any new key versions will expire after 90 days. - expiresIn: "P90D", - }); - - // You can get the current key rotation policy of a given key by calling the getKeyRotationPolicy method. - const currentPolicy = await client.getKeyRotationPolicy(keyName); - - // Finally, you can rotate a key on-demand by creating a new version of the given key. - const rotatedKey = await client.rotateKey(keyName); -} - -main(); -``` - -### Iterating lists of keys - -Using the KeyClient, you can retrieve and iterate through all of the -keys in an Azure Key Vault, as well as through all of the deleted keys and the -versions of a specific key. The following API methods are available: - -- `listPropertiesOfKeys` will list all of your non-deleted keys by their names, only - at their latest versions. -- `listDeletedKeys` will list all of your deleted keys by their names, - only at their latest versions. -- `listPropertiesOfKeyVersions` will list all the versions of a key based on a key - name. - -Which can be used as follows: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - for await (let keyProperties of client.listPropertiesOfKeys()) { - console.log("Key properties: ", keyProperties); - } - for await (let deletedKey of client.listDeletedKeys()) { - console.log("Deleted: ", deletedKey); - } - for await (let versionProperties of client.listPropertiesOfKeyVersions(keyName)) { - console.log("Version properties: ", versionProperties); - } -} - -main(); -``` - -All of these methods will return **all of the available results** at once. To -retrieve them by pages, add `.byPage()` right after invoking the API method you -want to use, as follows: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyClient } = require("@azure/keyvault-keys"); - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const client = new KeyClient(url, credential); - -const keyName = "MyKeyName"; - -async function main() { - for await (let page of client.listPropertiesOfKeys().byPage()) { - for (let keyProperties of page) { - console.log("Key properties: ", keyProperties); - } - } - for await (let page of client.listDeletedKeys().byPage()) { - for (let deletedKey of page) { - console.log("Deleted key: ", deletedKey); - } - } - for await (let page of client.listPropertiesOfKeyVersions(keyName).byPage()) { - for (let versionProperties of page) { - console.log("Version: ", versionProperties); - } - } -} - -main(); -``` - -## Cryptography - -This library also offers a set of cryptographic utilities available through -`CryptographyClient`. Similar to the `KeyClient`, `CryptographyClient` will -connect to Azure Key Vault with the provided set of credentials. Once -connected, `CryptographyClient` can encrypt, decrypt, sign, verify, wrap keys, -and unwrap keys. - -We can next connect to the key vault service just as we do with the `KeyClient`. -We'll need to copy some settings from the key vault we are -connecting to into our environment variables. Once they are in our environment, -we can access them with the following code: - -```typescript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - // Create or retrieve a key from the keyvault - let myKey = await keysClient.createKey("MyKey", "RSA"); - - // Lastly, create our cryptography client and connect to the service - const cryptographyClient = new CryptographyClient(myKey, credential); -} - -main(); -``` - -### Encrypt - -`encrypt` will encrypt a message. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey.id, credential); - - const encryptResult = await cryptographyClient.encrypt({ - algorithm: "RSA1_5", - plaintext: Buffer.from("My Message"), - }); - console.log("encrypt result: ", encryptResult.result); -} - -main(); -``` - -### Decrypt - -`decrypt` will decrypt an encrypted message. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey.id, credential); - - const encryptResult = await cryptographyClient.encrypt({ - algorithm: "RSA1_5", - plaintext: Buffer.from("My Message"), - }); - console.log("encrypt result: ", encryptResult.result); - - const decryptResult = await cryptographyClient.decrypt({ - algorithm: "RSA1_5", - ciphertext: encryptResult.result, - }); - console.log("decrypt result: ", decryptResult.result.toString()); -} - -main(); -``` - -### Sign - -`sign` will cryptographically sign the digest (hash) of a message with a signature. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; -import { createHash } from "crypto"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey, credential); - - const signatureValue = "MySignature"; - let hash = createHash("sha256"); - - let digest = hash.update(signatureValue).digest(); - console.log("digest: ", digest); - - const signResult = await cryptographyClient.sign("RS256", digest); - console.log("sign result: ", signResult.result); -} - -main(); -``` - -### Sign Data - -`signData` will cryptographically sign a message with a signature. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey, credential); - - const signResult = await cryptographyClient.signData("RS256", Buffer.from("My Message")); - console.log("sign result: ", signResult.result); -} - -main(); -``` - -### Verify - -`verify` will cryptographically verify that the signed digest was signed with the given signature. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; -import { createHash } from "crypto"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey, credential); - - const hash = createHash("sha256"); - hash.update("My Message"); - const digest = hash.digest(); - - const signResult = await cryptographyClient.sign("RS256", digest); - console.log("sign result: ", signResult.result); - - const verifyResult = await cryptographyClient.verify("RS256", digest, signResult.result); - console.log("verify result: ", verifyResult.result); -} - -main(); -``` - -### Verify Data - -`verifyData` will cryptographically verify that the signed message was signed with the given signature. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey, credential); - - const buffer = Buffer.from("My Message"); - - const signResult = await cryptographyClient.signData("RS256", buffer); - console.log("sign result: ", signResult.result); - - const verifyResult = await cryptographyClient.verifyData("RS256", buffer, signResult.result); - console.log("verify result: ", verifyResult.result); -} - -main(); -``` - -### Wrap Key - -`wrapKey` will wrap a key with an encryption layer. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey, credential); - - const wrapResult = await cryptographyClient.wrapKey("RSA-OAEP", Buffer.from("My Key")); - console.log("wrap result:", wrapResult.result); -} - -main(); -``` - -### Unwrap Key - -`unwrapKey` will unwrap a wrapped key. - -```javascript -import { DefaultAzureCredential } from "@azure/identity"; -import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - -const credential = new DefaultAzureCredential(); - -const vaultName = ""; -const url = `https://${vaultName}.vault.azure.net`; - -const keysClient = new KeyClient(url, credential); - -async function main() { - let myKey = await keysClient.createKey("MyKey", "RSA"); - const cryptographyClient = new CryptographyClient(myKey, credential); - - const wrapResult = await cryptographyClient.wrapKey("RSA-OAEP", Buffer.from("My Key")); - console.log("wrap result:", wrapResult.result); - - const unwrapResult = await cryptographyClient.unwrapKey("RSA-OAEP", wrapResult.result); - console.log("unwrap result: ", unwrapResult.result); -} - -main(); -``` - -## Troubleshooting - -See our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/TROUBLESHOOTING.md) for details on how to diagnose various failure scenarios. - -Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`: - -```javascript -const { setLogLevel } = require("@azure/logger"); - -setLogLevel("info"); -``` - -## Next steps - -You can find more code samples through the following links: - -- [Key Vault Keys Samples (JavaScript)](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/javascript) -- [Key Vault Keys Samples (TypeScript)](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/typescript) -- [Key Vault Keys Test Cases](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/test/) - -## Contributing - -If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. - -[aboutkeys]: https://learn.microsoft.com/azure/key-vault/keys/about-keys -[keyvault]: https://learn.microsoft.com/azure/key-vault/key-vault-overview -[managedhsm]: https://learn.microsoft.com/azure/key-vault/managed-hsm/overview -[cors]: https://github.com/Azure/azure-sdk-for-js/blob/main/samples/cors/ts/README.md -[package-gh]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-keys -[package-npm]: https://www.npmjs.com/package/@azure/keyvault-keys -[docs]: https://learn.microsoft.com/javascript/api/@azure/keyvault-keys -[docs-service]: https://azure.microsoft.com/services/key-vault/ -[samples]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples -[tscompileroptions]: https://www.typescriptlang.org/docs/handbook/compiler-options.html -[softdelete]: https://learn.microsoft.com/azure/key-vault/key-vault-ovw-soft-delete -[azure_keyvault]: https://learn.microsoft.com/azure/key-vault/general/overview -[azure_keyvault_cli]: https://learn.microsoft.com/azure/key-vault/general/quick-create-cli -[azure_keyvault_portal]: https://learn.microsoft.com/azure/key-vault/general/quick-create-portal -[azure_keyvault_mhsm]: https://learn.microsoft.com/azure/key-vault/managed-hsm/overview -[azure_keyvault_mhsm_cli]: https://learn.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli -[default_azure_credential]: https://learn.microsoft.com/javascript/api/@azure/identity/defaultazurecredential?view=azure-node-latest -[managed_identity]: https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview -[azure_identity]: https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fkeyvault%2Fkeyvault-keys%2FREADME.png) diff --git a/sdk/keyvault/keyvault-keys/TROUBLESHOOTING.md b/sdk/keyvault/keyvault-keys/TROUBLESHOOTING.md deleted file mode 100644 index dd208e03e9da..000000000000 --- a/sdk/keyvault/keyvault-keys/TROUBLESHOOTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# Troubleshooting Azure Key Vault Keys SDK Issues - -See our [Azure Key Vault SDK Troubleshooting Guide](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/TROUBLESHOOTING.md) to troubleshoot issues common to the Azure Key Vault SDKs for JavaScript. diff --git a/sdk/keyvault/keyvault-keys/api-extractor.json b/sdk/keyvault/keyvault-keys/api-extractor.json deleted file mode 100644 index 4ff72306672e..000000000000 --- a/sdk/keyvault/keyvault-keys/api-extractor.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", - "mainEntryPointFilePath": "dist/esm/index.d.ts", - "docModel": { - "enabled": true - }, - "apiReport": { - "enabled": true, - "reportFolder": "./review" - }, - "dtsRollup": { - "enabled": true, - "untrimmedFilePath": "", - "publicTrimmedFilePath": "dist/keyvault-keys.d.ts" - }, - "messages": { - "tsdocMessageReporting": { - "default": { - "logLevel": "none" - } - }, - "extractorMessageReporting": { - "ae-missing-release-tag": { - "logLevel": "none" - }, - "ae-unresolved-link": { - "logLevel": "none" - } - } - } -} diff --git a/sdk/keyvault/keyvault-keys/assets.json b/sdk/keyvault/keyvault-keys/assets.json deleted file mode 100644 index 7de955e29bf2..000000000000 --- a/sdk/keyvault/keyvault-keys/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "js", - "TagPrefix": "js/keyvault/keyvault-keys", - "Tag": "js/keyvault/keyvault-keys_30697cfd84" -} diff --git a/sdk/keyvault/keyvault-keys/package.json b/sdk/keyvault/keyvault-keys/package.json deleted file mode 100644 index 856c1f48e3ea..000000000000 --- a/sdk/keyvault/keyvault-keys/package.json +++ /dev/null @@ -1,152 +0,0 @@ -{ - "name": "@azure/keyvault-keys", - "sdk-type": "client", - "author": "Microsoft Corporation", - "version": "4.9.1", - "license": "MIT", - "description": "Isomorphic client library for Azure KeyVault's keys.", - "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/README.md", - "repository": "github:Azure/azure-sdk-for-js", - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault" - ], - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "main": "./dist/commonjs/index.js", - "module": "./dist/esm/index.js", - "types": "./dist/commonjs/index.d.ts", - "engines": { - "node": ">=18.0.0" - }, - "files": [ - "dist/", - "README.md", - "LICENSE" - ], - "browser": "./dist/browser/index.js", - "scripts": { - "build": "npm run clean && dev-tool run build-package && dev-tool run extract-api", - "build:samples": "echo Obsolete.", - "build:test": "npm run clean && dev-tool run build-package", - "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", - "clean": "dev-tool run vendored rimraf --glob dist dist-* types *.tgz *.log dist-browser statistics.html coverage && dev-tool run vendored rimraf --glob src/**/*.js && dev-tool run vendored rimraf --glob test/**/*.js", - "execute:samples": "dev-tool samples run samples-dev", - "extract-api": "dev-tool run build-package && dev-tool run extract-api", - "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", - "generate:client": "autorest --typescript swagger/README.md", - "integration-test": "npm run integration-test:node && npm run integration-test:browser", - "integration-test:browser": "echo skipped", - "integration-test:node": "dev-tool run test:vitest --no-test-proxy --esm -- --test-timeout 5000000 --hook-timeout 100000", - "lint": "eslint package.json api-extractor.json src test", - "lint:fix": "eslint package.json api-extractor.json src test --fix --fix-type [problem,suggestion]", - "pack": "npm pack 2>&1", - "test": "npm run clean && npm run build:test && npm run unit-test", - "test:browser": "echo skipped", - "test:node": "npm run clean && npm run build:test && npm run unit-test:node", - "unit-test": "npm run unit-test:node && npm run unit-test:browser", - "unit-test:browser": "echo skipped", - "unit-test:node": "dev-tool run test:vitest -- --test-timeout 100000 --hook-timeout 100000", - "update-snippets": "echo skipped" - }, - "sideEffects": false, - "//metadata": { - "constantPaths": [ - { - "path": "src/generated/keyVaultClient.ts", - "prefix": "packageDetails" - }, - { - "path": "src/constants.ts", - "prefix": "SDK_VERSION" - }, - { - "path": "swagger/README.md", - "prefix": "package-version" - } - ] - }, - "//sampleConfiguration": { - "productName": "Azure Key Vault Keys", - "productSlugs": [ - "azure", - "azure-key-vault" - ], - "requiredResources": { - "Azure Key Vault": "https://learn.microsoft.com/azure/key-vault/quick-create-portal" - }, - "customSnippets": { - "prerequisites": "samples-dev/snippets/_prerequisites.md" - } - }, - "dependencies": { - "@azure-rest/core-client": "^2.0.0", - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.3.0", - "@azure/core-http-compat": "^2.0.1", - "@azure/core-lro": "^2.2.0", - "@azure/core-paging": "^1.1.1", - "@azure/core-rest-pipeline": "^1.8.1", - "@azure/core-tracing": "^1.0.0", - "@azure/core-util": "^1.0.0", - "@azure/keyvault-common": "^2.0.0", - "@azure/logger": "^1.0.0", - "tslib": "^2.2.0" - }, - "devDependencies": { - "@azure-tools/test-credential": "^2.0.0", - "@azure-tools/test-recorder": "^4.1.0", - "@azure-tools/test-utils-vitest": "^1.0.0", - "@azure/dev-tool": "^1.0.0", - "@azure/eslint-plugin-azure-sdk": "^3.0.0", - "@azure/identity": "^4.4.1", - "@types/node": "^18.0.0", - "@vitest/browser": "^3.0.3", - "@vitest/coverage-istanbul": "^3.0.3", - "dayjs": "^1.10.7", - "dotenv": "^16.0.0", - "eslint": "^9.9.0", - "playwright": "^1.47.2", - "typescript": "~5.7.2", - "vitest": "^3.0.3" - }, - "type": "module", - "tshy": { - "exports": { - "./package.json": "./package.json", - ".": "./src/index.ts" - }, - "dialects": [ - "esm", - "commonjs" - ], - "esmDialects": [ - "browser" - ], - "selfLink": false, - "project": "./tsconfig.src.json" - }, - "exports": { - "./package.json": "./package.json", - ".": { - "browser": { - "types": "./dist/browser/index.d.ts", - "default": "./dist/browser/index.js" - }, - "import": { - "types": "./dist/esm/index.d.ts", - "default": "./dist/esm/index.js" - }, - "require": { - "types": "./dist/commonjs/index.d.ts", - "default": "./dist/commonjs/index.js" - } - } - } -} diff --git a/sdk/keyvault/keyvault-keys/platform-matrix.json b/sdk/keyvault/keyvault-keys/platform-matrix.json deleted file mode 100644 index e42088658e6f..000000000000 --- a/sdk/keyvault/keyvault-keys/platform-matrix.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "include": [ - { - "Agent": { - "ubuntu-20.04_ManagedHSM": { - "OSVmImage": "env:LINUXVMIMAGE", - "Pool": "env:LINUXPOOL", - "ArmTemplateParameters": "@{ enableHsm = $true }" - } - }, - "TestType": "node", - "NodeTestVersion": "18.x" - } - ] -} diff --git a/sdk/keyvault/keyvault-keys/review/keyvault-keys.api.md b/sdk/keyvault/keyvault-keys/review/keyvault-keys.api.md deleted file mode 100644 index 2c6d42e9faa5..000000000000 --- a/sdk/keyvault/keyvault-keys/review/keyvault-keys.api.md +++ /dev/null @@ -1,569 +0,0 @@ -## API Report File for "@azure/keyvault-keys" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts - -import { AzureLogger } from '@azure/logger'; -import type * as coreClient from '@azure-rest/core-client'; -import type { ExtendedCommonClientOptions } from '@azure/core-http-compat'; -import { PagedAsyncIterableIterator } from '@azure/core-paging'; -import { PageSettings } from '@azure/core-paging'; -import { PollerLike } from '@azure/core-lro'; -import { PollOperationState } from '@azure/core-lro'; -import type { TokenCredential } from '@azure/core-auth'; - -// @public -export interface AesCbcDecryptParameters { - algorithm: AesCbcEncryptionAlgorithm; - ciphertext: Uint8Array; - iv: Uint8Array; -} - -// @public -export type AesCbcEncryptionAlgorithm = "A128CBC" | "A192CBC" | "A256CBC" | "A128CBCPAD" | "A192CBCPAD" | "A256CBCPAD"; - -// @public -export interface AesCbcEncryptParameters { - algorithm: AesCbcEncryptionAlgorithm; - iv?: Uint8Array; - plaintext: Uint8Array; -} - -// @public -export interface AesGcmDecryptParameters { - additionalAuthenticatedData?: Uint8Array; - algorithm: AesGcmEncryptionAlgorithm; - authenticationTag: Uint8Array; - ciphertext: Uint8Array; - iv: Uint8Array; -} - -// @public -export type AesGcmEncryptionAlgorithm = "A128GCM" | "A192GCM" | "A256GCM"; - -// @public -export interface AesGcmEncryptParameters { - additionalAuthenticatedData?: Uint8Array; - algorithm: AesGcmEncryptionAlgorithm; - plaintext: Uint8Array; -} - -// @public -export interface BackupKeyOptions extends coreClient.OperationOptions { -} - -// @public -export interface BeginDeleteKeyOptions extends KeyPollerOptions { -} - -// @public -export interface BeginRecoverDeletedKeyOptions extends KeyPollerOptions { -} - -// @public -export interface CreateEcKeyOptions extends CreateKeyOptions { -} - -// @public -export interface CreateKeyOptions extends coreClient.OperationOptions { - curve?: KeyCurveName; - enabled?: boolean; - readonly expiresOn?: Date; - exportable?: boolean; - hsm?: boolean; - keyOps?: KeyOperation[]; - keySize?: number; - notBefore?: Date; - releasePolicy?: KeyReleasePolicy; - tags?: { - [propertyName: string]: string; - }; -} - -// @public -export interface CreateOctKeyOptions extends CreateKeyOptions { -} - -// @public -export interface CreateRsaKeyOptions extends CreateKeyOptions { - publicExponent?: number; -} - -// @public -export class CryptographyClient { - constructor(key: string | KeyVaultKey, credential: TokenCredential, pipelineOptions?: CryptographyClientOptions); - constructor(key: JsonWebKey_2); - decrypt(decryptParameters: DecryptParameters, options?: DecryptOptions): Promise; - // @deprecated - decrypt(algorithm: EncryptionAlgorithm, ciphertext: Uint8Array, options?: DecryptOptions): Promise; - encrypt(encryptParameters: EncryptParameters, options?: EncryptOptions): Promise; - // @deprecated - encrypt(algorithm: EncryptionAlgorithm, plaintext: Uint8Array, options?: EncryptOptions): Promise; - get keyID(): string | undefined; - sign(algorithm: SignatureAlgorithm, digest: Uint8Array, options?: SignOptions): Promise; - signData(algorithm: SignatureAlgorithm, data: Uint8Array, options?: SignOptions): Promise; - unwrapKey(algorithm: KeyWrapAlgorithm, encryptedKey: Uint8Array, options?: UnwrapKeyOptions): Promise; - get vaultUrl(): string; - verify(algorithm: SignatureAlgorithm, digest: Uint8Array, signature: Uint8Array, options?: VerifyOptions): Promise; - verifyData(algorithm: SignatureAlgorithm, data: Uint8Array, signature: Uint8Array, options?: VerifyOptions): Promise; - wrapKey(algorithm: KeyWrapAlgorithm, key: Uint8Array, options?: WrapKeyOptions): Promise; -} - -// @public -export interface CryptographyClientOptions extends KeyClientOptions { -} - -// @public -export interface CryptographyOptions extends coreClient.OperationOptions { -} - -// @public -export interface DecryptOptions extends CryptographyOptions { -} - -// @public -export type DecryptParameters = RsaDecryptParameters | AesGcmDecryptParameters | AesCbcDecryptParameters; - -// @public -export interface DecryptResult { - algorithm: EncryptionAlgorithm; - keyID?: string; - result: Uint8Array; -} - -// @public -export interface DeletedKey { - id?: string; - key?: JsonWebKey_2; - keyOperations?: KeyOperation[]; - keyType?: KeyType_2; - name: string; - properties: KeyProperties & { - readonly recoveryId?: string; - readonly scheduledPurgeDate?: Date; - deletedOn?: Date; - }; -} - -// @public -export type DeletionRecoveryLevel = string; - -// @public -export type EncryptionAlgorithm = string; - -// @public -export interface EncryptOptions extends CryptographyOptions { -} - -// @public -export type EncryptParameters = RsaEncryptParameters | AesGcmEncryptParameters | AesCbcEncryptParameters; - -// @public -export interface EncryptResult { - additionalAuthenticatedData?: Uint8Array; - algorithm: EncryptionAlgorithm; - authenticationTag?: Uint8Array; - iv?: Uint8Array; - keyID?: string; - result: Uint8Array; -} - -// @public -export interface GetCryptographyClientOptions { - keyVersion?: string; -} - -// @public -export interface GetDeletedKeyOptions extends coreClient.OperationOptions { -} - -// @public -export interface GetKeyOptions extends coreClient.OperationOptions { - version?: string; -} - -// @public -export interface GetKeyRotationPolicyOptions extends coreClient.OperationOptions { -} - -// @public -export interface GetRandomBytesOptions extends coreClient.OperationOptions { -} - -// @public -export interface ImportKeyOptions extends coreClient.OperationOptions { - enabled?: boolean; - expiresOn?: Date; - exportable?: boolean; - hardwareProtected?: boolean; - notBefore?: Date; - releasePolicy?: KeyReleasePolicy; - tags?: { - [propertyName: string]: string; - }; -} - -// @public -interface JsonWebKey_2 { - crv?: KeyCurveName; - d?: Uint8Array; - dp?: Uint8Array; - dq?: Uint8Array; - e?: Uint8Array; - k?: Uint8Array; - keyOps?: KeyOperation[]; - kid?: string; - kty?: KeyType_2; - n?: Uint8Array; - p?: Uint8Array; - q?: Uint8Array; - qi?: Uint8Array; - t?: Uint8Array; - x?: Uint8Array; - y?: Uint8Array; -} -export { JsonWebKey_2 as JsonWebKey } - -// @public -export class KeyClient { - constructor(vaultUrl: string, credential: TokenCredential, pipelineOptions?: KeyClientOptions); - backupKey(name: string, options?: BackupKeyOptions): Promise; - beginDeleteKey(name: string, options?: BeginDeleteKeyOptions): Promise, DeletedKey>>; - beginRecoverDeletedKey(name: string, options?: BeginRecoverDeletedKeyOptions): Promise, DeletedKey>>; - createEcKey(name: string, options?: CreateEcKeyOptions): Promise; - createKey(name: string, keyType: KeyType_2, options?: CreateKeyOptions): Promise; - createOctKey(name: string, options?: CreateOctKeyOptions): Promise; - createRsaKey(name: string, options?: CreateRsaKeyOptions): Promise; - getCryptographyClient(keyName: string, options?: GetCryptographyClientOptions): CryptographyClient; - getDeletedKey(name: string, options?: GetDeletedKeyOptions): Promise; - getKey(name: string, options?: GetKeyOptions): Promise; - getKeyRotationPolicy(keyName: string, options?: GetKeyRotationPolicyOptions): Promise; - getRandomBytes(count: number, options?: GetRandomBytesOptions): Promise; - importKey(name: string, key: JsonWebKey_2, options?: ImportKeyOptions): Promise; - listDeletedKeys(options?: ListDeletedKeysOptions): PagedAsyncIterableIterator; - listPropertiesOfKeys(options?: ListPropertiesOfKeysOptions): PagedAsyncIterableIterator; - listPropertiesOfKeyVersions(name: string, options?: ListPropertiesOfKeyVersionsOptions): PagedAsyncIterableIterator; - purgeDeletedKey(name: string, options?: PurgeDeletedKeyOptions): Promise; - releaseKey(name: string, targetAttestationToken: string, options?: ReleaseKeyOptions): Promise; - restoreKeyBackup(backup: Uint8Array, options?: RestoreKeyBackupOptions): Promise; - rotateKey(name: string, options?: RotateKeyOptions): Promise; - updateKeyProperties(name: string, keyVersion: string, options?: UpdateKeyPropertiesOptions): Promise; - updateKeyProperties(name: string, options?: UpdateKeyPropertiesOptions): Promise; - updateKeyRotationPolicy(keyName: string, policy: KeyRotationPolicyProperties, options?: UpdateKeyRotationPolicyOptions): Promise; - readonly vaultUrl: string; -} - -// @public -export interface KeyClientOptions extends ExtendedCommonClientOptions { - disableChallengeResourceVerification?: boolean; - serviceVersion?: string; -} - -// @public -export type KeyCurveName = string; - -// @public -export type KeyExportEncryptionAlgorithm = string; - -// @public -export type KeyOperation = string; - -// @public -export interface KeyPollerOptions extends coreClient.OperationOptions { - intervalInMs?: number; - resumeFrom?: string; -} - -// @public -export interface KeyProperties { - readonly createdOn?: Date; - enabled?: boolean; - expiresOn?: Date; - exportable?: boolean; - readonly hsmPlatform?: string; - id?: string; - readonly managed?: boolean; - name: string; - notBefore?: Date; - recoverableDays?: number; - readonly recoveryLevel?: DeletionRecoveryLevel; - releasePolicy?: KeyReleasePolicy; - tags?: { - [propertyName: string]: string; - }; - readonly updatedOn?: Date; - vaultUrl: string; - version?: string; -} - -// @public -export interface KeyReleasePolicy { - contentType?: string; - encodedPolicy?: Uint8Array; - immutable?: boolean; -} - -// @public -export interface KeyRotationLifetimeAction { - action: KeyRotationPolicyAction; - timeAfterCreate?: string; - timeBeforeExpiry?: string; -} - -// @public -export interface KeyRotationPolicy extends KeyRotationPolicyProperties { - readonly createdOn?: Date; - readonly id?: string; - readonly updatedOn?: Date; -} - -// @public -export type KeyRotationPolicyAction = "Rotate" | "Notify"; - -// @public -export interface KeyRotationPolicyProperties { - expiresIn?: string; - lifetimeActions?: KeyRotationLifetimeAction[]; -} - -// @public -type KeyType_2 = string; -export { KeyType_2 as KeyType } - -// @public -export interface KeyVaultKey { - id?: string; - key?: JsonWebKey_2; - keyOperations?: KeyOperation[]; - keyType?: KeyType_2; - name: string; - properties: KeyProperties; -} - -// @public -export interface KeyVaultKeyIdentifier { - name: string; - sourceId: string; - vaultUrl: string; - version?: string; -} - -// @public -export type KeyWrapAlgorithm = "A128KW" | "A192KW" | "A256KW" | "RSA-OAEP" | "RSA-OAEP-256" | "RSA1_5"; - -// @public -export enum KnownDeletionRecoveryLevel { - CustomizedRecoverable = "CustomizedRecoverable", - CustomizedRecoverableProtectedSubscription = "CustomizedRecoverable+ProtectedSubscription", - CustomizedRecoverablePurgeable = "CustomizedRecoverable+Purgeable", - Purgeable = "Purgeable", - Recoverable = "Recoverable", - RecoverableProtectedSubscription = "Recoverable+ProtectedSubscription", - RecoverablePurgeable = "Recoverable+Purgeable" -} - -// @public -export enum KnownEncryptionAlgorithms { - A128CBC = "A128CBC", - A128Cbcpad = "A128CBCPAD", - A128GCM = "A128GCM", - A128KW = "A128KW", - A192CBC = "A192CBC", - A192Cbcpad = "A192CBCPAD", - A192GCM = "A192GCM", - A192KW = "A192KW", - A256CBC = "A256CBC", - A256Cbcpad = "A256CBCPAD", - A256GCM = "A256GCM", - A256KW = "A256KW", - RSA15 = "RSA1_5", - RSAOaep = "RSA-OAEP", - RSAOaep256 = "RSA-OAEP-256" -} - -// @public -export enum KnownKeyCurveNames { - P256 = "P-256", - P256K = "P-256K", - P384 = "P-384", - P521 = "P-521" -} - -// @public -export enum KnownKeyExportEncryptionAlgorithm { - CkmRsaAesKeyWrap = "CKM_RSA_AES_KEY_WRAP", - RsaAesKeyWrap256 = "RSA_AES_KEY_WRAP_256", - RsaAesKeyWrap384 = "RSA_AES_KEY_WRAP_384" -} - -// @public -export enum KnownKeyOperations { - Decrypt = "decrypt", - Encrypt = "encrypt", - Import = "import", - Sign = "sign", - UnwrapKey = "unwrapKey", - Verify = "verify", - WrapKey = "wrapKey" -} - -// @public -export enum KnownKeyTypes { - EC = "EC", - ECHSM = "EC-HSM", - Oct = "oct", - OctHSM = "oct-HSM", - RSA = "RSA", - RSAHSM = "RSA-HSM" -} - -// @public -export enum KnownSignatureAlgorithms { - ES256 = "ES256", - ES256K = "ES256K", - ES384 = "ES384", - ES512 = "ES512", - PS256 = "PS256", - PS384 = "PS384", - PS512 = "PS512", - RS256 = "RS256", - RS384 = "RS384", - RS512 = "RS512", - Rsnull = "RSNULL" -} - -// @public -export interface ListDeletedKeysOptions extends coreClient.OperationOptions { -} - -// @public -export interface ListPropertiesOfKeysOptions extends coreClient.OperationOptions { -} - -// @public -export interface ListPropertiesOfKeyVersionsOptions extends coreClient.OperationOptions { -} - -// @public -export const logger: AzureLogger; - -export { PagedAsyncIterableIterator } - -export { PageSettings } - -// @public -export function parseKeyVaultKeyIdentifier(id: string): KeyVaultKeyIdentifier; - -export { PollerLike } - -export { PollOperationState } - -// @public -export interface PurgeDeletedKeyOptions extends coreClient.OperationOptions { -} - -// @public -export interface ReleaseKeyOptions extends coreClient.OperationOptions { - algorithm?: KeyExportEncryptionAlgorithm; - nonce?: string; - version?: string; -} - -// @public -export interface ReleaseKeyResult { - value: string; -} - -// @public -export interface RestoreKeyBackupOptions extends coreClient.OperationOptions { -} - -// @public -export interface RotateKeyOptions extends coreClient.OperationOptions { -} - -// @public -export interface RsaDecryptParameters { - algorithm: RsaEncryptionAlgorithm; - ciphertext: Uint8Array; -} - -// @public -export type RsaEncryptionAlgorithm = "RSA1_5" | "RSA-OAEP" | "RSA-OAEP-256"; - -// @public -export interface RsaEncryptParameters { - algorithm: RsaEncryptionAlgorithm; - plaintext: Uint8Array; -} - -// @public -export type SignatureAlgorithm = string; - -// @public -export interface SignOptions extends CryptographyOptions { -} - -// @public -export interface SignResult { - algorithm: SignatureAlgorithm; - keyID?: string; - result: Uint8Array; -} - -// @public -export interface UnwrapKeyOptions extends CryptographyOptions { -} - -// @public -export interface UnwrapResult { - algorithm: KeyWrapAlgorithm; - keyID?: string; - result: Uint8Array; -} - -// @public -export interface UpdateKeyPropertiesOptions extends coreClient.OperationOptions { - enabled?: boolean; - expiresOn?: Date; - keyOps?: KeyOperation[]; - notBefore?: Date; - releasePolicy?: KeyReleasePolicy; - tags?: { - [propertyName: string]: string; - }; -} - -// @public -export interface UpdateKeyRotationPolicyOptions extends coreClient.OperationOptions { -} - -// @public -export interface VerifyDataOptions extends CryptographyOptions { -} - -// @public -export interface VerifyOptions extends CryptographyOptions { -} - -// @public -export interface VerifyResult { - keyID?: string; - result: boolean; -} - -// @public -export interface WrapKeyOptions extends CryptographyOptions { -} - -// @public -export interface WrapResult { - algorithm: KeyWrapAlgorithm; - keyID?: string; - result: Uint8Array; -} - -// (No @packageDocumentation comment for this package) - -``` diff --git a/sdk/keyvault/keyvault-keys/sample.env b/sdk/keyvault/keyvault-keys/sample.env deleted file mode 100644 index 77aa215fde62..000000000000 --- a/sdk/keyvault/keyvault-keys/sample.env +++ /dev/null @@ -1,15 +0,0 @@ -# The name of the key vault to use in the samples. -# Create a Key Vault in the Azure Portal and enter its URI (e.g. https://mytest.vault.azure.net/) here. -KEYVAULT_URI= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://learn.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= - -# Our tests assume that TEST_MODE is "playback" by default. You can -# change it to "record" to generate new recordings, or "live" to bypass the recorder entirely. -# TEST_MODE=playback diff --git a/sdk/keyvault/keyvault-keys/samples-dev/cryptography.ts b/sdk/keyvault/keyvault-keys/samples-dev/cryptography.ts deleted file mode 100644 index 82342f276244..000000000000 --- a/sdk/keyvault/keyvault-keys/samples-dev/cryptography.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an Azure Key Vault key to sign/verify, encrypt/decrypt, and wrap/unwrap data. - */ - -import { createHash } from "node:crypto"; - -import { CryptographyClient, KeyClient } from "@azure/keyvault-keys"; -import { DefaultAzureCredential } from "@azure/identity"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - - // Connection to Azure Key Vault - const client = new KeyClient(url, credential); - - const keyName = `crypto-sample-key${Date.now()}`; - - // Connection to Azure Key Vault Cryptography functionality - const myWorkKey = await client.createKey(keyName, "RSA"); - - const cryptoClient = new CryptographyClient( - myWorkKey.id!, // You can use either the key or the key Id i.e. its url to create a CryptographyClient. - credential, - ); - - // Sign and Verify - const signatureValue = "MySignature"; - let hash = createHash("sha256"); - - await hash.update(signatureValue); - let digest = hash.digest(); - console.log("digest: ", digest); - - const signature = await cryptoClient.sign("RS256", digest); - console.log("sign result: ", signature); - - const verifyResult = await cryptoClient.verify("RS256", digest, signature.result); - console.log("verify result: ", verifyResult); - - // Encrypt and decrypt - const encrypt = await cryptoClient.encrypt({ - algorithm: "RSA1_5", - plaintext: Buffer.from("My Message"), - }); - console.log("encrypt result: ", encrypt); - - const decrypt = await cryptoClient.decrypt({ algorithm: "RSA1_5", ciphertext: encrypt.result }); - console.log("decrypt: ", decrypt.result.toString()); - - // Wrap and unwrap - const wrapped = await cryptoClient.wrapKey("RSA-OAEP", Buffer.from("My Message")); - console.log("wrap result: ", wrapped); - - const unwrapped = await cryptoClient.unwrapKey("RSA-OAEP", wrapped.result); - console.log("unwrap result: ", unwrapped); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); diff --git a/sdk/keyvault/keyvault-keys/samples-dev/helloWorld.ts b/sdk/keyvault/keyvault-keys/samples-dev/helloWorld.ts deleted file mode 100644 index a1e59e27a6a6..000000000000 --- a/sdk/keyvault/keyvault-keys/samples-dev/helloWorld.ts +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Creates, reads, lists, and deletes keys. - */ - -import { KeyClient } from "@azure/keyvault-keys"; -import { DefaultAzureCredential } from "@azure/identity"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - const client = new KeyClient(url, credential); - - // Create unique names for keys we will use in this sample - const uniqueString = Date.now(); - const keyName = `sample-key-${uniqueString}`; - const ecKeyName = `sample-ec-key-${uniqueString}`; - const rsaKeyName = `sample-rsa-key-${uniqueString}`; - - // You can create keys using the general method - const result = await client.createKey(keyName, "EC"); - console.log("key: ", result); - - // Or using specialized key creation methods - const ecResult = await client.createEcKey(ecKeyName, { curve: "P-256" }); - const rsaResult = await client.createRsaKey(rsaKeyName, { keySize: 2048 }); - console.log("Elliptic curve key: ", ecResult); - console.log("RSA Key: ", rsaResult); - - // Get a specific key - const key = await client.getKey(keyName); - console.log("key: ", key); - - // Or list the keys we have - for await (const keyProperties of client.listPropertiesOfKeys()) { - const key = await client.getKey(keyProperties.name); - console.log("key: ", key); - } - - // Update the key - const updatedKey = await client.updateKeyProperties(keyName, result.properties.version!, { - enabled: false, - }); - console.log("updated key: ", updatedKey); - - // Delete the key - the key is soft-deleted but not yet purged - const deletePoller = await client.beginDeleteKey(keyName); - await deletePoller.pollUntilDone(); - - // The `getDeletedKey` method can be used to retrieve any soft-deleted key - const deletedKey = await client.getDeletedKey(keyName); - console.log("deleted key: ", deletedKey); - - // Purge the key - the key is permanently deleted - // This operation could take some time to complete - await console.time("purge a single key"); - await client.purgeDeletedKey(keyName); - await console.timeEnd("purge a single key"); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); diff --git a/sdk/keyvault/keyvault-keys/samples-dev/keyRotation.ts b/sdk/keyvault/keyvault-keys/samples-dev/keyRotation.ts deleted file mode 100644 index 5df2ad441f68..000000000000 --- a/sdk/keyvault/keyvault-keys/samples-dev/keyRotation.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Creates and updates a key's automated rotation policy, and rotates a key on-demand. - */ - -import { KeyClient } from "@azure/keyvault-keys"; -import { DefaultAzureCredential } from "@azure/identity"; -import dayjs from "dayjs"; -import duration from "dayjs/plugin/duration.js"; -dayjs.extend(duration); - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - const client = new KeyClient(url, credential); - - const keyName = `key-rotation-sample-key-${Date.now()}`; - const key = await client.createKey(keyName, "EC"); - console.log("created key", key); - - // Set the key's automated rotation policy to rotate the key 30 days after the key is created. - const policy = await client.updateKeyRotationPolicy(key.name, { - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P30D", - }, - ], - }); - console.log("created policy", policy); - - // Get the key's current rotation policy - const currentPolicy = await client.getKeyRotationPolicy(key.name); - console.log("fetched policy", currentPolicy); - - // Update the key's automated rotation policy to notify 30 days before the key expires. - // By using the ISO8601 duration standard, interoperability with any 3rd party library that supports Durations is supported. - // In this example, we'll use Day.js (documented in https://day.js.org) to create the duration. - // For more information on the ISO 8601 Duration standard, please refer to the Wikipedia page on Durations: - // https://wikipedia.org/wiki/ISO_8601#Durations - const updatedPolicy = await client.updateKeyRotationPolicy(key.name, { - lifetimeActions: [ - { - action: "Notify", - timeBeforeExpiry: dayjs.duration({ days: 30 }).toISOString(), - }, - ], - expiresIn: "P90D", - }); - console.log("updated policy", updatedPolicy); - - // Rotate the key on-demand, generating a new version of the key. - const newKeyVersion = await client.rotateKey(key.name); - console.log("rotated key", newKeyVersion); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); diff --git a/sdk/keyvault/keyvault-keys/samples-dev/snippets/_prerequisites.md b/sdk/keyvault/keyvault-keys/samples-dev/snippets/_prerequisites.md deleted file mode 100644 index 6f2d90ee9dc1..000000000000 --- a/sdk/keyvault/keyvault-keys/samples-dev/snippets/_prerequisites.md +++ /dev/null @@ -1,5 +0,0 @@ -To quickly create the needed Key Vault resources in Azure and to receive a connection string for them, you can deploy our sample template by clicking: - -[![](http://azuredeploy.net/deploybutton.png)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-sdk-for-js%2Fmaster%2Fsdk%2Fkeyvault%2Ftest-resources.json) - -If creating the Key Vault manually using the Azure Portal, be aware that the samples require that the soft-delete feature be enabled. Our template above will enable this feature automatically, but it is possible to enable it manually using the Azure CLI. See [the documentation for enabling soft-delete in Key Vault](https://learn.microsoft.com/azure/key-vault/key-vault-soft-delete-cli) for more information. diff --git a/sdk/keyvault/keyvault-keys/samples/v4/javascript/README.md b/sdk/keyvault/keyvault-keys/samples/v4/javascript/README.md deleted file mode 100644 index 25583e1cfc25..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/javascript/README.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -page_type: sample -languages: - - javascript -products: - - azure - - azure-key-vault -urlFragment: keyvault-keys-javascript ---- - -# Azure Key Vault Keys client library samples for JavaScript - -These sample programs show how to use the JavaScript client libraries for Azure Key Vault Keys in some common scenarios. - -| **File Name** | **Description** | -| ------------------------------- | ----------------------------------------------------------------------------------- | -| [cryptography.js][cryptography] | Uses an Azure Key Vault key to sign/verify, encrypt/decrypt, and wrap/unwrap data. | -| [helloWorld.js][helloworld] | Creates, reads, lists, and deletes keys. | -| [keyRotation.js][keyrotation] | Creates and updates a key's automated rotation policy, and rotates a key on-demand. | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -You need [an Azure subscription][freesub] and the following Azure resources to run these sample programs: - -- [Azure Key Vault][createinstance_azurekeyvault] - -To quickly create the needed Key Vault resources in Azure and to receive a connection string for them, you can deploy our sample template by clicking: - -[![](http://azuredeploy.net/deploybutton.png)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-sdk-for-js%2Fmaster%2Fsdk%2Fkeyvault%2Ftest-resources.json) - -If creating the Key Vault manually using the Azure Portal, be aware that the samples require that the soft-delete feature be enabled. Our template above will enable this feature automatically, but it is possible to enable it manually using the Azure CLI. See [the documentation for enabling soft-delete in Key Vault](https://learn.microsoft.com/azure/key-vault/key-vault-soft-delete-cli) for more information. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -3. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node cryptography.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env KEYVAULT_URI="" node cryptography.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[cryptography]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/javascript/cryptography.js -[helloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/javascript/helloWorld.js -[keyrotation]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/javascript/keyRotation.js -[apiref]: https://learn.microsoft.com/javascript/api/@azure/keyvault-keys -[freesub]: https://azure.microsoft.com/free/ -[createinstance_azurekeyvault]: https://learn.microsoft.com/azure/key-vault/quick-create-portal -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-keys/README.md diff --git a/sdk/keyvault/keyvault-keys/samples/v4/javascript/cryptography.js b/sdk/keyvault/keyvault-keys/samples/v4/javascript/cryptography.js deleted file mode 100644 index 0265c8eaf689..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/javascript/cryptography.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an Azure Key Vault key to sign/verify, encrypt/decrypt, and wrap/unwrap data. - */ - -const { createHash } = require("crypto"); - -const { CryptographyClient, KeyClient } = require("@azure/keyvault-keys"); -const { DefaultAzureCredential } = require("@azure/identity"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - - // Connection to Azure Key Vault - const client = new KeyClient(url, credential); - - const keyName = `crypto-sample-key${Date.now()}`; - - // Connection to Azure Key Vault Cryptography functionality - const myWorkKey = await client.createKey(keyName, "RSA"); - - const cryptoClient = new CryptographyClient( - myWorkKey.id, // You can use either the key or the key Id i.e. its url to create a CryptographyClient. - credential - ); - - // Sign and Verify - const signatureValue = "MySignature"; - let hash = createHash("sha256"); - - hash.update(signatureValue); - let digest = hash.digest(); - console.log("digest: ", digest); - - const signature = await cryptoClient.sign("RS256", digest); - console.log("sign result: ", signature); - - const verifyResult = await cryptoClient.verify("RS256", digest, signature.result); - console.log("verify result: ", verifyResult); - - // Encrypt and decrypt - const encrypt = await cryptoClient.encrypt({ - algorithm: "RSA1_5", - plaintext: Buffer.from("My Message"), - }); - console.log("encrypt result: ", encrypt); - - const decrypt = await cryptoClient.decrypt({ algorithm: "RSA1_5", ciphertext: encrypt.result }); - console.log("decrypt: ", decrypt.result.toString()); - - // Wrap and unwrap - const wrapped = await cryptoClient.wrapKey("RSA-OAEP", Buffer.from("My Message")); - console.log("wrap result: ", wrapped); - - const unwrapped = await cryptoClient.unwrapKey("RSA-OAEP", wrapped.result); - console.log("unwrap result: ", unwrapped); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-keys/samples/v4/javascript/helloWorld.js b/sdk/keyvault/keyvault-keys/samples/v4/javascript/helloWorld.js deleted file mode 100644 index e50cc4a3f4a9..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/javascript/helloWorld.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Creates, reads, lists, and deletes keys. - */ - -const { KeyClient } = require("@azure/keyvault-keys"); -const { DefaultAzureCredential } = require("@azure/identity"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - const client = new KeyClient(url, credential); - - // Create unique names for keys we will use in this sample - const uniqueString = Date.now(); - const keyName = `sample-key-${uniqueString}`; - const ecKeyName = `sample-ec-key-${uniqueString}`; - const rsaKeyName = `sample-rsa-key-${uniqueString}`; - - // You can create keys using the general method - const result = await client.createKey(keyName, "EC"); - console.log("key: ", result); - - // Or using specialized key creation methods - const ecResult = await client.createEcKey(ecKeyName, { curve: "P-256" }); - const rsaResult = await client.createRsaKey(rsaKeyName, { keySize: 2048 }); - console.log("Elliptic curve key: ", ecResult); - console.log("RSA Key: ", rsaResult); - - // Get a specific key - const key = await client.getKey(keyName); - console.log("key: ", key); - - // Or list the keys we have - for await (const keyProperties of client.listPropertiesOfKeys()) { - const key = await client.getKey(keyProperties.name); - console.log("key: ", key); - } - - // Update the key - const updatedKey = await client.updateKeyProperties(keyName, result.properties.version, { - enabled: false, - }); - console.log("updated key: ", updatedKey); - - // Delete the key - the key is soft-deleted but not yet purged - const deletePoller = await client.beginDeleteKey(keyName); - await deletePoller.pollUntilDone(); - - // The `getDeletedKey` method can be used to retrieve any soft-deleted key - const deletedKey = await client.getDeletedKey(keyName); - console.log("deleted key: ", deletedKey); - - // Purge the key - the key is permanently deleted - // This operation could take some time to complete - console.time("purge a single key"); - await client.purgeDeletedKey(keyName); - console.timeEnd("purge a single key"); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-keys/samples/v4/javascript/keyRotation.js b/sdk/keyvault/keyvault-keys/samples/v4/javascript/keyRotation.js deleted file mode 100644 index fec346f471f7..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/javascript/keyRotation.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Creates and updates a key's automated rotation policy, and rotates a key on-demand. - */ - -const { KeyClient } = require("@azure/keyvault-keys"); -const { DefaultAzureCredential } = require("@azure/identity"); -const dayjs = require("dayjs"); -const duration = require("dayjs/plugin/duration"); -dayjs.extend(duration); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - const client = new KeyClient(url, credential); - - const keyName = `key-rotation-sample-key-${Date.now()}`; - const key = await client.createKey(keyName, "EC"); - console.log("created key", key); - - // Set the key's automated rotation policy to rotate the key 30 days after the key is created. - const policy = await client.updateKeyRotationPolicy(key.name, { - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P30D", - }, - ], - }); - console.log("created policy", policy); - - // Get the key's current rotation policy - const currentPolicy = await client.getKeyRotationPolicy(key.name); - console.log("fetched policy", currentPolicy); - - // Update the key's automated rotation policy to notify 30 days before the key expires. - // By using the ISO8601 duration standard, interoperability with any 3rd party library that supports Durations is supported. - // In this example, we'll use Day.js (documented in https://day.js.org) to create the duration. - // For more information on the ISO 8601 Duration standard, please refer to the Wikipedia page on Durations: - // https://wikipedia.org/wiki/ISO_8601#Durations - const updatedPolicy = await client.updateKeyRotationPolicy(key.name, { - lifetimeActions: [ - { - action: "Notify", - timeBeforeExpiry: dayjs.duration({ days: 30 }).toISOString(), - }, - ], - expiresIn: "P90D", - }); - console.log("updated policy", updatedPolicy); - - // Rotate the key on-demand, generating a new version of the key. - const newKeyVersion = await client.rotateKey(key.name); - console.log("rotated key", newKeyVersion); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-keys/samples/v4/javascript/package.json b/sdk/keyvault/keyvault-keys/samples/v4/javascript/package.json deleted file mode 100644 index 8660b8f36548..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/javascript/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@azure-samples/keyvault-keys-js", - "private": true, - "version": "1.0.0", - "description": "Azure Key Vault Keys client library samples for JavaScript", - "engines": { - "node": ">=18.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/keyvault/keyvault-keys" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-keys", - "dependencies": { - "@azure/keyvault-keys": "latest", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "dayjs": "^1.10.7" - } -} diff --git a/sdk/keyvault/keyvault-keys/samples/v4/javascript/sample.env b/sdk/keyvault/keyvault-keys/samples/v4/javascript/sample.env deleted file mode 100644 index 77aa215fde62..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/javascript/sample.env +++ /dev/null @@ -1,15 +0,0 @@ -# The name of the key vault to use in the samples. -# Create a Key Vault in the Azure Portal and enter its URI (e.g. https://mytest.vault.azure.net/) here. -KEYVAULT_URI= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://learn.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= - -# Our tests assume that TEST_MODE is "playback" by default. You can -# change it to "record" to generate new recordings, or "live" to bypass the recorder entirely. -# TEST_MODE=playback diff --git a/sdk/keyvault/keyvault-keys/samples/v4/typescript/README.md b/sdk/keyvault/keyvault-keys/samples/v4/typescript/README.md deleted file mode 100644 index 306cf7ee21e2..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/typescript/README.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -page_type: sample -languages: - - typescript -products: - - azure - - azure-key-vault -urlFragment: keyvault-keys-typescript ---- - -# Azure Key Vault Keys client library samples for TypeScript - -These sample programs show how to use the TypeScript client libraries for Azure Key Vault Keys in some common scenarios. - -| **File Name** | **Description** | -| ------------------------------- | ----------------------------------------------------------------------------------- | -| [cryptography.ts][cryptography] | Uses an Azure Key Vault key to sign/verify, encrypt/decrypt, and wrap/unwrap data. | -| [helloWorld.ts][helloworld] | Creates, reads, lists, and deletes keys. | -| [keyRotation.ts][keyrotation] | Creates and updates a key's automated rotation policy, and rotates a key on-demand. | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using: - -```bash -npm install -g typescript -``` - -You need [an Azure subscription][freesub] and the following Azure resources to run these sample programs: - -- [Azure Key Vault][createinstance_azurekeyvault] - -To quickly create the needed Key Vault resources in Azure and to receive a connection string for them, you can deploy our sample template by clicking: - -[![](http://azuredeploy.net/deploybutton.png)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-sdk-for-js%2Fmaster%2Fsdk%2Fkeyvault%2Ftest-resources.json) - -If creating the Key Vault manually using the Azure Portal, be aware that the samples require that the soft-delete feature be enabled. Our template above will enable this feature automatically, but it is possible to enable it manually using the Azure CLI. See [the documentation for enabling soft-delete in Key Vault](https://learn.microsoft.com/azure/key-vault/key-vault-soft-delete-cli) for more information. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Compile the samples: - -```bash -npm run build -``` - -3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -4. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node dist/cryptography.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env KEYVAULT_URI="" node dist/cryptography.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[cryptography]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/cryptography.ts -[helloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/helloWorld.ts -[keyrotation]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/keyRotation.ts -[apiref]: https://learn.microsoft.com/javascript/api/@azure/keyvault-keys -[freesub]: https://azure.microsoft.com/free/ -[createinstance_azurekeyvault]: https://learn.microsoft.com/azure/key-vault/quick-create-portal -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-keys/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/keyvault/keyvault-keys/samples/v4/typescript/package.json b/sdk/keyvault/keyvault-keys/samples/v4/typescript/package.json deleted file mode 100644 index 9284f4ad96b9..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/typescript/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "@azure-samples/keyvault-keys-ts", - "private": true, - "version": "1.0.0", - "description": "Azure Key Vault Keys client library samples for TypeScript", - "engines": { - "node": ">=18.0.0" - }, - "scripts": { - "build": "tsc", - "prebuild": "rimraf dist/" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/keyvault/keyvault-keys" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-keys", - "dependencies": { - "@azure/keyvault-keys": "latest", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "dayjs": "^1.10.7" - }, - "devDependencies": { - "@types/node": "^18.0.0", - "typescript": "~5.7.2", - "rimraf": "latest" - } -} diff --git a/sdk/keyvault/keyvault-keys/samples/v4/typescript/sample.env b/sdk/keyvault/keyvault-keys/samples/v4/typescript/sample.env deleted file mode 100644 index 77aa215fde62..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/typescript/sample.env +++ /dev/null @@ -1,15 +0,0 @@ -# The name of the key vault to use in the samples. -# Create a Key Vault in the Azure Portal and enter its URI (e.g. https://mytest.vault.azure.net/) here. -KEYVAULT_URI= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://learn.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= - -# Our tests assume that TEST_MODE is "playback" by default. You can -# change it to "record" to generate new recordings, or "live" to bypass the recorder entirely. -# TEST_MODE=playback diff --git a/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/cryptography.ts b/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/cryptography.ts deleted file mode 100644 index 6747098165c6..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/cryptography.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an Azure Key Vault key to sign/verify, encrypt/decrypt, and wrap/unwrap data. - */ - -import { createHash } from "crypto"; - -import { CryptographyClient, KeyClient } from "@azure/keyvault-keys"; -import { DefaultAzureCredential } from "@azure/identity"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - - // Connection to Azure Key Vault - const client = new KeyClient(url, credential); - - const keyName = `crypto-sample-key${Date.now()}`; - - // Connection to Azure Key Vault Cryptography functionality - const myWorkKey = await client.createKey(keyName, "RSA"); - - const cryptoClient = new CryptographyClient( - myWorkKey.id!, // You can use either the key or the key Id i.e. its url to create a CryptographyClient. - credential - ); - - // Sign and Verify - const signatureValue = "MySignature"; - let hash = createHash("sha256"); - - hash.update(signatureValue); - let digest = hash.digest(); - console.log("digest: ", digest); - - const signature = await cryptoClient.sign("RS256", digest); - console.log("sign result: ", signature); - - const verifyResult = await cryptoClient.verify("RS256", digest, signature.result); - console.log("verify result: ", verifyResult); - - // Encrypt and decrypt - const encrypt = await cryptoClient.encrypt({ - algorithm: "RSA1_5", - plaintext: Buffer.from("My Message"), - }); - console.log("encrypt result: ", encrypt); - - const decrypt = await cryptoClient.decrypt({ algorithm: "RSA1_5", ciphertext: encrypt.result }); - console.log("decrypt: ", decrypt.result.toString()); - - // Wrap and unwrap - const wrapped = await cryptoClient.wrapKey("RSA-OAEP", Buffer.from("My Message")); - console.log("wrap result: ", wrapped); - - const unwrapped = await cryptoClient.unwrapKey("RSA-OAEP", wrapped.result); - console.log("unwrap result: ", unwrapped); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); diff --git a/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/helloWorld.ts b/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/helloWorld.ts deleted file mode 100644 index c59b5a533e29..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/helloWorld.ts +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Creates, reads, lists, and deletes keys. - */ - -import { KeyClient } from "@azure/keyvault-keys"; -import { DefaultAzureCredential } from "@azure/identity"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - const client = new KeyClient(url, credential); - - // Create unique names for keys we will use in this sample - const uniqueString = Date.now(); - const keyName = `sample-key-${uniqueString}`; - const ecKeyName = `sample-ec-key-${uniqueString}`; - const rsaKeyName = `sample-rsa-key-${uniqueString}`; - - // You can create keys using the general method - const result = await client.createKey(keyName, "EC"); - console.log("key: ", result); - - // Or using specialized key creation methods - const ecResult = await client.createEcKey(ecKeyName, { curve: "P-256" }); - const rsaResult = await client.createRsaKey(rsaKeyName, { keySize: 2048 }); - console.log("Elliptic curve key: ", ecResult); - console.log("RSA Key: ", rsaResult); - - // Get a specific key - const key = await client.getKey(keyName); - console.log("key: ", key); - - // Or list the keys we have - for await (const keyProperties of client.listPropertiesOfKeys()) { - const key = await client.getKey(keyProperties.name); - console.log("key: ", key); - } - - // Update the key - const updatedKey = await client.updateKeyProperties(keyName, result.properties.version!, { - enabled: false, - }); - console.log("updated key: ", updatedKey); - - // Delete the key - the key is soft-deleted but not yet purged - const deletePoller = await client.beginDeleteKey(keyName); - await deletePoller.pollUntilDone(); - - // The `getDeletedKey` method can be used to retrieve any soft-deleted key - const deletedKey = await client.getDeletedKey(keyName); - console.log("deleted key: ", deletedKey); - - // Purge the key - the key is permanently deleted - // This operation could take some time to complete - console.time("purge a single key"); - await client.purgeDeletedKey(keyName); - console.timeEnd("purge a single key"); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); diff --git a/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/keyRotation.ts b/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/keyRotation.ts deleted file mode 100644 index 537963403fc9..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/typescript/src/keyRotation.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Creates and updates a key's automated rotation policy, and rotates a key on-demand. - */ - -import { KeyClient } from "@azure/keyvault-keys"; -import { DefaultAzureCredential } from "@azure/identity"; -import dayjs from "dayjs"; -import duration from "dayjs/plugin/duration"; -dayjs.extend(duration); - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms. - // See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information - // about DefaultAzureCredential and the other credentials that are available for use. - const credential = new DefaultAzureCredential(); - - const url = process.env["KEYVAULT_URI"] || ""; - const client = new KeyClient(url, credential); - - const keyName = `key-rotation-sample-key-${Date.now()}`; - const key = await client.createKey(keyName, "EC"); - console.log("created key", key); - - // Set the key's automated rotation policy to rotate the key 30 days after the key is created. - const policy = await client.updateKeyRotationPolicy(key.name, { - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P30D", - }, - ], - }); - console.log("created policy", policy); - - // Get the key's current rotation policy - const currentPolicy = await client.getKeyRotationPolicy(key.name); - console.log("fetched policy", currentPolicy); - - // Update the key's automated rotation policy to notify 30 days before the key expires. - // By using the ISO8601 duration standard, interoperability with any 3rd party library that supports Durations is supported. - // In this example, we'll use Day.js (documented in https://day.js.org) to create the duration. - // For more information on the ISO 8601 Duration standard, please refer to the Wikipedia page on Durations: - // https://wikipedia.org/wiki/ISO_8601#Durations - const updatedPolicy = await client.updateKeyRotationPolicy(key.name, { - lifetimeActions: [ - { - action: "Notify", - timeBeforeExpiry: dayjs.duration({ days: 30 }).toISOString(), - }, - ], - expiresIn: "P90D", - }); - console.log("updated policy", updatedPolicy); - - // Rotate the key on-demand, generating a new version of the key. - const newKeyVersion = await client.rotateKey(key.name); - console.log("rotated key", newKeyVersion); -} - -main().catch((error) => { - console.error("An error occurred:", error); - process.exit(1); -}); diff --git a/sdk/keyvault/keyvault-keys/samples/v4/typescript/tsconfig.json b/sdk/keyvault/keyvault-keys/samples/v4/typescript/tsconfig.json deleted file mode 100644 index ad5ff9a19d36..000000000000 --- a/sdk/keyvault/keyvault-keys/samples/v4/typescript/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2018", - "module": "commonjs", - "moduleResolution": "node", - "resolveJsonModule": true, - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "strict": true, - "alwaysStrict": true, - "outDir": "dist", - "rootDir": "src" - }, - "include": [ - "src/**/*.ts" - ] -} diff --git a/sdk/keyvault/keyvault-keys/src/constants.ts b/sdk/keyvault/keyvault-keys/src/constants.ts deleted file mode 100644 index f0a3a965f06d..000000000000 --- a/sdk/keyvault/keyvault-keys/src/constants.ts +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export const SDK_VERSION: string = "4.9.1"; diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/aesCryptographyProvider-browser.mts b/sdk/keyvault/keyvault-keys/src/cryptography/aesCryptographyProvider-browser.mts deleted file mode 100644 index 47d9d8b97a40..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/aesCryptographyProvider-browser.mts +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { CryptographyProvider} from "./models.js"; -import { LocalCryptographyUnsupportedError } from "./models.js"; - -/** - * The browser replacement of the AesCryptographyProvider. Since we do not - * support local cryptography in the browser this replacement always returns false - * for `supportsAlgorithm` and `supportsOperation` so that these methods should - * never be called. - */ -export class AesCryptographyProvider implements CryptographyProvider { - encrypt(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } - decrypt(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } - - /** - * Browser RSA provider does not support any algorithms or operations. - */ - isSupported(): boolean { - return false; - } - - wrapKey(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } - - unwrapKey(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } - - sign(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } - - signData(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } - - verify(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } - - verifyData(): never { - throw new LocalCryptographyUnsupportedError( - "AES Local cryptography is not supported in the browser.", - ); - } -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/aesCryptographyProvider.ts b/sdk/keyvault/keyvault-keys/src/cryptography/aesCryptographyProvider.ts deleted file mode 100644 index fce0c11d9561..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/aesCryptographyProvider.ts +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { OperationOptions } from "@azure-rest/core-client"; -import * as crypto from "node:crypto"; -import type { - AesCbcEncryptParameters, - DecryptOptions, - DecryptResult, - EncryptOptions, - EncryptResult, - JsonWebKey, - KeyWrapAlgorithm, - SignOptions, - SignResult, - UnwrapKeyOptions, - UnwrapResult, - VerifyOptions, - VerifyResult, - WrapKeyOptions, - WrapResult, -} from "../index.js"; -import type { AesCbcDecryptParameters } from "../cryptographyClientModels.js"; -import type { CryptographyProvider, CryptographyProviderOperation } from "./models.js"; -import { LocalCryptographyUnsupportedError } from "./models.js"; - -/** - * An AES cryptography provider supporting AES algorithms. - * @internal - */ -export class AesCryptographyProvider implements CryptographyProvider { - private key: JsonWebKey; - constructor(key: JsonWebKey) { - this.key = key; - } - encrypt( - encryptParameters: AesCbcEncryptParameters, - _options?: EncryptOptions, - ): Promise { - const { algorithm, keySizeInBytes } = this.supportedAlgorithms[encryptParameters.algorithm]; - const iv = encryptParameters.iv || crypto.randomBytes(16); - - this.ensureValid(keySizeInBytes); - - const cipher = crypto.createCipheriv(algorithm, this.key.k!.subarray(0, keySizeInBytes), iv); - let encrypted = cipher.update(Buffer.from(encryptParameters.plaintext)); - encrypted = Buffer.concat([encrypted, cipher.final()]); - - return Promise.resolve({ - algorithm: encryptParameters.algorithm, - result: encrypted, - iv: iv, - }); - } - - decrypt( - decryptParameters: AesCbcDecryptParameters, - _options?: DecryptOptions, - ): Promise { - const { algorithm, keySizeInBytes } = this.supportedAlgorithms[decryptParameters.algorithm]; - - this.ensureValid(keySizeInBytes); - - const decipher = crypto.createDecipheriv( - algorithm, - this.key.k!.subarray(0, keySizeInBytes), - decryptParameters.iv, - ); - let dec = decipher.update(Buffer.from(decryptParameters.ciphertext)); - dec = Buffer.concat([dec, decipher.final()]); - - return Promise.resolve({ - algorithm: decryptParameters.algorithm, - result: dec, - }); - } - - isSupported(algorithm: string, operation: CryptographyProviderOperation): boolean { - if (!this.key.k) { - return false; - } - - if (!Object.keys(this.supportedAlgorithms).includes(algorithm)) { - return false; - } - - if (!this.supportedOperations.includes(operation)) { - return false; - } - - return true; - } - - /** - * The set of algorithms this provider supports. - * For AES encryption, the values include the underlying algorithm used in crypto - * as well as the key size in bytes. - * - * We start with support for A[SIZE]CBCPAD which uses the PKCS padding (the default padding scheme in node crypto) - */ - private supportedAlgorithms: { [s: string]: { algorithm: string; keySizeInBytes: number } } = { - A128CBCPAD: { - algorithm: "aes-128-cbc", - keySizeInBytes: 128 >> 3, - }, - A192CBCPAD: { - algorithm: "aes-192-cbc", - keySizeInBytes: 192 >> 3, - }, - A256CBCPAD: { - algorithm: "aes-256-cbc", - keySizeInBytes: 256 >> 3, - }, - }; - - private supportedOperations: CryptographyProviderOperation[] = ["encrypt", "decrypt"]; - - wrapKey( - _algorithm: KeyWrapAlgorithm, - _keyToWrap: Uint8Array, - _options?: WrapKeyOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Wrapping a key using a local JsonWebKey is not supported for AES.", - ); - } - - unwrapKey( - _algorithm: KeyWrapAlgorithm, - _encryptedKey: Uint8Array, - _options?: UnwrapKeyOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Unwrapping a key using a local JsonWebKey is not supported for AES.", - ); - } - - sign(_algorithm: string, _digest: Uint8Array, _options?: SignOptions): Promise { - throw new LocalCryptographyUnsupportedError( - "Signing using a local JsonWebKey is not supported for AES.", - ); - } - - signData(_algorithm: string, _data: Uint8Array, _options?: SignOptions): Promise { - throw new LocalCryptographyUnsupportedError( - "Signing using a local JsonWebKey is not supported for AES.", - ); - } - - verify( - _algorithm: string, - _digest: Uint8Array, - _signature: Uint8Array, - _options?: VerifyOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Verifying using a local JsonWebKey is not supported for AES.", - ); - } - verifyData( - _algorithm: string, - _data: Uint8Array, - _signature: Uint8Array, - _updatedOptions: OperationOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Verifying using a local JsonWebKey is not supported for AES.", - ); - } - - private ensureValid(keySizeInBytes: number): void { - if ( - this.key && - this.key.kty?.toUpperCase() !== "OCT" && - this.key.kty?.toUpperCase() !== "OCT-HSM" - ) { - throw new Error("Key type does not match the key type oct or oct-hsm"); - } - - if (!this.key.k) { - throw new Error("Symmetric key is required"); - } - - if (this.key.k.length < keySizeInBytes) { - throw new Error(`Key must be at least ${keySizeInBytes << 3} bits`); - } - } -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/conversions.ts b/sdk/keyvault/keyvault-keys/src/cryptography/conversions.ts deleted file mode 100644 index b9d96c4b3a7a..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/conversions.ts +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { JsonWebKey } from "../keysModels.js"; - -/** - * @internal - * Encodes a length of a packet in DER format - */ -function encodeLength(length: number): Uint8Array { - if (length <= 127) { - return Uint8Array.of(length); - } else if (length < 256) { - return Uint8Array.of(0x81, length); - } else if (length < 65536) { - return Uint8Array.of(0x82, length >> 8, length & 0xff); - } else { - throw new Error("Unsupported length to encode"); - } -} - -/** - * @internal - * Encodes a buffer for DER, as sets the id to the given id - */ -function encodeBuffer(buffer: Uint8Array, bufferId: number): Uint8Array { - if (buffer.length === 0) { - return buffer; - } - - let result = new Uint8Array(buffer); - - // If the high bit is set, prepend a 0 - if (result[0] & 0x80) { - const array = new Uint8Array(result.length + 1); - array[0] = 0; - array.set(result, 1); - result = array; - } - - // Prepend the DER header for this buffer - const encodedLength = encodeLength(result.length); - const totalLength = 1 + encodedLength.length + result.length; - - const outputBuffer = new Uint8Array(totalLength); - outputBuffer[0] = bufferId; - outputBuffer.set(encodedLength, 1); - outputBuffer.set(result, 1 + encodedLength.length); - - return outputBuffer; -} - -function makeSequence(encodedParts: Uint8Array[]): string { - const totalLength = encodedParts.reduce((sum, part) => sum + part.length, 0); - const sequence = new Uint8Array(totalLength); - - for (let i = 0; i < encodedParts.length; i++) { - const previousLength = i > 0 ? encodedParts[i - 1].length : 0; - sequence.set(encodedParts[i], previousLength); - } - - const full_encoded = encodeBuffer(sequence, 0x30); // SEQUENCE - return Buffer.from(full_encoded).toString("base64"); -} - -/** - * Fill in the PEM with 64 character lines as per RFC: - * - * "To represent the encapsulated text of a PEM message, the encoding - * function's output is delimited into text lines (using local - * conventions), with each line except the last containing exactly 64 - * printable characters and the final line containing 64 or fewer - * printable characters." - */ -function formatBase64Sequence(base64Sequence: string): string { - const lines = base64Sequence.match(/.{1,64}/g); - let result = ""; - if (lines) { - for (const line of lines) { - result += line; - result += "\n"; - } - } else { - throw new Error("Could not create correct PEM"); - } - return result; -} - -/** - * @internal - * Encode a JWK to PEM format. To do so, it internally repackages the JWK as a DER - * that is then encoded as a PEM. - */ -export function convertJWKtoPEM(key: JsonWebKey): string { - let result = ""; - - if (key.n && key.e) { - const parts = [key.n, key.e]; - const encodedParts = parts.map((part) => encodeBuffer(part, 0x2)); // INTEGER - const base64Sequence = makeSequence(encodedParts); - result += "-----BEGIN RSA PUBLIC KEY-----\n"; - result += formatBase64Sequence(base64Sequence); - result += "-----END RSA PUBLIC KEY-----\n"; - } - - if (!result.length) { - throw new Error("Unsupported key format for local operations"); - } - - return result.slice(0, -1); // Removing the last new line -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/crypto-browser.mts b/sdk/keyvault/keyvault-keys/src/cryptography/crypto-browser.mts deleted file mode 100644 index 2d21ff26f922..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/crypto-browser.mts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { LocalCryptographyUnsupportedError } from "./models.js"; - -/** - * @internal - * Use the platform-local hashing functionality - */ -export async function createHash(_algorithm: string, _data: Uint8Array): Promise { - throw new LocalCryptographyUnsupportedError( - "Our libraries don't currently support browser hashing", - ); -} - -/** - * @internal - * Use the platform-local verify functionality - */ -export function createVerify(_algorithm: string, _data: Uint8Array): never { - throw new LocalCryptographyUnsupportedError( - "Our libraries don't currently support browser hashing", - ); -} - -/** - * @internal - * Use the platform-local randomBytes functionality - */ -export function randomBytes(_length: number): Uint8Array { - throw new LocalCryptographyUnsupportedError( - "Our libraries don't currently support browser crypto", - ); -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/crypto.ts b/sdk/keyvault/keyvault-keys/src/cryptography/crypto.ts deleted file mode 100644 index a3b44ef69f0c..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/crypto.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Verify } from "node:crypto"; -import { - createHash as cryptoCreateHash, - createVerify as cryptoCreateVerify, - randomBytes as cryptoRandomBytes, -} from "node:crypto"; - -/** - * @internal - * Mapping between signature algorithms and their corresponding hash algorithms. Externally used for testing. - **/ -const algorithmToHashAlgorithm: { [s: string]: string } = { - ES256: "SHA256", - ES256K: "SHA256", - PS256: "SHA256", - RS256: "SHA256", - ES384: "SHA384", - PS384: "SHA384", - RS384: "SHA384", - ES512: "SHA512", - PS512: "SHA512", - RS512: "SHA512", -}; - -/** - * @internal - * Use the platform-local hashing functionality - */ -export async function createHash(algorithm: string, data: Uint8Array): Promise { - const hashAlgorithm = algorithmToHashAlgorithm[algorithm]; - if (!hashAlgorithm) { - throw new Error( - `Invalid algorithm ${algorithm} passed to createHash. Supported algorithms: ${Object.keys( - algorithmToHashAlgorithm, - ).join(", ")}`, - ); - } - const hash = cryptoCreateHash(hashAlgorithm); - hash.update(Buffer.from(data)); - const digest = hash.digest(); - return digest; -} - -/** - * @internal - * Use the platform-local verify functionality - */ -export function createVerify(algorithm: string, data: Uint8Array): Verify { - const verifyAlgorithm = algorithmToHashAlgorithm[algorithm]; - if (!verifyAlgorithm) { - throw new Error( - `Invalid algorithm ${algorithm} passed to createHash. Supported algorithms: ${Object.keys( - algorithmToHashAlgorithm, - ).join(", ")}`, - ); - } - const verifier = cryptoCreateVerify(verifyAlgorithm); - verifier.update(Buffer.from(data)); - verifier.end(); - return verifier; -} - -/** - * @internal - * Use the platform-local randomBytes functionality - */ -export function randomBytes(length: number): Uint8Array { - return cryptoRandomBytes(length); -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/models.ts b/sdk/keyvault/keyvault-keys/src/cryptography/models.ts deleted file mode 100644 index 616907c29e74..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/models.ts +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { OperationOptions } from "@azure-rest/core-client"; -import type { - DecryptOptions, - DecryptParameters, - DecryptResult, - EncryptOptions, - EncryptParameters, - EncryptResult, - KeyWrapAlgorithm, - SignOptions, - SignResult, - SignatureAlgorithm, - UnwrapKeyOptions, - UnwrapResult, - VerifyOptions, - VerifyResult, - WrapKeyOptions, - WrapResult, -} from "../index.js"; - -export class LocalCryptographyUnsupportedError extends Error {} - -/** - * The set of operations a {@link CryptographyProvider} supports. - * - * This corresponds to every single method on the interface so that providers - * can declare whether they support this method or not. - * - * Purposely more granular than {@link KnownKeyOperations} because some providers - * support verifyData but not verify. - * @internal - */ -export type CryptographyProviderOperation = - | "encrypt" - | "decrypt" - | "wrapKey" - | "unwrapKey" - | "sign" - | "signData" - | "verify" - | "verifyData"; - -/** - * - * Represents an object that can perform cryptography operations. - * @internal - */ -export interface CryptographyProvider { - /** - * Encrypts the given plaintext with the specified encryption parameters. - * @internal - * - * @param encryptParameters - The encryption parameters, keyed on the encryption algorithm chosen. - * @param options - Additional options. - */ - encrypt(encryptParameters: EncryptParameters, options?: EncryptOptions): Promise; - - /** - * Decrypts the given ciphertext with the specified decryption parameters. - * @internal - * - * @param decryptParameters - The decryption parameters. - * @param options - Additional options. - */ - decrypt(decryptParameters: DecryptParameters, options?: DecryptOptions): Promise; - - /** - * - * @param algorithm - The algorithm to check support for. - * @param operation - The {@link CryptographyProviderOperation} to check support for. - */ - isSupported(algorithm: string, operation: CryptographyProviderOperation): boolean; - - /** - * Wraps the given key using the specified cryptography algorithm - * @internal - * - * @param algorithm - The encryption algorithm to use to wrap the given key. - * @param keyToWrap - The key to wrap. - * @param options - Additional options. - */ - wrapKey( - algorithm: KeyWrapAlgorithm, - keyToWrap: Uint8Array, - options?: WrapKeyOptions, - ): Promise; - - /** - * Unwraps the given wrapped key using the specified cryptography algorithm - * @internal - * - * @param algorithm - The decryption algorithm to use to unwrap the key. - * @param encryptedKey - The encrypted key to unwrap. - * @param options - Additional options. - */ - unwrapKey( - algorithm: KeyWrapAlgorithm, - encryptedKey: Uint8Array, - options?: UnwrapKeyOptions, - ): Promise; - - /** - * Cryptographically sign the digest of a message - * @internal - * - * @param algorithm - The signing algorithm to use. - * @param digest - The digest of the data to sign. - * @param options - Additional options. - */ - sign( - algorithm: SignatureAlgorithm, - digest: Uint8Array, - options?: SignOptions, - ): Promise; - - /** - * Cryptographically sign a block of data - * @internal - * - * @param algorithm - The signing algorithm to use. - * @param data - The data to sign. - * @param options - Additional options. - */ - signData( - algorithm: SignatureAlgorithm, - data: Uint8Array, - options?: SignOptions, - ): Promise; - - /** - * Verify the signed message digest - * @internal - * - * @param algorithm - The signing algorithm to use to verify with. - * @param digest - The digest to verify. - * @param signature - The signature to verify the digest against. - * @param options - Additional options. - */ - verify( - algorithm: SignatureAlgorithm, - digest: Uint8Array, - signature: Uint8Array, - options?: VerifyOptions, - ): Promise; - - /** - * Verify the signed block of data - * @internal - * - * @param algorithm - The algorithm to use to verify with. - * @param data - The signed block of data to verify. - * @param signature - The signature to verify the block against. - * @param updatedOptions - Additional options. - */ - verifyData( - algorithm: string, - data: Uint8Array, - signature: Uint8Array, - updatedOptions: OperationOptions, - ): Promise; -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/remoteCryptographyProvider.ts b/sdk/keyvault/keyvault-keys/src/cryptography/remoteCryptographyProvider.ts deleted file mode 100644 index 8a7930d5d86b..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/remoteCryptographyProvider.ts +++ /dev/null @@ -1,433 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { TokenCredential } from "@azure/core-auth"; - -import type { - DecryptOptions, - DecryptParameters, - DecryptResult, - EncryptOptions, - EncryptParameters, - EncryptResult, - KeyWrapAlgorithm, - SignOptions, - SignResult, - UnwrapKeyOptions, - VerifyOptions, - VerifyResult, - WrapKeyOptions, - WrapResult, -} from "../cryptographyClientModels.js"; -import { SDK_VERSION } from "../constants.js"; -import type { UnwrapResult } from "../cryptographyClientModels.js"; -import type { KeyVaultClientOptionalParams } from "../generated/index.js"; -import { KeyVaultClient } from "../generated/index.js"; -import { parseKeyVaultKeyIdentifier } from "../identifier.js"; -import type { CryptographyClientOptions, GetKeyOptions, KeyVaultKey } from "../keysModels.js"; -import { LATEST_API_VERSION } from "../keysModels.js"; -import { getKeyFromKeyBundle } from "../transformations.js"; -import { createHash } from "./crypto.js"; -import type { CryptographyProvider, CryptographyProviderOperation } from "./models.js"; -import { logger } from "../log.js"; -import { keyVaultAuthenticationPolicy } from "@azure/keyvault-common"; -import { tracingClient } from "../tracing.js"; -import { bearerTokenAuthenticationPolicyName } from "@azure/core-rest-pipeline"; - -/** - * The remote cryptography provider is used to run crypto operations against KeyVault. - * @internal - */ -export class RemoteCryptographyProvider implements CryptographyProvider { - constructor( - key: string | KeyVaultKey, - credential: TokenCredential, - pipelineOptions: CryptographyClientOptions = {}, - ) { - this.key = key; - - let keyId: string; - if (typeof key === "string") { - keyId = key; - } else { - keyId = key.id!; - } - - try { - const parsed = parseKeyVaultKeyIdentifier(keyId); - if (parsed.name === "") { - throw new Error("Could not find 'name' of key in key URL"); - } - - if (!parsed.vaultUrl || parsed.vaultUrl === "") { - throw new Error("Could not find 'vaultUrl' of key in key URL"); - } - - this.vaultUrl = parsed.vaultUrl; - this.name = parsed.name; - this.version = parsed.version ?? ""; - - this.client = getOrInitializeClient(this.vaultUrl, credential, pipelineOptions); - } catch (err: any) { - logger.error(err); - - throw new Error(`${keyId} is not a valid Key Vault key ID`); - } - } - - // The remote client supports all algorithms and all operations. - isSupported(_algorithm: string, _operation: CryptographyProviderOperation): boolean { - return true; - } - - encrypt( - encryptParameters: EncryptParameters, - options: EncryptOptions = {}, - ): Promise { - const { algorithm, plaintext, ...params } = encryptParameters; - const requestOptions = { ...options, ...params }; - - return tracingClient.withSpan( - "RemoteCryptographyProvider.encrypt", - requestOptions, - async (updatedOptions) => { - const result = await this.client.encrypt( - this.name, - this.version, - { - algorithm, - value: plaintext, - aad: - "additionalAuthenticatedData" in encryptParameters - ? encryptParameters.additionalAuthenticatedData - : undefined, - iv: "iv" in encryptParameters ? encryptParameters.iv : undefined, - }, - updatedOptions, - ); - - return { - algorithm: encryptParameters.algorithm, - result: result.result!, - keyID: this.getKeyID(), - additionalAuthenticatedData: result.additionalAuthenticatedData, - authenticationTag: result.authenticationTag, - iv: result.iv, - }; - }, - ); - } - - decrypt( - decryptParameters: DecryptParameters, - options: DecryptOptions = {}, - ): Promise { - const { algorithm, ciphertext, ...params } = decryptParameters; - const requestOptions = { ...options, ...params }; - - return tracingClient.withSpan( - "RemoteCryptographyProvider.decrypt", - requestOptions, - async (updatedOptions) => { - const result = await this.client.decrypt( - this.name, - this.version, - { - algorithm, - value: ciphertext, - aad: - "additionalAuthenticatedData" in decryptParameters - ? decryptParameters.additionalAuthenticatedData - : undefined, - iv: "iv" in decryptParameters ? decryptParameters.iv : undefined, - tag: - "authenticationTag" in decryptParameters - ? decryptParameters.authenticationTag - : undefined, - }, - updatedOptions, - ); - return { - result: result.result!, - keyID: this.getKeyID(), - algorithm, - }; - }, - ); - } - - wrapKey( - algorithm: KeyWrapAlgorithm, - keyToWrap: Uint8Array, - options: WrapKeyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "RemoteCryptographyProvider.wrapKey", - options, - async (updatedOptions) => { - const result = await this.client.wrapKey( - this.name, - this.version, - { - algorithm, - value: keyToWrap, - }, - updatedOptions, - ); - - return { - result: result.result!, - algorithm, - keyID: this.getKeyID(), - }; - }, - ); - } - - unwrapKey( - algorithm: KeyWrapAlgorithm, - encryptedKey: Uint8Array, - options: UnwrapKeyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "RemoteCryptographyProvider.unwrapKey", - options, - async (updatedOptions) => { - const result = await this.client.unwrapKey( - this.name, - this.version, - { - algorithm, - value: encryptedKey, - }, - updatedOptions, - ); - - return { - result: result.result!, - algorithm, - keyID: this.getKeyID(), - }; - }, - ); - } - - sign(algorithm: string, digest: Uint8Array, options: SignOptions = {}): Promise { - return tracingClient.withSpan( - "RemoteCryptographyProvider.sign", - options, - async (updatedOptions) => { - const result = await this.client.sign( - this.name, - this.version, - { - algorithm, - value: digest, - }, - updatedOptions, - ); - - return { result: result.result!, algorithm, keyID: this.getKeyID() }; - }, - ); - } - - verifyData( - algorithm: string, - data: Uint8Array, - signature: Uint8Array, - options: VerifyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "RemoteCryptographyProvider.verifyData", - options, - async (updatedOptions) => { - const hash = await createHash(algorithm, data); - return this.verify(algorithm, hash, signature, updatedOptions); - }, - ); - } - - verify( - algorithm: string, - digest: Uint8Array, - signature: Uint8Array, - options: VerifyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "RemoteCryptographyProvider.verify", - options, - async (updatedOptions) => { - const response = await this.client.verify( - this.name, - this.version, - { - algorithm, - digest, - signature, - }, - updatedOptions, - ); - return { - result: response.value ? response.value : false, - keyID: this.getKeyID(), - }; - }, - ); - } - - signData(algorithm: string, data: Uint8Array, options: SignOptions = {}): Promise { - return tracingClient.withSpan( - "RemoteCryptographyProvider.signData", - options, - async (updatedOptions) => { - const digest = await createHash(algorithm, data); - const result = await this.client.sign( - this.name, - this.version, - { - algorithm, - value: digest, - }, - updatedOptions, - ); - return { result: result.result!, algorithm, keyID: this.getKeyID() }; - }, - ); - } - - /** - * The base URL to the vault. - */ - readonly vaultUrl: string; - - /** - * The ID of the key used to perform cryptographic operations for the client. - */ - get keyId(): string | undefined { - return this.getKeyID(); - } - - /** - * Gets the {@link KeyVaultKey} used for cryptography operations, fetching it - * from KeyVault if necessary. - * @param options - Additional options. - */ - getKey(options: GetKeyOptions = {}): Promise { - return tracingClient.withSpan( - "RemoteCryptographyProvider.getKey", - options, - async (updatedOptions) => { - if (typeof this.key === "string") { - if (!this.name || this.name === "") { - throw new Error("getKey requires a key with a name"); - } - const response = await this.client.getKey( - this.name, - options && options.version ? options.version : this.version ? this.version : "", - updatedOptions, - ); - this.key = getKeyFromKeyBundle(response); - } - return this.key; - }, - ); - } - - /** - * A reference to the auto-generated KeyVault HTTP client. - */ - private client: KeyVaultClient; - - /** - * A reference to the key used for the cryptographic operations. - * Based on what was provided to the CryptographyClient constructor, - * it can be either a string with the URL of a Key Vault Key, or an already parsed {@link KeyVaultKey}. - */ - private key: string | KeyVaultKey; - - /** - * Name of the key the client represents - */ - private name: string; - - /** - * Version of the key the client represents - */ - private version: string; - - /** - * Attempts to retrieve the ID of the key. - */ - private getKeyID(): string | undefined { - let kid; - if (typeof this.key !== "string") { - kid = this.key.id; - } else { - kid = this.key; - } - - return kid; - } -} - -/** - * A helper method to either get the passed down generated client or initialize a new one. - * An already constructed generated client may be passed down from {@link KeyClient} in which case we should reuse it. - * - * @internal - * @param credential - The credential to use when initializing a new client. - * @param options - The options for constructing a client or the underlying client if one already exists. - * @returns - A generated client instance - */ -function getOrInitializeClient( - vaultUrl: string, - credential: TokenCredential, - options: CryptographyClientOptions & { generatedClient?: KeyVaultClient }, -): KeyVaultClient { - if (options.generatedClient) { - return options.generatedClient; - } - - const libInfo = `azsdk-js-keyvault-keys/${SDK_VERSION}`; - - const userAgentOptions = options.userAgentOptions; - - options.userAgentOptions = { - userAgentPrefix: - userAgentOptions && userAgentOptions.userAgentPrefix - ? `${userAgentOptions.userAgentPrefix} ${libInfo}` - : libInfo, - }; - - const internalPipelineOptions: KeyVaultClientOptionalParams = { - ...options, - apiVersion: options.serviceVersion || LATEST_API_VERSION, - loggingOptions: { - logger: logger.info, - additionalAllowedHeaderNames: [ - "x-ms-keyvault-region", - "x-ms-keyvault-network-info", - "x-ms-keyvault-service-version", - ], - }, - }; - - const client = new KeyVaultClient(vaultUrl, credential, internalPipelineOptions); - - client.pipeline.removePolicy({ name: bearerTokenAuthenticationPolicyName }); - client.pipeline.addPolicy(keyVaultAuthenticationPolicy(credential, options)); - // Workaround for: https://github.com/Azure/azure-sdk-for-js/issues/31843 - client.pipeline.addPolicy({ - name: "ContentTypePolicy", - sendRequest(request, next) { - const contentType = request.headers.get("Content-Type") ?? ""; - if (contentType.startsWith("application/json")) { - request.headers.set("Content-Type", "application/json"); - } - return next(request); - }, - }); - - return client; -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/rsaCryptographyProvider-browser.mts b/sdk/keyvault/keyvault-keys/src/cryptography/rsaCryptographyProvider-browser.mts deleted file mode 100644 index 7e33c09265a2..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/rsaCryptographyProvider-browser.mts +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { CryptographyProvider} from "./models.js"; -import { LocalCryptographyUnsupportedError } from "./models.js"; - -/** - * The browser replacement of the RsaCryptographyProvider. Since we do not - * support local cryptography in the browser this replacement always returns false - * for `supportsAlgorithm` and `supportsOperation` so that these methods should - * never be called. - */ -export class RsaCryptographyProvider implements CryptographyProvider { - encrypt(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } - decrypt(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } - - /** - * Browser RSA Provider does not support any algorithms or operations. - */ - isSupported(): boolean { - return false; - } - - wrapKey(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } - - unwrapKey(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } - - sign(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } - - signData(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } - - verify(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } - - verifyData(): never { - throw new LocalCryptographyUnsupportedError( - "RSA Local cryptography is not supported in the browser.", - ); - } -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptography/rsaCryptographyProvider.ts b/sdk/keyvault/keyvault-keys/src/cryptography/rsaCryptographyProvider.ts deleted file mode 100644 index f0979362a663..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptography/rsaCryptographyProvider.ts +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { RSA_PKCS1_OAEP_PADDING, RSA_PKCS1_PADDING } from "constants"; -import { publicEncrypt } from "node:crypto"; -import { createVerify } from "./crypto.js"; -import type { - DecryptOptions, - DecryptParameters, - DecryptResult, - EncryptOptions, - EncryptParameters, - EncryptResult, - JsonWebKey, - KeyWrapAlgorithm, - SignOptions, - SignResult, - SignatureAlgorithm, - UnwrapKeyOptions, - UnwrapResult, - VerifyOptions, - VerifyResult, - WrapKeyOptions, - WrapResult, -} from "../index.js"; -import { convertJWKtoPEM } from "./conversions.js"; -import type { CryptographyProvider, CryptographyProviderOperation } from "./models.js"; -import { LocalCryptographyUnsupportedError } from "./models.js"; - -/** - * An RSA cryptography provider supporting RSA algorithms. - */ -export class RsaCryptographyProvider implements CryptographyProvider { - constructor(key: JsonWebKey) { - this.key = key; - } - - isSupported(algorithm: string, operation: CryptographyProviderOperation): boolean { - return ( - this.applicableAlgorithms.includes(algorithm) && this.applicableOperations.includes(operation) - ); - } - - encrypt(encryptParameters: EncryptParameters, _options?: EncryptOptions): Promise { - this.ensureValid(); - const keyPEM = convertJWKtoPEM(this.key); - - const padding = - encryptParameters.algorithm === "RSA1_5" ? RSA_PKCS1_PADDING : RSA_PKCS1_OAEP_PADDING; - - return Promise.resolve({ - algorithm: encryptParameters.algorithm, - keyID: this.key.kid, - result: publicEncrypt( - { key: keyPEM, padding: padding }, - Buffer.from(encryptParameters.plaintext), - ), - }); - } - - decrypt( - _decryptParameters: DecryptParameters, - _options?: DecryptOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Decrypting using a local JsonWebKey is not supported.", - ); - } - - wrapKey( - algorithm: KeyWrapAlgorithm, - keyToWrap: Uint8Array, - _options?: WrapKeyOptions, - ): Promise { - this.ensureValid(); - const keyPEM = convertJWKtoPEM(this.key); - - const padding = algorithm === "RSA1_5" ? RSA_PKCS1_PADDING : RSA_PKCS1_OAEP_PADDING; - - return Promise.resolve({ - algorithm: algorithm as KeyWrapAlgorithm, - result: publicEncrypt({ key: keyPEM, padding }, Buffer.from(keyToWrap)), - keyID: this.key.kid, - }); - } - - unwrapKey( - _algorithm: KeyWrapAlgorithm, - _encryptedKey: Uint8Array, - _options?: UnwrapKeyOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Unwrapping a key using a local JsonWebKey is not supported.", - ); - } - - sign( - _algorithm: SignatureAlgorithm, - _digest: Uint8Array, - _options?: SignOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Signing a digest using a local JsonWebKey is not supported.", - ); - } - - signData( - _algorithm: SignatureAlgorithm, - _data: Uint8Array, - _options?: SignOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Signing a block of data using a local JsonWebKey is not supported.", - ); - } - - async verify( - _algorithm: SignatureAlgorithm, - _digest: Uint8Array, - _signature: Uint8Array, - _options?: VerifyOptions, - ): Promise { - throw new LocalCryptographyUnsupportedError( - "Verifying a digest using a local JsonWebKey is not supported.", - ); - } - - verifyData( - algorithm: SignatureAlgorithm, - data: Uint8Array, - signature: Uint8Array, - _options?: VerifyOptions, - ): Promise { - this.ensureValid(); - const keyPEM = convertJWKtoPEM(this.key); - - const verifier = createVerify(algorithm, data); - return Promise.resolve({ - result: verifier.verify(keyPEM, Buffer.from(signature)), - keyID: this.key.kid, - }); - } - - /** - * The {@link JsonWebKey} used to perform crypto operations. - */ - private key: JsonWebKey; - - /** - * The set of algorithms this provider supports - */ - private applicableAlgorithms: string[] = [ - "RSA1_5", - "RSA-OAEP", - "PS256", - "RS256", - "PS384", - "RS384", - "PS512", - "RS512", - ]; - - /** - * The set of operations this provider supports - */ - private applicableOperations: CryptographyProviderOperation[] = [ - "encrypt", - "wrapKey", - "verifyData", - ]; - - /** - * Mapping between signature algorithms and their corresponding hash algorithms. Externally used for testing. - * @internal - */ - signatureAlgorithmToHashAlgorithm: { [s: string]: string } = { - PS256: "SHA256", - RS256: "SHA256", - PS384: "SHA384", - RS384: "SHA384", - PS512: "SHA512", - RS512: "SHA512", - }; - - private ensureValid(): void { - if ( - this.key && - this.key.kty?.toUpperCase() !== "RSA" && - this.key.kty?.toUpperCase() !== "RSA-HSM" - ) { - throw new Error("Key type does not match the algorithm RSA"); - } - } -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptographyClient.ts b/sdk/keyvault/keyvault-keys/src/cryptographyClient.ts deleted file mode 100644 index b584c825aa8f..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptographyClient.ts +++ /dev/null @@ -1,672 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { OperationOptions } from "@azure-rest/core-client"; -import type { TokenCredential } from "@azure/core-auth"; -import type { - CryptographyClientOptions, - GetKeyOptions, - JsonWebKey, - KeyOperation, - KeyVaultKey, -} from "./keysModels.js"; -import { KnownKeyOperations } from "./keysModels.js"; -import type { - AesCbcEncryptParameters, - AesCbcEncryptionAlgorithm, - CryptographyClientKey, - DecryptOptions, - DecryptParameters, - DecryptResult, - EncryptOptions, - EncryptParameters, - EncryptResult, - EncryptionAlgorithm, - KeyWrapAlgorithm, - SignOptions, - SignResult, - SignatureAlgorithm, - UnwrapKeyOptions, - UnwrapResult, - VerifyOptions, - VerifyResult, - WrapKeyOptions, - WrapResult, -} from "./cryptographyClientModels.js"; -import { RemoteCryptographyProvider } from "./cryptography/remoteCryptographyProvider.js"; -import { randomBytes } from "./cryptography/crypto.js"; -import type { CryptographyProvider, CryptographyProviderOperation } from "./cryptography/models.js"; -import { RsaCryptographyProvider } from "./cryptography/rsaCryptographyProvider.js"; -import { AesCryptographyProvider } from "./cryptography/aesCryptographyProvider.js"; -import { tracingClient } from "./tracing.js"; -import { isRestError } from "@azure/core-rest-pipeline"; -import { logger } from "./log.js"; - -/** - * A client used to perform cryptographic operations on an Azure Key vault key - * or a local {@link JsonWebKey}. - */ -export class CryptographyClient { - /** - * The key the CryptographyClient currently holds. - */ - private key: CryptographyClientKey; - - /** - * The remote provider, which would be undefined if used in local mode. - */ - private remoteProvider?: RemoteCryptographyProvider; - - /** - * Constructs a new instance of the Cryptography client for the given key - * - * Example usage: - * ```ts - * import { KeyClient, CryptographyClient } from "@azure/keyvault-keys"; - * import { DefaultAzureCredential } from "@azure/identity"; - * - * let vaultUrl = `https://.vault.azure.net`; - * let credentials = new DefaultAzureCredential(); - * - * let keyClient = new KeyClient(vaultUrl, credentials); - * let keyVaultKey = await keyClient.getKey("MyKey"); - * - * let client = new CryptographyClient(keyVaultKey.id, credentials); - * // or - * let client = new CryptographyClient(keyVaultKey, credentials); - * ``` - * @param key - The key to use during cryptography tasks. You can also pass the identifier of the key i.e its url here. - * @param credential - An object that implements the `TokenCredential` interface used to authenticate requests to the service. Use the \@azure/identity package to create a credential that suits your needs. - * @param pipelineOptions - Pipeline options used to configure Key Vault API requests. - * Omit this parameter to use the default pipeline configuration. - */ - constructor( - key: string | KeyVaultKey, - credential: TokenCredential, - pipelineOptions?: CryptographyClientOptions, - ); - /** - * Constructs a new instance of the Cryptography client for the given key in local mode. - * - * Example usage: - * ```ts - * import { CryptographyClient } from "@azure/keyvault-keys"; - * - * const jsonWebKey: JsonWebKey = { - * // ... - * }; - * const client = new CryptographyClient(jsonWebKey); - * ``` - * @param key - The JsonWebKey to use during cryptography operations. - */ - constructor(key: JsonWebKey); - /** - * Internal constructor implementation for either local or Key Vault backed keys. - * @param key - The key to use during cryptography tasks. - * @param credential - Teh credential to use when constructing a Key Vault Cryptography client. - */ - constructor( - key: string | KeyVaultKey | JsonWebKey, - credential?: TokenCredential, - pipelineOptions: CryptographyClientOptions = {}, - ) { - if (typeof key === "string") { - // Key URL for remote-local operations. - this.key = { - kind: "identifier", - value: key, - }; - this.remoteProvider = new RemoteCryptographyProvider(key, credential!, pipelineOptions); - } else if ("name" in key) { - // KeyVault key for remote-local operations. - this.key = { - kind: "KeyVaultKey", - value: key, - }; - this.remoteProvider = new RemoteCryptographyProvider(key, credential!, pipelineOptions); - } else { - // JsonWebKey for local-only operations. - this.key = { - kind: "JsonWebKey", - value: key, - }; - } - } - - /** - * The base URL to the vault. If a local {@link JsonWebKey} is used vaultUrl will be empty. - */ - get vaultUrl(): string { - return this.remoteProvider?.vaultUrl || ""; - } - - /** - * The ID of the key used to perform cryptographic operations for the client. - */ - get keyID(): string | undefined { - if (this.key.kind === "identifier" || this.key.kind === "remoteOnlyIdentifier") { - return this.key.value; - } else if (this.key.kind === "KeyVaultKey") { - return this.key.value.id; - } else { - return this.key.value.kid; - } - } - - /** - * Encrypts the given plaintext with the specified encryption parameters. - * Depending on the algorithm set in the encryption parameters, the set of possible encryption parameters will change. - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.encrypt({ algorithm: "RSA1_5", plaintext: Buffer.from("My Message")}); - * let result = await client.encrypt({ algorithm: "A256GCM", plaintext: Buffer.from("My Message"), additionalAuthenticatedData: Buffer.from("My authenticated data")}); - * ``` - * @param encryptParameters - The encryption parameters, keyed on the encryption algorithm chosen. - * @param options - Additional options. - */ - public encrypt( - encryptParameters: EncryptParameters, - options?: EncryptOptions, - ): Promise; - /** - * Encrypts the given plaintext with the specified cryptography algorithm - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.encrypt("RSA1_5", Buffer.from("My Message")); - * ``` - * @param algorithm - The algorithm to use. - * @param plaintext - The text to encrypt. - * @param options - Additional options. - * @deprecated Use `encrypt({ algorithm, plaintext }, options)` instead. - */ - public encrypt( - algorithm: EncryptionAlgorithm, - plaintext: Uint8Array, - options?: EncryptOptions, - ): Promise; - public encrypt( - ...args: - | [EncryptParameters, EncryptOptions?] - | [EncryptionAlgorithm, Uint8Array, EncryptOptions?] - ): Promise { - const [parameters, options] = this.disambiguateEncryptArguments(args); - return tracingClient.withSpan("CryptographyClient.encrypt", options, async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.Encrypt); - this.initializeIV(parameters); - const provider = await this.getProvider("encrypt", parameters.algorithm, updatedOptions); - try { - return provider.encrypt(parameters, updatedOptions); - } catch (error: any) { - if (this.remoteProvider) { - return this.remoteProvider.encrypt(parameters, updatedOptions); - } - throw error; - } - }); - } - - private initializeIV(parameters: EncryptParameters): void { - // For AES-GCM the service **must** generate the IV, so we only populate it for AES-CBC - const algorithmsRequiringIV: AesCbcEncryptionAlgorithm[] = [ - "A128CBC", - "A128CBCPAD", - "A192CBC", - "A192CBCPAD", - "A256CBC", - "A256CBCPAD", - ]; - - if (parameters.algorithm in algorithmsRequiringIV) { - try { - const cbcParams = parameters as AesCbcEncryptParameters; - if (!cbcParams.iv) { - cbcParams.iv = randomBytes(16); - } - } catch (e: any) { - throw new Error( - `Unable to initialize IV for algorithm ${parameters.algorithm}. You may pass a valid IV to avoid this error. Error: ${e.message}`, - ); - } - } - } - - /** - * Standardizes the arguments of multiple overloads into a single shape. - * @param args - The encrypt arguments - */ - private disambiguateEncryptArguments( - args: [EncryptParameters, EncryptOptions?] | [string, Uint8Array, EncryptOptions?], - ): [EncryptParameters, EncryptOptions] { - if (typeof args[0] === "string") { - // Sample shape: ["RSA1_5", buffer, options] - return [ - { - algorithm: args[0], - plaintext: args[1], - } as EncryptParameters, - args[2] || {}, - ]; - } else { - // Sample shape: [{ algorithm: "RSA1_5", plaintext: buffer }, options] - return [args[0], (args[1] || {}) as EncryptOptions]; - } - } - - /** - * Decrypts the given ciphertext with the specified decryption parameters. - * Depending on the algorithm used in the decryption parameters, the set of possible decryption parameters will change. - * - * Microsoft recommends you not use CBC without first ensuring the integrity of the ciphertext using, for example, an HMAC. See https://learn.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.decrypt({ algorithm: "RSA1_5", ciphertext: encryptedBuffer }); - * let result = await client.decrypt({ algorithm: "A256GCM", iv: ivFromEncryptResult, authenticationTag: tagFromEncryptResult }); - * ``` - * @param decryptParameters - The decryption parameters. - * @param options - Additional options. - */ - public async decrypt( - decryptParameters: DecryptParameters, - options?: DecryptOptions, - ): Promise; - /** - * Decrypts the given ciphertext with the specified cryptography algorithm - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.decrypt("RSA1_5", encryptedBuffer); - * ``` - * - * Microsoft recommends you not use CBC without first ensuring the integrity of the ciphertext using, for example, an HMAC. See https://learn.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param algorithm - The algorithm to use. - * @param ciphertext - The text to decrypt. - * @param options - Additional options. - * @deprecated Use `decrypt({ algorithm, ciphertext }, options)` instead. - */ - public decrypt( - algorithm: EncryptionAlgorithm, - ciphertext: Uint8Array, - options?: DecryptOptions, - ): Promise; - public decrypt( - ...args: - | [DecryptParameters, DecryptOptions?] - | [EncryptionAlgorithm, Uint8Array, DecryptOptions?] - ): Promise { - const [parameters, options] = this.disambiguateDecryptArguments(args); - - return tracingClient.withSpan("CryptographyClient.decrypt", options, async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.Decrypt); - const provider = await this.getProvider("decrypt", parameters.algorithm, updatedOptions); - try { - return provider.decrypt(parameters, updatedOptions); - } catch (error: any) { - if (this.remoteProvider) { - return this.remoteProvider.decrypt(parameters, updatedOptions); - } - throw error; - } - }); - } - - /** - * Standardizes the arguments of multiple overloads into a single shape. - * @param args - The decrypt arguments - */ - private disambiguateDecryptArguments( - args: [DecryptParameters, DecryptOptions?] | [string, Uint8Array, DecryptOptions?], - ): [DecryptParameters, DecryptOptions] { - if (typeof args[0] === "string") { - // Sample shape: ["RSA1_5", encryptedBuffer, options] - return [ - { - algorithm: args[0], - ciphertext: args[1], - } as DecryptParameters, - args[2] || {}, - ]; - } else { - // Sample shape: [{ algorithm: "RSA1_5", ciphertext: encryptedBuffer }, options] - return [args[0], (args[1] || {}) as DecryptOptions]; - } - } - - /** - * Wraps the given key using the specified cryptography algorithm - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.wrapKey("RSA1_5", keyToWrap); - * ``` - * @param algorithm - The encryption algorithm to use to wrap the given key. - * @param key - The key to wrap. - * @param options - Additional options. - */ - public wrapKey( - algorithm: KeyWrapAlgorithm, - key: Uint8Array, - options: WrapKeyOptions = {}, - ): Promise { - return tracingClient.withSpan("CryptographyClient.wrapKey", options, async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.WrapKey); - const provider = await this.getProvider("wrapKey", algorithm, updatedOptions); - try { - return provider.wrapKey(algorithm, key, updatedOptions); - } catch (err: any) { - if (this.remoteProvider) { - return this.remoteProvider.wrapKey(algorithm, key, options); - } - throw err; - } - }); - } - - /** - * Unwraps the given wrapped key using the specified cryptography algorithm - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.unwrapKey("RSA1_5", keyToUnwrap); - * ``` - * @param algorithm - The decryption algorithm to use to unwrap the key. - * @param encryptedKey - The encrypted key to unwrap. - * @param options - Additional options. - */ - public unwrapKey( - algorithm: KeyWrapAlgorithm, - encryptedKey: Uint8Array, - options: UnwrapKeyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "CryptographyClient.unwrapKey", - options, - async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.UnwrapKey); - const provider = await this.getProvider("unwrapKey", algorithm, updatedOptions); - try { - return provider.unwrapKey(algorithm, encryptedKey, updatedOptions); - } catch (err: any) { - if (this.remoteProvider) { - return this.remoteProvider.unwrapKey(algorithm, encryptedKey, options); - } - throw err; - } - }, - ); - } - - /** - * Cryptographically sign the digest of a message - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.sign("RS256", digest); - * ``` - * @param algorithm - The signing algorithm to use. - * @param digest - The digest of the data to sign. - * @param options - Additional options. - */ - public sign( - algorithm: SignatureAlgorithm, - digest: Uint8Array, - options: SignOptions = {}, - ): Promise { - return tracingClient.withSpan("CryptographyClient.sign", options, async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.Sign); - const provider = await this.getProvider("sign", algorithm, updatedOptions); - try { - return provider.sign(algorithm, digest, updatedOptions); - } catch (err: any) { - if (this.remoteProvider) { - return this.remoteProvider.sign(algorithm, digest, updatedOptions); - } - throw err; - } - }); - } - - /** - * Verify the signed message digest - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.verify("RS256", signedDigest, signature); - * ``` - * @param algorithm - The signing algorithm to use to verify with. - * @param digest - The digest to verify. - * @param signature - The signature to verify the digest against. - * @param options - Additional options. - */ - public verify( - algorithm: SignatureAlgorithm, - digest: Uint8Array, - signature: Uint8Array, - options: VerifyOptions = {}, - ): Promise { - return tracingClient.withSpan("CryptographyClient.verify", options, async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.Verify); - const provider = await this.getProvider("verify", algorithm, updatedOptions); - try { - return provider.verify(algorithm, digest, signature, updatedOptions); - } catch (err: any) { - if (this.remoteProvider) { - return this.remoteProvider.verify(algorithm, digest, signature, updatedOptions); - } - throw err; - } - }); - } - - /** - * Cryptographically sign a block of data - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.signData("RS256", message); - * ``` - * @param algorithm - The signing algorithm to use. - * @param data - The data to sign. - * @param options - Additional options. - */ - public signData( - algorithm: SignatureAlgorithm, - data: Uint8Array, - // eslint-disable-next-line @azure/azure-sdk/ts-naming-options - options: SignOptions = {}, - ): Promise { - return tracingClient.withSpan( - "CryptographyClient.signData", - options, - async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.Sign); - const provider = await this.getProvider("signData", algorithm, updatedOptions); - try { - return provider.signData(algorithm, data, updatedOptions); - } catch (err: any) { - if (this.remoteProvider) { - return this.remoteProvider.signData(algorithm, data, options); - } - throw err; - } - }, - ); - } - - /** - * Verify the signed block of data - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.verifyData("RS256", signedMessage, signature); - * ``` - * @param algorithm - The algorithm to use to verify with. - * @param data - The signed block of data to verify. - * @param signature - The signature to verify the block against. - * @param options - Additional options. - */ - public verifyData( - algorithm: SignatureAlgorithm, - data: Uint8Array, - signature: Uint8Array, - // eslint-disable-next-line @azure/azure-sdk/ts-naming-options - options: VerifyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "CryptographyClient.verifyData", - options, - async (updatedOptions) => { - this.ensureValid(await this.fetchKey(updatedOptions), KnownKeyOperations.Verify); - const provider = await this.getProvider("verifyData", algorithm, updatedOptions); - try { - return provider.verifyData(algorithm, data, signature, updatedOptions); - } catch (err: any) { - if (this.remoteProvider) { - return this.remoteProvider.verifyData(algorithm, data, signature, updatedOptions); - } - throw err; - } - }, - ); - } - - /** - * Retrieves the {@link JsonWebKey} from the Key Vault, if possible. Returns undefined if the key could not be retrieved due to insufficient permissions. - * - * Example usage: - * ```ts - * let client = new CryptographyClient(keyVaultKey, credentials); - * let result = await client.getKeyMaterial(); - * ``` - */ - private async getKeyMaterial(options: GetKeyOptions): Promise { - const key = await this.fetchKey(options); - - switch (key.kind) { - case "JsonWebKey": - return key.value; - case "KeyVaultKey": - return key.value.key!; - default: - return undefined; - } - } - - /** - * Returns the underlying key used for cryptographic operations. - * If needed, attempts to fetch the key from KeyVault and exchanges the ID for the actual key. - * @param options - The additional options. - */ - private async fetchKey(options: T): Promise { - if (this.key.kind === "identifier") { - // Exchange the identifier with the actual key when needed - let key: KeyVaultKey | undefined; - try { - key = await this.remoteProvider!.getKey(options); - } catch (e: unknown) { - if (isRestError(e) && e.statusCode === 403) { - // If we don't have permission to get the key, we'll fall back to using the remote provider. - // Marking the key as a remoteOnlyIdentifier will ensure that we don't attempt to fetch the key again. - logger.verbose( - `Permission denied to get key ${this.key.value}. Falling back to remote operation.`, - ); - this.key = { kind: "remoteOnlyIdentifier", value: this.key.value }; - } else { - throw e; - } - } - - if (key) { - this.key = { kind: "KeyVaultKey", value: key }; - } - } - - return this.key; - } - - private providers?: CryptographyProvider[]; - /** - * Gets the provider that support this algorithm and operation. - * The available providers are ordered by priority such that the first provider that supports this - * operation is the one we should use. - * @param operation - The {@link KeyOperation}. - * @param algorithm - The algorithm to use. - */ - private async getProvider( - operation: CryptographyProviderOperation, - algorithm: string, - options: T, - ): Promise { - if (!this.providers) { - const keyMaterial = await this.getKeyMaterial(options); - this.providers = []; - - // Add local crypto providers as needed - if (keyMaterial) { - this.providers.push( - new RsaCryptographyProvider(keyMaterial), - new AesCryptographyProvider(keyMaterial), - ); - } - - // If the remote provider exists, we're in hybrid-mode. Otherwise we're in local-only mode. - // If we're in hybrid mode the remote provider is used as a catch-all and should be last in the list. - if (this.remoteProvider) { - this.providers.push(this.remoteProvider); - } - } - - const providers = this.providers.filter((p) => p.isSupported(algorithm, operation)); - - if (providers.length === 0) { - throw new Error( - `Unable to support operation: "${operation}" with algorithm: "${algorithm}" ${ - this.key.kind === "JsonWebKey" ? "using a local JsonWebKey" : "" - }`, - ); - } - - // Return the first provider that supports this request - return providers[0]; - } - - private ensureValid(key: CryptographyClientKey, operation?: KeyOperation): void { - if (key.kind === "KeyVaultKey") { - const keyOps = key.value.keyOperations; - const { notBefore, expiresOn } = key.value.properties; - const now = new Date(); - - // Check KeyVault Key Expiration - if (notBefore && now < notBefore) { - throw new Error(`Key ${key.value.id} can't be used before ${notBefore.toISOString()}`); - } - - if (expiresOn && now > expiresOn) { - throw new Error(`Key ${key.value.id} expired at ${expiresOn.toISOString()}`); - } - - // Check Key operations - if (operation && keyOps && !keyOps?.includes(operation)) { - throw new Error(`Operation ${operation} is not supported on key ${key.value.id}`); - } - } else if (key.kind === "JsonWebKey") { - // Check JsonWebKey Key operations - if (operation && key.value.keyOps && !key.value.keyOps?.includes(operation)) { - throw new Error(`Operation ${operation} is not supported on key ${key.value.kid}`); - } - } - } -} diff --git a/sdk/keyvault/keyvault-keys/src/cryptographyClientModels.ts b/sdk/keyvault/keyvault-keys/src/cryptographyClientModels.ts deleted file mode 100644 index 4d1195c79dd0..000000000000 --- a/sdk/keyvault/keyvault-keys/src/cryptographyClientModels.ts +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { CryptographyOptions, KeyVaultKey } from "./keysModels.js"; - -import type { JsonWebKey } from "./generated/models/index.js"; -import { - JsonWebKeyEncryptionAlgorithm as EncryptionAlgorithm, - JsonWebKeyCurveName as KeyCurveName, - JsonWebKeySignatureAlgorithm as SignatureAlgorithm, -} from "./generated/models/index.js"; - -export { KeyCurveName, EncryptionAlgorithm, SignatureAlgorithm }; - -/** Known values of {@link KeyCurveName} that the service accepts. */ -export enum KnownKeyCurveNames { - /** The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. */ - P256 = "P-256", - /** The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. */ - P384 = "P-384", - /** The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. */ - P521 = "P-521", - /** The SECG SECP256K1 elliptic curve. */ - P256K = "P-256K", -} - -/** Known values of {@link SignatureAlgorithm} that the service accepts. */ -export enum KnownSignatureAlgorithms { - /** RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https://tools.ietf.org/html/rfc7518 */ - PS256 = "PS256", - /** RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https://tools.ietf.org/html/rfc7518 */ - PS384 = "PS384", - /** RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https://tools.ietf.org/html/rfc7518 */ - PS512 = "PS512", - /** RSASSA-PKCS1-v1_5 using SHA-256, as described in https://tools.ietf.org/html/rfc7518 */ - RS256 = "RS256", - /** RSASSA-PKCS1-v1_5 using SHA-384, as described in https://tools.ietf.org/html/rfc7518 */ - RS384 = "RS384", - /** RSASSA-PKCS1-v1_5 using SHA-512, as described in https://tools.ietf.org/html/rfc7518 */ - RS512 = "RS512", - /** Reserved */ - Rsnull = "RSNULL", - /** ECDSA using P-256 and SHA-256, as described in https://tools.ietf.org/html/rfc7518. */ - ES256 = "ES256", - /** ECDSA using P-384 and SHA-384, as described in https://tools.ietf.org/html/rfc7518 */ - ES384 = "ES384", - /** ECDSA using P-521 and SHA-512, as described in https://tools.ietf.org/html/rfc7518 */ - ES512 = "ES512", - /** ECDSA using P-256K and SHA-256, as described in https://tools.ietf.org/html/rfc7518 */ - ES256K = "ES256K", -} - -/** Known values of {@link EncryptionAlgorithm} that the service accepts. */ -export enum KnownEncryptionAlgorithms { - /** Encryption Algorithm - RSA-OAEP */ - RSAOaep = "RSA-OAEP", - /** Encryption Algorithm - RSA-OAEP-256 */ - RSAOaep256 = "RSA-OAEP-256", - /** Encryption Algorithm - RSA1_5 */ - RSA15 = "RSA1_5", - /** Encryption Algorithm - A128GCM */ - A128GCM = "A128GCM", - /** Encryption Algorithm - A192GCM */ - A192GCM = "A192GCM", - /** Encryption Algorithm - A256GCM */ - A256GCM = "A256GCM", - /** Encryption Algorithm - A128KW */ - A128KW = "A128KW", - /** Encryption Algorithm - A192KW */ - A192KW = "A192KW", - /** Encryption Algorithm - A256KW */ - A256KW = "A256KW", - /** Encryption Algorithm - A128CBC */ - A128CBC = "A128CBC", - /** Encryption Algorithm - A192CBC */ - A192CBC = "A192CBC", - /** Encryption Algorithm - A256CBC */ - A256CBC = "A256CBC", - /** Encryption Algorithm - A128CBCPAD */ - A128Cbcpad = "A128CBCPAD", - /** Encryption Algorithm - A192CBCPAD */ - A192Cbcpad = "A192CBCPAD", - /** Encryption Algorithm - A256CBCPAD */ - A256Cbcpad = "A256CBCPAD", -} - -/** - * Supported algorithms for key wrapping/unwrapping - */ -export type KeyWrapAlgorithm = - | "A128KW" - | "A192KW" - | "A256KW" - | "RSA-OAEP" - | "RSA-OAEP-256" - | "RSA1_5"; - -/** - * Result of the {@link encrypt} operation. - */ -export interface EncryptResult { - /** - * Result of the {@link encrypt} operation in bytes. - */ - result: Uint8Array; - /** - * The {@link EncryptionAlgorithm} used to encrypt the data. - */ - algorithm: EncryptionAlgorithm; - /** - * The ID of the Key Vault Key used to encrypt the data. - */ - keyID?: string; - /** - * The initialization vector used for encryption. - */ - iv?: Uint8Array; - /** - * The authentication tag resulting from encryption with a symmetric key including A128GCM, A192GCM, and A256GCM. - */ - authenticationTag?: Uint8Array; - /** - * Additional data that is authenticated during decryption but not encrypted. - */ - additionalAuthenticatedData?: Uint8Array; -} - -/** - * Result of the {@link wrap} operation. - */ -export interface WrapResult { - /** - * Result of the {@link wrap} operation in bytes. - */ - result: Uint8Array; - /** - * The ID of the Key Vault Key used to wrap the data. - */ - keyID?: string; - /** - * The {@link EncryptionAlgorithm} used to wrap the data. - */ - algorithm: KeyWrapAlgorithm; -} - -/** - * Result of the {@link unwrap} operation. - */ -export interface UnwrapResult { - /** - * Result of the {@link unwrap} operation in bytes. - */ - result: Uint8Array; - /** - * The ID of the Key Vault Key used to unwrap the data. - */ - keyID?: string; - /** - * The {@link KeyWrapAlgorithm} used to unwrap the data. - */ - algorithm: KeyWrapAlgorithm; -} -/** - * Result of the {@link decrypt} operation. - */ -export interface DecryptResult { - /** - * Result of the {@link decrypt} operation in bytes. - */ - result: Uint8Array; - /** - * The ID of the Key Vault Key used to decrypt the encrypted data. - */ - keyID?: string; - /** - * The {@link EncryptionAlgorithm} used to decrypt the encrypted data. - */ - algorithm: EncryptionAlgorithm; -} - -/** - * Result of the {@link sign} operation. - */ -export interface SignResult { - /** - * Result of the {@link sign} operation in bytes. - */ - result: Uint8Array; - /** - * The ID of the Key Vault Key used to sign the data. - */ - keyID?: string; - /** - * The {@link EncryptionAlgorithm} used to sign the data. - */ - algorithm: SignatureAlgorithm; -} - -/** - * Result of the {@link verify} operation. - */ -export interface VerifyResult { - /** - * Result of the {@link verify} operation in bytes. - */ - result: boolean; - /** - * The ID of the Key Vault Key used to verify the data. - */ - keyID?: string; -} - -/** - * Options for {@link encrypt}. - */ -export interface EncryptOptions extends CryptographyOptions {} - -/** - * Options for {@link decrypt}. - */ -export interface DecryptOptions extends CryptographyOptions {} - -/** - * Options for {@link sign}. - */ -export interface SignOptions extends CryptographyOptions {} - -/** - * Options for {@link verify}. - */ -export interface VerifyOptions extends CryptographyOptions {} - -/** - * Options for {@link verifyData} - */ -export interface VerifyDataOptions extends CryptographyOptions {} - -/** - * Options for {@link wrapKey}. - */ -export interface WrapKeyOptions extends CryptographyOptions {} - -/** - * Options for {@link unwrapKey}. - */ -export interface UnwrapKeyOptions extends CryptographyOptions {} - -/** - * A union type representing all supported RSA encryption algorithms. - */ -export type RsaEncryptionAlgorithm = "RSA1_5" | "RSA-OAEP" | "RSA-OAEP-256"; - -/** - * Encryption parameters for RSA encryption algorithms. - */ -export interface RsaEncryptParameters { - /** - * The encryption algorithm to use. - */ - algorithm: RsaEncryptionAlgorithm; - /** - * The plain text to encrypt. - */ - plaintext: Uint8Array; -} - -/** - * A union type representing all supported AES-GCM encryption algorithms. - */ -export type AesGcmEncryptionAlgorithm = "A128GCM" | "A192GCM" | "A256GCM"; - -/** - * Encryption parameters for AES-GCM encryption algorithms. - */ -export interface AesGcmEncryptParameters { - /** - * The encryption algorithm to use. - */ - algorithm: AesGcmEncryptionAlgorithm; - /** - * The plain text to encrypt. - */ - plaintext: Uint8Array; - /** - * Optional data that is authenticated but not encrypted. - */ - additionalAuthenticatedData?: Uint8Array; -} - -/** - * A union type representing all supported AES-CBC encryption algorithms. - */ -export type AesCbcEncryptionAlgorithm = - | "A128CBC" - | "A192CBC" - | "A256CBC" - | "A128CBCPAD" - | "A192CBCPAD" - | "A256CBCPAD"; - -/** - * Encryption parameters for AES-CBC encryption algorithms. - */ -export interface AesCbcEncryptParameters { - /** - * The encryption algorithm to use. - */ - algorithm: AesCbcEncryptionAlgorithm; - /** - * The plain text to encrypt. - */ - plaintext: Uint8Array; - /** - * The initialization vector used for encryption. If omitted we will attempt to generate an IV using crypto's `randomBytes` functionality. - * An error will be thrown if creating an IV fails, and you may recover by passing in your own cryptographically secure IV. - * - * When passing your own IV, make sure you use a cryptographically random, non-repeating IV. - */ - iv?: Uint8Array; -} - -/** - * A type representing all currently supported encryption parameters as they apply to different encryption algorithms. - */ -export type EncryptParameters = - | RsaEncryptParameters - | AesGcmEncryptParameters - | AesCbcEncryptParameters; - -/** - * Decryption parameters for RSA encryption algorithms. - */ -export interface RsaDecryptParameters { - /** - * The encryption algorithm to use. - */ - algorithm: RsaEncryptionAlgorithm; - /** - * The ciphertext to decrypt. - */ - ciphertext: Uint8Array; -} - -/** - * Decryption parameters for AES-GCM encryption algorithms. - */ -export interface AesGcmDecryptParameters { - /** - * The encryption algorithm to use. - */ - algorithm: AesGcmEncryptionAlgorithm; - /** - * The ciphertext to decrypt. - */ - ciphertext: Uint8Array; - /** - * The initialization vector (or nonce) generated during encryption. - */ - iv: Uint8Array; - /** - * The authentication tag generated during encryption. - */ - authenticationTag: Uint8Array; - /** - * Optional data that is authenticated but not encrypted. - */ - additionalAuthenticatedData?: Uint8Array; -} - -/** - * Decryption parameters for AES-CBC encryption algorithms. - */ -export interface AesCbcDecryptParameters { - /** - * The encryption algorithm to use. - */ - algorithm: AesCbcEncryptionAlgorithm; - /** - * The initialization vector used during encryption. - */ - /** - * The ciphertext to decrypt. Microsoft recommends you not use CBC without first ensuring the integrity of the ciphertext using an HMAC, for example. - * See https://learn.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - */ - ciphertext: Uint8Array; - /** - * The initialization vector generated during encryption. - */ - iv: Uint8Array; -} - -/** - * A type representing all currently supported decryption parameters as they apply to different encryption algorithms. - */ -export type DecryptParameters = - | RsaDecryptParameters - | AesGcmDecryptParameters - | AesCbcDecryptParameters; - -/** - * The various key types a {@link CryptographyClient} can hold. - * The key may be an identifier (URL) to a KeyVault key, the actual KeyVault key, - * or a local-only JsonWebKey. - * - * If an identifier is used, an attempt will be made to exchange it for a {@link KeyVaultKey} during the first operation call. If this attempt fails, the identifier - * will become a remote-only identifier and the {@link CryptographyClient} will only be able to perform remote operations. - */ -export type CryptographyClientKey = - | { - kind: "identifier"; - value: string; - } - | { - kind: "remoteOnlyIdentifier"; - value: string; - } - | { - kind: "KeyVaultKey"; - value: KeyVaultKey; - } - | { - kind: "JsonWebKey"; - value: JsonWebKey; - }; diff --git a/sdk/keyvault/keyvault-keys/src/generated/api/index.ts b/sdk/keyvault/keyvault-keys/src/generated/api/index.ts deleted file mode 100644 index 096aaa4b5dee..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/api/index.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export { - createKeyVault, - KeyVaultContext, - KeyVaultClientOptionalParams, -} from "./keyVaultContext.js"; -export { - getRandomBytes, - updateKeyRotationPolicy, - getKeyRotationPolicy, - recoverDeletedKey, - purgeDeletedKey, - getDeletedKey, - getDeletedKeys, - release, - unwrapKey, - wrapKey, - verify, - sign, - decrypt, - encrypt, - restoreKey, - backupKey, - getKeys, - getKeyVersions, - getKey, - updateKey, - deleteKey, - importKey, - rotateKey, - createKey, -} from "./operations.js"; -export { - GetRandomBytesOptionalParams, - UpdateKeyRotationPolicyOptionalParams, - GetKeyRotationPolicyOptionalParams, - RecoverDeletedKeyOptionalParams, - PurgeDeletedKeyOptionalParams, - GetDeletedKeyOptionalParams, - GetDeletedKeysOptionalParams, - ReleaseOptionalParams, - UnwrapKeyOptionalParams, - WrapKeyOptionalParams, - VerifyOptionalParams, - SignOptionalParams, - DecryptOptionalParams, - EncryptOptionalParams, - RestoreKeyOptionalParams, - BackupKeyOptionalParams, - GetKeysOptionalParams, - GetKeyVersionsOptionalParams, - GetKeyOptionalParams, - UpdateKeyOptionalParams, - DeleteKeyOptionalParams, - ImportKeyOptionalParams, - RotateKeyOptionalParams, - CreateKeyOptionalParams, -} from "./options.js"; diff --git a/sdk/keyvault/keyvault-keys/src/generated/api/keyVaultContext.ts b/sdk/keyvault/keyvault-keys/src/generated/api/keyVaultContext.ts deleted file mode 100644 index d1f3a5994825..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/api/keyVaultContext.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { logger } from "../logger.js"; -import { KnownVersions } from "../models/models.js"; -import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; -import { TokenCredential } from "@azure/core-auth"; - -/** The key vault client performs cryptographic key operations and vault operations against the Key Vault service. */ -export interface KeyVaultContext extends Client { - /** The API version to use for this operation. */ - /** Known values of {@link KnownVersions} that the service accepts. */ - apiVersion: string; -} - -/** Optional parameters for the client. */ -export interface KeyVaultClientOptionalParams extends ClientOptions { - /** The API version to use for this operation. */ - /** Known values of {@link KnownVersions} that the service accepts. */ - apiVersion?: string; -} - -/** The key vault client performs cryptographic key operations and vault operations against the Key Vault service. */ -export function createKeyVault( - endpointParam: string, - credential: TokenCredential, - options: KeyVaultClientOptionalParams = {}, -): KeyVaultContext { - const endpointUrl = - options.endpoint ?? options.baseUrl ?? String(endpointParam); - const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; - const userAgentInfo = `azsdk-js-keyvault-keys/1.0.0-beta.1`; - const userAgentPrefix = prefixFromOptions - ? `${prefixFromOptions} azsdk-js-api ${userAgentInfo}` - : `azsdk-js-api ${userAgentInfo}`; - const { apiVersion: _, ...updatedOptions } = { - ...options, - userAgentOptions: { userAgentPrefix }, - loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, - credentials: { - scopes: options.credentials?.scopes ?? [ - "https://vault.azure.net/.default", - ], - }, - }; - const clientContext = getClient(endpointUrl, credential, updatedOptions); - clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - const apiVersion = options.apiVersion ?? "7.6-preview.1"; - clientContext.pipeline.addPolicy({ - name: "ClientApiVersionPolicy", - sendRequest: (req, next) => { - // Use the apiVersion defined in request url directly - // Append one if there is no apiVersion and we have one at client options - const url = new URL(req.url); - if (!url.searchParams.get("api-version")) { - req.url = `${req.url}${ - Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" - }api-version=${apiVersion}`; - } - - return next(req); - }, - }); - return { ...clientContext, apiVersion } as KeyVaultContext; -} diff --git a/sdk/keyvault/keyvault-keys/src/generated/api/operations.ts b/sdk/keyvault/keyvault-keys/src/generated/api/operations.ts deleted file mode 100644 index ede3f9bd6e11..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/api/operations.ts +++ /dev/null @@ -1,1183 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { - BackupKeyOptionalParams, - KeyVaultContext as Client, - CreateKeyOptionalParams, - DecryptOptionalParams, - DeleteKeyOptionalParams, - EncryptOptionalParams, - GetDeletedKeyOptionalParams, - GetDeletedKeysOptionalParams, - GetKeyOptionalParams, - GetKeyRotationPolicyOptionalParams, - GetKeysOptionalParams, - GetKeyVersionsOptionalParams, - GetRandomBytesOptionalParams, - ImportKeyOptionalParams, - PurgeDeletedKeyOptionalParams, - RecoverDeletedKeyOptionalParams, - ReleaseOptionalParams, - RestoreKeyOptionalParams, - RotateKeyOptionalParams, - SignOptionalParams, - UnwrapKeyOptionalParams, - UpdateKeyOptionalParams, - UpdateKeyRotationPolicyOptionalParams, - VerifyOptionalParams, - WrapKeyOptionalParams, -} from "./index.js"; -import { - KeyCreateParameters, - keyCreateParametersSerializer, - KeyBundle, - keyBundleDeserializer, - keyVaultErrorDeserializer, - KeyImportParameters, - keyImportParametersSerializer, - DeletedKeyBundle, - deletedKeyBundleDeserializer, - KeyUpdateParameters, - keyUpdateParametersSerializer, - _KeyListResult, - _keyListResultDeserializer, - KeyItem, - BackupKeyResult, - backupKeyResultDeserializer, - KeyRestoreParameters, - keyRestoreParametersSerializer, - KeyOperationsParameters, - keyOperationsParametersSerializer, - KeyOperationResult, - keyOperationResultDeserializer, - KeySignParameters, - keySignParametersSerializer, - KeyVerifyParameters, - keyVerifyParametersSerializer, - KeyVerifyResult, - keyVerifyResultDeserializer, - KeyReleaseParameters, - keyReleaseParametersSerializer, - KeyReleaseResult, - keyReleaseResultDeserializer, - _DeletedKeyListResult, - _deletedKeyListResultDeserializer, - DeletedKeyItem, - KeyRotationPolicy, - keyRotationPolicySerializer, - keyRotationPolicyDeserializer, - GetRandomBytesRequest, - getRandomBytesRequestSerializer, - RandomBytes, - randomBytesDeserializer, -} from "../models/models.js"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../static-helpers/pagingHelpers.js"; -import { - StreamableMethod, - PathUncheckedResponse, - createRestError, - operationOptionsToRequestParameters, -} from "@azure-rest/core-client"; - -export function _getRandomBytesSend( - context: Client, - parameters: GetRandomBytesRequest, - options: GetRandomBytesOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/rng") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: getRandomBytesRequestSerializer(parameters), - }); -} - -export async function _getRandomBytesDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return randomBytesDeserializer(result.body); -} - -/** Get the requested number of bytes containing random values from a managed HSM. */ -export async function getRandomBytes( - context: Client, - parameters: GetRandomBytesRequest, - options: GetRandomBytesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getRandomBytesSend(context, parameters, options); - return _getRandomBytesDeserialize(result); -} - -export function _updateKeyRotationPolicySend( - context: Client, - keyName: string, - keyRotationPolicy: KeyRotationPolicy, - options: UpdateKeyRotationPolicyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/rotationpolicy", keyName) - .put({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyRotationPolicySerializer(keyRotationPolicy), - }); -} - -export async function _updateKeyRotationPolicyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyRotationPolicyDeserializer(result.body); -} - -/** Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update permission. */ -export async function updateKeyRotationPolicy( - context: Client, - keyName: string, - keyRotationPolicy: KeyRotationPolicy, - options: UpdateKeyRotationPolicyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateKeyRotationPolicySend( - context, - keyName, - keyRotationPolicy, - options, - ); - return _updateKeyRotationPolicyDeserialize(result); -} - -export function _getKeyRotationPolicySend( - context: Client, - keyName: string, - options: GetKeyRotationPolicyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/rotationpolicy", keyName) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _getKeyRotationPolicyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyRotationPolicyDeserializer(result.body); -} - -/** The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This operation requires the keys/get permission. */ -export async function getKeyRotationPolicy( - context: Client, - keyName: string, - options: GetKeyRotationPolicyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getKeyRotationPolicySend(context, keyName, options); - return _getKeyRotationPolicyDeserialize(result); -} - -export function _recoverDeletedKeySend( - context: Client, - keyName: string, - options: RecoverDeletedKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/deletedkeys/{key-name}/recover", keyName) - .post({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _recoverDeletedKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyBundleDeserializer(result.body); -} - -/** The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires the keys/recover permission. */ -export async function recoverDeletedKey( - context: Client, - keyName: string, - options: RecoverDeletedKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _recoverDeletedKeySend(context, keyName, options); - return _recoverDeletedKeyDeserialize(result); -} - -export function _purgeDeletedKeySend( - context: Client, - keyName: string, - options: PurgeDeletedKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/deletedkeys/{key-name}", keyName) - .delete({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _purgeDeletedKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return; -} - -/** The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/purge permission. */ -export async function purgeDeletedKey( - context: Client, - keyName: string, - options: PurgeDeletedKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _purgeDeletedKeySend(context, keyName, options); - return _purgeDeletedKeyDeserialize(result); -} - -export function _getDeletedKeySend( - context: Client, - keyName: string, - options: GetDeletedKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/deletedkeys/{key-name}", keyName) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _getDeletedKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return deletedKeyBundleDeserializer(result.body); -} - -/** The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/get permission. */ -export async function getDeletedKey( - context: Client, - keyName: string, - options: GetDeletedKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getDeletedKeySend(context, keyName, options); - return _getDeletedKeyDeserialize(result); -} - -export function _getDeletedKeysSend( - context: Client, - options: GetDeletedKeysOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/deletedkeys") - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { - "api-version": context.apiVersion, - maxresults: options?.maxresults, - }, - }); -} - -export async function _getDeletedKeysDeserialize( - result: PathUncheckedResponse, -): Promise<_DeletedKeyListResult> { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return _deletedKeyListResultDeserializer(result.body); -} - -/** Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. */ -export function getDeletedKeys( - context: Client, - options: GetDeletedKeysOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _getDeletedKeysSend(context, options), - _getDeletedKeysDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); -} - -export function _releaseSend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyReleaseParameters, - options: ReleaseOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}/release", keyName, keyVersion) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyReleaseParametersSerializer(parameters), - }); -} - -export async function _releaseDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyReleaseResultDeserializer(result.body); -} - -/** The release key operation is applicable to all key types. The target key must be marked exportable. This operation requires the keys/release permission. */ -export async function release( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyReleaseParameters, - options: ReleaseOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _releaseSend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _releaseDeserialize(result); -} - -export function _unwrapKeySend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: UnwrapKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}/unwrapkey", keyName, keyVersion) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyOperationsParametersSerializer(parameters), - }); -} - -export async function _unwrapKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyOperationResultDeserializer(result.body); -} - -/** The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey permission. */ -export async function unwrapKey( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: UnwrapKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _unwrapKeySend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _unwrapKeyDeserialize(result); -} - -export function _wrapKeySend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: WrapKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}/wrapkey", keyName, keyVersion) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyOperationsParametersSerializer(parameters), - }); -} - -export async function _wrapKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyOperationResultDeserializer(result.body); -} - -/** The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have access to the public key material. This operation requires the keys/wrapKey permission. */ -export async function wrapKey( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: WrapKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _wrapKeySend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _wrapKeyDeserialize(result); -} - -export function _verifySend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyVerifyParameters, - options: VerifyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}/verify", keyName, keyVersion) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyVerifyParametersSerializer(parameters), - }); -} - -export async function _verifyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyVerifyResultDeserializer(result.body); -} - -/** The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public portion of the key but this operation is supported as a convenience for callers that only have a key-reference and not the public portion of the key. This operation requires the keys/verify permission. */ -export async function verify( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyVerifyParameters, - options: VerifyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _verifySend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _verifyDeserialize(result); -} - -export function _signSend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeySignParameters, - options: SignOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}/sign", keyName, keyVersion) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keySignParametersSerializer(parameters), - }); -} - -export async function _signDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyOperationResultDeserializer(result.body); -} - -/** The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation uses the private portion of the key. This operation requires the keys/sign permission. */ -export async function sign( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeySignParameters, - options: SignOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _signSend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _signDeserialize(result); -} - -export function _decryptSend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: DecryptOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}/decrypt", keyName, keyVersion) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyOperationsParametersSerializer(parameters), - }); -} - -export async function _decryptDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyOperationResultDeserializer(result.body); -} - -/** The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption without first ensuring the integrity of the ciphertext using an HMAC, for example. See https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. */ -export async function decrypt( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: DecryptOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _decryptSend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _decryptDeserialize(result); -} - -export function _encryptSend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: EncryptOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}/encrypt", keyName, keyVersion) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyOperationsParametersSerializer(parameters), - }); -} - -export async function _encryptDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyOperationResultDeserializer(result.body); -} - -/** The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have access to the public key material. This operation requires the keys/encrypt permission. */ -export async function encrypt( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: EncryptOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _encryptSend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _encryptDeserialize(result); -} - -export function _restoreKeySend( - context: Client, - parameters: KeyRestoreParameters, - options: RestoreKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/restore") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyRestoreParametersSerializer(parameters), - }); -} - -export async function _restoreKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyBundleDeserializer(result.body); -} - -/** Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and access control policies. The RESTORE operation may be used to import a previously backed up key. Individual versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be rejected. While the key name is retained during restore, the final key identifier will change if the key is restored to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This operation requires the keys/restore permission. */ -export async function restoreKey( - context: Client, - parameters: KeyRestoreParameters, - options: RestoreKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _restoreKeySend(context, parameters, options); - return _restoreKeyDeserialize(result); -} - -export function _backupKeySend( - context: Client, - keyName: string, - options: BackupKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/backup", keyName) - .post({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _backupKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return backupKeyResultDeserializer(result.body); -} - -/** The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical area. This operation requires the key/backup permission. */ -export async function backupKey( - context: Client, - keyName: string, - options: BackupKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _backupKeySend(context, keyName, options); - return _backupKeyDeserialize(result); -} - -export function _getKeysSend( - context: Client, - options: GetKeysOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys") - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { - "api-version": context.apiVersion, - maxresults: options?.maxresults, - }, - }); -} - -export async function _getKeysDeserialize( - result: PathUncheckedResponse, -): Promise<_KeyListResult> { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return _keyListResultDeserializer(result.body); -} - -/** Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and tags are provided in the response. Individual versions of a key are not listed in the response. This operation requires the keys/list permission. */ -export function getKeys( - context: Client, - options: GetKeysOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _getKeysSend(context, options), - _getKeysDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); -} - -export function _getKeyVersionsSend( - context: Client, - keyName: string, - options: GetKeyVersionsOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/versions", keyName) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { - "api-version": context.apiVersion, - maxresults: options?.maxresults, - }, - }); -} - -export async function _getKeyVersionsDeserialize( - result: PathUncheckedResponse, -): Promise<_KeyListResult> { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return _keyListResultDeserializer(result.body); -} - -/** The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list permission. */ -export function getKeyVersions( - context: Client, - keyName: string, - options: GetKeyVersionsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _getKeyVersionsSend(context, keyName, options), - _getKeyVersionsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); -} - -export function _getKeySend( - context: Client, - keyName: string, - keyVersion: string, - options: GetKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}", keyName, keyVersion) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _getKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyBundleDeserializer(result.body); -} - -/** The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. This operation requires the keys/get permission. */ -export async function getKey( - context: Client, - keyName: string, - keyVersion: string, - options: GetKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getKeySend(context, keyName, keyVersion, options); - return _getKeyDeserialize(result); -} - -export function _updateKeySend( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyUpdateParameters, - options: UpdateKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/{key-version}", keyName, keyVersion) - .patch({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyUpdateParametersSerializer(parameters), - }); -} - -export async function _updateKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyBundleDeserializer(result.body); -} - -/** In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material of a key itself cannot be changed. This operation requires the keys/update permission. */ -export async function updateKey( - context: Client, - keyName: string, - keyVersion: string, - parameters: KeyUpdateParameters, - options: UpdateKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateKeySend( - context, - keyName, - keyVersion, - parameters, - options, - ); - return _updateKeyDeserialize(result); -} - -export function _deleteKeySend( - context: Client, - keyName: string, - options: DeleteKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}", keyName) - .delete({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _deleteKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return deletedKeyBundleDeserializer(result.body); -} - -/** The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the keys/delete permission. */ -export async function deleteKey( - context: Client, - keyName: string, - options: DeleteKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteKeySend(context, keyName, options); - return _deleteKeyDeserialize(result); -} - -export function _importKeySend( - context: Client, - keyName: string, - parameters: KeyImportParameters, - options: ImportKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}", keyName) - .put({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyImportParametersSerializer(parameters), - }); -} - -export async function _importKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyBundleDeserializer(result.body); -} - -/** The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. */ -export async function importKey( - context: Client, - keyName: string, - parameters: KeyImportParameters, - options: ImportKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _importKeySend(context, keyName, parameters, options); - return _importKeyDeserialize(result); -} - -export function _rotateKeySend( - context: Client, - keyName: string, - options: RotateKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/rotate", keyName) - .post({ - ...operationOptionsToRequestParameters(options), - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - }); -} - -export async function _rotateKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyBundleDeserializer(result.body); -} - -/** The operation will rotate the key based on the key policy. It requires the keys/rotate permission. */ -export async function rotateKey( - context: Client, - keyName: string, - options: RotateKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _rotateKeySend(context, keyName, options); - return _rotateKeyDeserialize(result); -} - -export function _createKeySend( - context: Client, - keyName: string, - parameters: KeyCreateParameters, - options: CreateKeyOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/keys/{key-name}/create", keyName) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: "application/json", - headers: { - accept: "application/json", - ...options.requestOptions?.headers, - }, - queryParameters: { "api-version": context.apiVersion }, - body: keyCreateParametersSerializer(parameters), - }); -} - -export async function _createKeyDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - const error = createRestError(result); - error.details = keyVaultErrorDeserializer(result.body); - throw error; - } - - return keyBundleDeserializer(result.body); -} - -/** The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the keys/create permission. */ -export async function createKey( - context: Client, - keyName: string, - parameters: KeyCreateParameters, - options: CreateKeyOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createKeySend(context, keyName, parameters, options); - return _createKeyDeserialize(result); -} diff --git a/sdk/keyvault/keyvault-keys/src/generated/api/options.ts b/sdk/keyvault/keyvault-keys/src/generated/api/options.ts deleted file mode 100644 index a42b815d23e2..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/api/options.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { OperationOptions } from "@azure-rest/core-client"; - -/** Optional parameters. */ -export interface GetRandomBytesOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface UpdateKeyRotationPolicyOptionalParams - extends OperationOptions {} - -/** Optional parameters. */ -export interface GetKeyRotationPolicyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface RecoverDeletedKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface PurgeDeletedKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface GetDeletedKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface GetDeletedKeysOptionalParams extends OperationOptions { - /** Maximum number of results to return in a page. If not specified the service will return up to 25 results. */ - maxresults?: number; -} - -/** Optional parameters. */ -export interface ReleaseOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface UnwrapKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface WrapKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface VerifyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface SignOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface DecryptOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface EncryptOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface RestoreKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface BackupKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface GetKeysOptionalParams extends OperationOptions { - /** Maximum number of results to return in a page. If not specified the service will return up to 25 results. */ - maxresults?: number; -} - -/** Optional parameters. */ -export interface GetKeyVersionsOptionalParams extends OperationOptions { - /** Maximum number of results to return in a page. If not specified the service will return up to 25 results. */ - maxresults?: number; -} - -/** Optional parameters. */ -export interface GetKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface UpdateKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface DeleteKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface ImportKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface RotateKeyOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface CreateKeyOptionalParams extends OperationOptions {} diff --git a/sdk/keyvault/keyvault-keys/src/generated/index.ts b/sdk/keyvault/keyvault-keys/src/generated/index.ts deleted file mode 100644 index 0118cdcf4e02..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/index.ts +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { - PageSettings, - ContinuablePage, - PagedAsyncIterableIterator, -} from "./static-helpers/pagingHelpers.js"; - -export { KeyVaultClient } from "./keyVaultClient.js"; -export { - KeyCreateParameters, - KnownJsonWebKeyType, - JsonWebKeyType, - KnownJsonWebKeyOperation, - JsonWebKeyOperation, - KeyAttributes, - KnownDeletionRecoveryLevel, - DeletionRecoveryLevel, - KnownJsonWebKeyCurveName, - JsonWebKeyCurveName, - KeyReleasePolicy, - KeyBundle, - JsonWebKey, - KeyVaultError, - ErrorModel, - KeyImportParameters, - DeletedKeyBundle, - KeyUpdateParameters, - KeyItem, - BackupKeyResult, - KeyRestoreParameters, - KeyOperationsParameters, - KnownJsonWebKeyEncryptionAlgorithm, - JsonWebKeyEncryptionAlgorithm, - KeyOperationResult, - KeySignParameters, - KnownJsonWebKeySignatureAlgorithm, - JsonWebKeySignatureAlgorithm, - KeyVerifyParameters, - KeyVerifyResult, - KeyReleaseParameters, - KnownKeyEncryptionAlgorithm, - KeyEncryptionAlgorithm, - KeyReleaseResult, - DeletedKeyItem, - KeyRotationPolicy, - LifetimeActions, - LifetimeActionsTrigger, - LifetimeActionsType, - KeyRotationPolicyAction, - KeyRotationPolicyAttributes, - GetRandomBytesRequest, - RandomBytes, - KnownVersions, -} from "./models/index.js"; -export { - KeyVaultClientOptionalParams, - GetRandomBytesOptionalParams, - UpdateKeyRotationPolicyOptionalParams, - GetKeyRotationPolicyOptionalParams, - RecoverDeletedKeyOptionalParams, - PurgeDeletedKeyOptionalParams, - GetDeletedKeyOptionalParams, - GetDeletedKeysOptionalParams, - ReleaseOptionalParams, - UnwrapKeyOptionalParams, - WrapKeyOptionalParams, - VerifyOptionalParams, - SignOptionalParams, - DecryptOptionalParams, - EncryptOptionalParams, - RestoreKeyOptionalParams, - BackupKeyOptionalParams, - GetKeysOptionalParams, - GetKeyVersionsOptionalParams, - GetKeyOptionalParams, - UpdateKeyOptionalParams, - DeleteKeyOptionalParams, - ImportKeyOptionalParams, - RotateKeyOptionalParams, - CreateKeyOptionalParams, -} from "./api/index.js"; -export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/sdk/keyvault/keyvault-keys/src/generated/keyVaultClient.ts b/sdk/keyvault/keyvault-keys/src/generated/keyVaultClient.ts deleted file mode 100644 index e307a3b7cec1..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/keyVaultClient.ts +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { - createKeyVault, - KeyVaultContext, - KeyVaultClientOptionalParams, - getRandomBytes, - updateKeyRotationPolicy, - getKeyRotationPolicy, - recoverDeletedKey, - purgeDeletedKey, - getDeletedKey, - getDeletedKeys, - release, - unwrapKey, - wrapKey, - verify, - sign, - decrypt, - encrypt, - restoreKey, - backupKey, - getKeys, - getKeyVersions, - getKey, - updateKey, - deleteKey, - importKey, - rotateKey, - createKey, - GetRandomBytesOptionalParams, - UpdateKeyRotationPolicyOptionalParams, - GetKeyRotationPolicyOptionalParams, - RecoverDeletedKeyOptionalParams, - PurgeDeletedKeyOptionalParams, - GetDeletedKeyOptionalParams, - GetDeletedKeysOptionalParams, - ReleaseOptionalParams, - UnwrapKeyOptionalParams, - WrapKeyOptionalParams, - VerifyOptionalParams, - SignOptionalParams, - DecryptOptionalParams, - EncryptOptionalParams, - RestoreKeyOptionalParams, - BackupKeyOptionalParams, - GetKeysOptionalParams, - GetKeyVersionsOptionalParams, - GetKeyOptionalParams, - UpdateKeyOptionalParams, - DeleteKeyOptionalParams, - ImportKeyOptionalParams, - RotateKeyOptionalParams, - CreateKeyOptionalParams, -} from "./api/index.js"; -import { - KeyCreateParameters, - KeyBundle, - KeyImportParameters, - DeletedKeyBundle, - KeyUpdateParameters, - KeyItem, - BackupKeyResult, - KeyRestoreParameters, - KeyOperationsParameters, - KeyOperationResult, - KeySignParameters, - KeyVerifyParameters, - KeyVerifyResult, - KeyReleaseParameters, - KeyReleaseResult, - DeletedKeyItem, - KeyRotationPolicy, - GetRandomBytesRequest, - RandomBytes, -} from "./models/models.js"; -import { PagedAsyncIterableIterator } from "./static-helpers/pagingHelpers.js"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { TokenCredential } from "@azure/core-auth"; - -export { KeyVaultClientOptionalParams } from "./api/keyVaultContext.js"; - -export class KeyVaultClient { - private _client: KeyVaultContext; - /** The pipeline used by this client to make requests */ - public readonly pipeline: Pipeline; - - /** The key vault client performs cryptographic key operations and vault operations against the Key Vault service. */ - constructor( - endpointParam: string, - credential: TokenCredential, - options: KeyVaultClientOptionalParams = {}, - ) { - const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; - const userAgentPrefix = prefixFromOptions - ? `${prefixFromOptions} azsdk-js-client` - : `azsdk-js-client`; - this._client = createKeyVault(endpointParam, credential, { - ...options, - userAgentOptions: { userAgentPrefix }, - }); - this.pipeline = this._client.pipeline; - } - - /** Get the requested number of bytes containing random values from a managed HSM. */ - getRandomBytes( - parameters: GetRandomBytesRequest, - options: GetRandomBytesOptionalParams = { requestOptions: {} }, - ): Promise { - return getRandomBytes(this._client, parameters, options); - } - - /** Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update permission. */ - updateKeyRotationPolicy( - keyName: string, - keyRotationPolicy: KeyRotationPolicy, - options: UpdateKeyRotationPolicyOptionalParams = { requestOptions: {} }, - ): Promise { - return updateKeyRotationPolicy( - this._client, - keyName, - keyRotationPolicy, - options, - ); - } - - /** The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This operation requires the keys/get permission. */ - getKeyRotationPolicy( - keyName: string, - options: GetKeyRotationPolicyOptionalParams = { requestOptions: {} }, - ): Promise { - return getKeyRotationPolicy(this._client, keyName, options); - } - - /** The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires the keys/recover permission. */ - recoverDeletedKey( - keyName: string, - options: RecoverDeletedKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return recoverDeletedKey(this._client, keyName, options); - } - - /** The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/purge permission. */ - purgeDeletedKey( - keyName: string, - options: PurgeDeletedKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return purgeDeletedKey(this._client, keyName, options); - } - - /** The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/get permission. */ - getDeletedKey( - keyName: string, - options: GetDeletedKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return getDeletedKey(this._client, keyName, options); - } - - /** Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. */ - getDeletedKeys( - options: GetDeletedKeysOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return getDeletedKeys(this._client, options); - } - - /** The release key operation is applicable to all key types. The target key must be marked exportable. This operation requires the keys/release permission. */ - release( - keyName: string, - keyVersion: string, - parameters: KeyReleaseParameters, - options: ReleaseOptionalParams = { requestOptions: {} }, - ): Promise { - return release(this._client, keyName, keyVersion, parameters, options); - } - - /** The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey permission. */ - unwrapKey( - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: UnwrapKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return unwrapKey(this._client, keyName, keyVersion, parameters, options); - } - - /** The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have access to the public key material. This operation requires the keys/wrapKey permission. */ - wrapKey( - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: WrapKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return wrapKey(this._client, keyName, keyVersion, parameters, options); - } - - /** The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public portion of the key but this operation is supported as a convenience for callers that only have a key-reference and not the public portion of the key. This operation requires the keys/verify permission. */ - verify( - keyName: string, - keyVersion: string, - parameters: KeyVerifyParameters, - options: VerifyOptionalParams = { requestOptions: {} }, - ): Promise { - return verify(this._client, keyName, keyVersion, parameters, options); - } - - /** The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation uses the private portion of the key. This operation requires the keys/sign permission. */ - sign( - keyName: string, - keyVersion: string, - parameters: KeySignParameters, - options: SignOptionalParams = { requestOptions: {} }, - ): Promise { - return sign(this._client, keyName, keyVersion, parameters, options); - } - - /** The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption without first ensuring the integrity of the ciphertext using an HMAC, for example. See https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. */ - decrypt( - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: DecryptOptionalParams = { requestOptions: {} }, - ): Promise { - return decrypt(this._client, keyName, keyVersion, parameters, options); - } - - /** The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have access to the public key material. This operation requires the keys/encrypt permission. */ - encrypt( - keyName: string, - keyVersion: string, - parameters: KeyOperationsParameters, - options: EncryptOptionalParams = { requestOptions: {} }, - ): Promise { - return encrypt(this._client, keyName, keyVersion, parameters, options); - } - - /** Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and access control policies. The RESTORE operation may be used to import a previously backed up key. Individual versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be rejected. While the key name is retained during restore, the final key identifier will change if the key is restored to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This operation requires the keys/restore permission. */ - restoreKey( - parameters: KeyRestoreParameters, - options: RestoreKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return restoreKey(this._client, parameters, options); - } - - /** The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical area. This operation requires the key/backup permission. */ - backupKey( - keyName: string, - options: BackupKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return backupKey(this._client, keyName, options); - } - - /** Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and tags are provided in the response. Individual versions of a key are not listed in the response. This operation requires the keys/list permission. */ - getKeys( - options: GetKeysOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return getKeys(this._client, options); - } - - /** The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list permission. */ - getKeyVersions( - keyName: string, - options: GetKeyVersionsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return getKeyVersions(this._client, keyName, options); - } - - /** The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. This operation requires the keys/get permission. */ - getKey( - keyName: string, - keyVersion: string, - options: GetKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return getKey(this._client, keyName, keyVersion, options); - } - - /** In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material of a key itself cannot be changed. This operation requires the keys/update permission. */ - updateKey( - keyName: string, - keyVersion: string, - parameters: KeyUpdateParameters, - options: UpdateKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return updateKey(this._client, keyName, keyVersion, parameters, options); - } - - /** The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the keys/delete permission. */ - deleteKey( - keyName: string, - options: DeleteKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return deleteKey(this._client, keyName, options); - } - - /** The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. */ - importKey( - keyName: string, - parameters: KeyImportParameters, - options: ImportKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return importKey(this._client, keyName, parameters, options); - } - - /** The operation will rotate the key based on the key policy. It requires the keys/rotate permission. */ - rotateKey( - keyName: string, - options: RotateKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return rotateKey(this._client, keyName, options); - } - - /** The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the keys/create permission. */ - createKey( - keyName: string, - parameters: KeyCreateParameters, - options: CreateKeyOptionalParams = { requestOptions: {} }, - ): Promise { - return createKey(this._client, keyName, parameters, options); - } -} diff --git a/sdk/keyvault/keyvault-keys/src/generated/logger.ts b/sdk/keyvault/keyvault-keys/src/generated/logger.ts deleted file mode 100644 index f43102537cd4..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/logger.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { createClientLogger } from "@azure/logger"; -export const logger = createClientLogger("keyvault-keys"); diff --git a/sdk/keyvault/keyvault-keys/src/generated/models/index.ts b/sdk/keyvault/keyvault-keys/src/generated/models/index.ts deleted file mode 100644 index e0e218b98a20..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/models/index.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export { - KeyCreateParameters, - KnownJsonWebKeyType, - JsonWebKeyType, - KnownJsonWebKeyOperation, - JsonWebKeyOperation, - KeyAttributes, - KnownDeletionRecoveryLevel, - DeletionRecoveryLevel, - KnownJsonWebKeyCurveName, - JsonWebKeyCurveName, - KeyReleasePolicy, - KeyBundle, - JsonWebKey, - KeyVaultError, - ErrorModel, - KeyImportParameters, - DeletedKeyBundle, - KeyUpdateParameters, - KeyItem, - BackupKeyResult, - KeyRestoreParameters, - KeyOperationsParameters, - KnownJsonWebKeyEncryptionAlgorithm, - JsonWebKeyEncryptionAlgorithm, - KeyOperationResult, - KeySignParameters, - KnownJsonWebKeySignatureAlgorithm, - JsonWebKeySignatureAlgorithm, - KeyVerifyParameters, - KeyVerifyResult, - KeyReleaseParameters, - KnownKeyEncryptionAlgorithm, - KeyEncryptionAlgorithm, - KeyReleaseResult, - DeletedKeyItem, - KeyRotationPolicy, - LifetimeActions, - LifetimeActionsTrigger, - LifetimeActionsType, - KeyRotationPolicyAction, - KeyRotationPolicyAttributes, - GetRandomBytesRequest, - RandomBytes, - KnownVersions, -} from "./models.js"; diff --git a/sdk/keyvault/keyvault-keys/src/generated/models/models.ts b/sdk/keyvault/keyvault-keys/src/generated/models/models.ts deleted file mode 100644 index c5b8bce6f187..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/models/models.ts +++ /dev/null @@ -1,1151 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; - -/** The key create parameters. */ -export interface KeyCreateParameters { - /** The type of key to create. For valid values, see JsonWebKeyType. */ - kty: JsonWebKeyType; - /** The key size in bits. For example: 2048, 3072, or 4096 for RSA. */ - keySize?: number; - /** The public exponent for a RSA key. */ - publicExponent?: number; - /** Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. */ - keyOps?: JsonWebKeyOperation[]; - /** The attributes of a key managed by the key vault service. */ - keyAttributes?: KeyAttributes; - /** Application specific metadata in the form of key-value pairs. */ - tags?: Record; - /** Elliptic curve name. For valid values, see JsonWebKeyCurveName. */ - curve?: JsonWebKeyCurveName; - /** The policy rules under which the key can be exported. */ - releasePolicy?: KeyReleasePolicy; -} - -export function keyCreateParametersSerializer(item: KeyCreateParameters): any { - return { - kty: item["kty"], - key_size: item["keySize"], - public_exponent: item["publicExponent"], - key_ops: !item["keyOps"] - ? item["keyOps"] - : item["keyOps"].map((p: any) => { - return p; - }), - attributes: !item["keyAttributes"] - ? item["keyAttributes"] - : keyAttributesSerializer(item["keyAttributes"]), - tags: item["tags"], - crv: item["curve"], - release_policy: !item["releasePolicy"] - ? item["releasePolicy"] - : keyReleasePolicySerializer(item["releasePolicy"]), - }; -} - -/** JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. */ -export enum KnownJsonWebKeyType { - /** Elliptic Curve. */ - EC = "EC", - /** Elliptic Curve with a private key which is stored in the HSM. */ - EC_HSM = "EC-HSM", - /** RSA (https://tools.ietf.org/html/rfc3447) */ - RSA = "RSA", - /** RSA with a private key which is stored in the HSM. */ - RSA_HSM = "RSA-HSM", - /** Octet sequence (used to represent symmetric keys) */ - oct = "oct", - /** Octet sequence (used to represent symmetric keys) which is stored the HSM. */ - oct_HSM = "oct-HSM", -} - -/** - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. \ - * {@link KnownJsonWebKeyType} can be used interchangeably with JsonWebKeyType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **EC**: Elliptic Curve. \ - * **EC-HSM**: Elliptic Curve with a private key which is stored in the HSM. \ - * **RSA**: RSA (https:\//tools.ietf.org\/html\/rfc3447) \ - * **RSA-HSM**: RSA with a private key which is stored in the HSM. \ - * **oct**: Octet sequence (used to represent symmetric keys) \ - * **oct-HSM**: Octet sequence (used to represent symmetric keys) which is stored the HSM. - */ -export type JsonWebKeyType = string; - -/** JSON web key operations. For more information, see JsonWebKeyOperation. */ -export enum KnownJsonWebKeyOperation { - /** Indicates that the key can be used to encrypt. */ - encrypt = "encrypt", - /** Indicates that the key can be used to decrypt. */ - decrypt = "decrypt", - /** Indicates that the key can be used to sign. */ - sign = "sign", - /** Indicates that the key can be used to verify. */ - verify = "verify", - /** Indicates that the key can be used to wrap another key. */ - wrapKey = "wrapKey", - /** Indicates that the key can be used to unwrap another key. */ - unwrapKey = "unwrapKey", - /** Indicates that the key can be imported during creation. */ - "import" = "import", - /** Indicates that the private component of the key can be exported. */ - "export" = "export", -} - -/** - * JSON web key operations. For more information, see JsonWebKeyOperation. \ - * {@link KnownJsonWebKeyOperation} can be used interchangeably with JsonWebKeyOperation, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **encrypt**: Indicates that the key can be used to encrypt. \ - * **decrypt**: Indicates that the key can be used to decrypt. \ - * **sign**: Indicates that the key can be used to sign. \ - * **verify**: Indicates that the key can be used to verify. \ - * **wrapKey**: Indicates that the key can be used to wrap another key. \ - * **unwrapKey**: Indicates that the key can be used to unwrap another key. \ - * **import**: Indicates that the key can be imported during creation. \ - * **export**: Indicates that the private component of the key can be exported. - */ -export type JsonWebKeyOperation = string; - -/** The attributes of a key managed by the key vault service. */ -export interface KeyAttributes { - /** Determines whether the object is enabled. */ - enabled?: boolean; - /** Not before date in UTC. */ - notBefore?: Date; - /** Expiry date in UTC. */ - expires?: Date; - /** Creation time in UTC. */ - readonly created?: Date; - /** Last updated time in UTC. */ - readonly updated?: Date; - /** softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. */ - readonly recoverableDays?: number; - /** Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains 'Purgeable' the key can be permanently deleted by a privileged user; otherwise, only the system can purge the key, at the end of the retention interval. */ - readonly recoveryLevel?: DeletionRecoveryLevel; - /** Indicates if the private key can be exported. Release policy must be provided when creating the first version of an exportable key. */ - exportable?: boolean; - /** The underlying HSM Platform. */ - readonly hsmPlatform?: string; -} - -export function keyAttributesSerializer(item: KeyAttributes): any { - return { - enabled: item["enabled"], - nbf: !item["notBefore"] - ? item["notBefore"] - : (item["notBefore"].getTime() / 1000) | 0, - exp: !item["expires"] - ? item["expires"] - : (item["expires"].getTime() / 1000) | 0, - exportable: item["exportable"], - }; -} - -export function keyAttributesDeserializer(item: any): KeyAttributes { - return { - enabled: item["enabled"], - notBefore: !item["nbf"] ? item["nbf"] : new Date(item["nbf"] * 1000), - expires: !item["exp"] ? item["exp"] : new Date(item["exp"] * 1000), - created: !item["created"] - ? item["created"] - : new Date(item["created"] * 1000), - updated: !item["updated"] - ? item["updated"] - : new Date(item["updated"] * 1000), - recoverableDays: item["recoverableDays"], - recoveryLevel: item["recoveryLevel"], - exportable: item["exportable"], - hsmPlatform: item["hsmPlatform"], - }; -} - -/** Reflects the deletion recovery level currently in effect for certificates in the current vault. If it contains 'Purgeable', the certificate can be permanently deleted by a privileged user; otherwise, only the system can purge the certificate, at the end of the retention interval. */ -export enum KnownDeletionRecoveryLevel { - /** Denotes a vault state in which deletion is an irreversible operation, without the possibility for recovery. This level corresponds to no protection being available against a Delete operation; the data is irretrievably lost upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.) */ - Purgeable = "Purgeable", - /** Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention interval (90 days), unless a Purge operation is requested, or the subscription is cancelled. System wil permanently delete it after 90 days, if not recovered */ - RecoverablePurgeable = "Recoverable+Purgeable", - /** Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention interval(90 days) and while the subscription is still available. System wil permanently delete it after 90 days, if not recovered */ - Recoverable = "Recoverable", - /** Denotes a vault and subscription state in which deletion is recoverable within retention interval (90 days), immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself cannot be permanently canceled. System wil permanently delete it after 90 days, if not recovered */ - RecoverableProtectedSubscription = "Recoverable+ProtectedSubscription", - /** Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion (i.e. purge when 7 <= SoftDeleteRetentionInDays < 90). This level guarantees the recoverability of the deleted entity during the retention interval, unless a Purge operation is requested, or the subscription is cancelled. */ - CustomizedRecoverablePurgeable = "CustomizedRecoverable+Purgeable", - /** Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent deletion (i.e. purge when 7 <= SoftDeleteRetentionInDays < 90).This level guarantees the recoverability of the deleted entity during the retention interval and while the subscription is still available. */ - CustomizedRecoverable = "CustomizedRecoverable", - /** Denotes a vault and subscription state in which deletion is recoverable, immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself cannot be permanently canceled when 7 <= SoftDeleteRetentionInDays < 90. This level guarantees the recoverability of the deleted entity during the retention interval, and also reflects the fact that the subscription itself cannot be cancelled. */ - CustomizedRecoverableProtectedSubscription = "CustomizedRecoverable+ProtectedSubscription", -} - -/** - * Reflects the deletion recovery level currently in effect for certificates in the current vault. If it contains 'Purgeable', the certificate can be permanently deleted by a privileged user; otherwise, only the system can purge the certificate, at the end of the retention interval. \ - * {@link KnownDeletionRecoveryLevel} can be used interchangeably with DeletionRecoveryLevel, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Purgeable**: Denotes a vault state in which deletion is an irreversible operation, without the possibility for recovery. This level corresponds to no protection being available against a Delete operation; the data is irretrievably lost upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.) \ - * **Recoverable+Purgeable**: Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention interval (90 days), unless a Purge operation is requested, or the subscription is cancelled. System wil permanently delete it after 90 days, if not recovered \ - * **Recoverable**: Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention interval(90 days) and while the subscription is still available. System wil permanently delete it after 90 days, if not recovered \ - * **Recoverable+ProtectedSubscription**: Denotes a vault and subscription state in which deletion is recoverable within retention interval (90 days), immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself cannot be permanently canceled. System wil permanently delete it after 90 days, if not recovered \ - * **CustomizedRecoverable+Purgeable**: Denotes a vault state in which deletion is recoverable, and which also permits immediate and permanent deletion (i.e. purge when 7 <= SoftDeleteRetentionInDays < 90). This level guarantees the recoverability of the deleted entity during the retention interval, unless a Purge operation is requested, or the subscription is cancelled. \ - * **CustomizedRecoverable**: Denotes a vault state in which deletion is recoverable without the possibility for immediate and permanent deletion (i.e. purge when 7 <= SoftDeleteRetentionInDays < 90).This level guarantees the recoverability of the deleted entity during the retention interval and while the subscription is still available. \ - * **CustomizedRecoverable+ProtectedSubscription**: Denotes a vault and subscription state in which deletion is recoverable, immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself cannot be permanently canceled when 7 <= SoftDeleteRetentionInDays < 90. This level guarantees the recoverability of the deleted entity during the retention interval, and also reflects the fact that the subscription itself cannot be cancelled. - */ -export type DeletionRecoveryLevel = string; - -/** Elliptic curve name. For valid values, see JsonWebKeyCurveName. */ -export enum KnownJsonWebKeyCurveName { - /** The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. */ - P256 = "P-256", - /** The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. */ - P384 = "P-384", - /** The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. */ - P521 = "P-521", - /** The SECG SECP256K1 elliptic curve. */ - P256_K = "P-256K", -} - -/** - * Elliptic curve name. For valid values, see JsonWebKeyCurveName. \ - * {@link KnownJsonWebKeyCurveName} can be used interchangeably with JsonWebKeyCurveName, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **P-256**: The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. \ - * **P-384**: The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. \ - * **P-521**: The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. \ - * **P-256K**: The SECG SECP256K1 elliptic curve. - */ -export type JsonWebKeyCurveName = string; - -/** The policy rules under which the key can be exported. */ -export interface KeyReleasePolicy { - /** Content type and version of key release policy */ - contentType?: string; - /** Defines the mutability state of the policy. Once marked immutable, this flag cannot be reset and the policy cannot be changed under any circumstances. */ - immutable?: boolean; - /** Blob encoding the policy rules under which the key can be released. Blob must be base64 URL encoded. */ - encodedPolicy?: Uint8Array; -} - -export function keyReleasePolicySerializer(item: KeyReleasePolicy): any { - return { - contentType: item["contentType"], - immutable: item["immutable"], - data: !item["encodedPolicy"] - ? item["encodedPolicy"] - : uint8ArrayToString(item["encodedPolicy"], "base64url"), - }; -} - -export function keyReleasePolicyDeserializer(item: any): KeyReleasePolicy { - return { - contentType: item["contentType"], - immutable: item["immutable"], - encodedPolicy: !item["data"] - ? item["data"] - : typeof item["data"] === "string" - ? stringToUint8Array(item["data"], "base64url") - : item["data"], - }; -} - -/** A KeyBundle consisting of a WebKey plus its attributes. */ -export interface KeyBundle { - /** The Json web key. */ - key?: JsonWebKey; - /** The key management attributes. */ - attributes?: KeyAttributes; - /** Application specific metadata in the form of key-value pairs. */ - tags?: Record; - /** True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. */ - readonly managed?: boolean; - /** The policy rules under which the key can be exported. */ - releasePolicy?: KeyReleasePolicy; -} - -export function keyBundleDeserializer(item: any): KeyBundle { - return { - key: !item["key"] ? item["key"] : jsonWebKeyDeserializer(item["key"]), - attributes: !item["attributes"] - ? item["attributes"] - : keyAttributesDeserializer(item["attributes"]), - tags: item["tags"], - managed: item["managed"], - releasePolicy: !item["release_policy"] - ? item["release_policy"] - : keyReleasePolicyDeserializer(item["release_policy"]), - }; -} - -/** As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18 */ -export interface JsonWebKey { - /** Key identifier. */ - kid?: string; - /** JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. */ - kty?: JsonWebKeyType; - /** Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. */ - keyOps?: string[]; - /** RSA modulus. */ - n?: Uint8Array; - /** RSA public exponent. */ - e?: Uint8Array; - /** RSA private exponent, or the D component of an EC private key. */ - d?: Uint8Array; - /** RSA private key parameter. */ - dp?: Uint8Array; - /** RSA private key parameter. */ - dq?: Uint8Array; - /** RSA private key parameter. */ - qi?: Uint8Array; - /** RSA secret prime. */ - p?: Uint8Array; - /** RSA secret prime, with p < q. */ - q?: Uint8Array; - /** Symmetric key. */ - k?: Uint8Array; - /** Protected Key, used with 'Bring Your Own Key'. */ - t?: Uint8Array; - /** Elliptic curve name. For valid values, see JsonWebKeyCurveName. */ - crv?: JsonWebKeyCurveName; - /** X component of an EC public key. */ - x?: Uint8Array; - /** Y component of an EC public key. */ - y?: Uint8Array; -} - -export function jsonWebKeySerializer(item: JsonWebKey): any { - return { - kid: item["kid"], - kty: item["kty"], - key_ops: !item["keyOps"] - ? item["keyOps"] - : item["keyOps"].map((p: any) => { - return p; - }), - n: !item["n"] ? item["n"] : uint8ArrayToString(item["n"], "base64url"), - e: !item["e"] ? item["e"] : uint8ArrayToString(item["e"], "base64url"), - d: !item["d"] ? item["d"] : uint8ArrayToString(item["d"], "base64url"), - dp: !item["dp"] ? item["dp"] : uint8ArrayToString(item["dp"], "base64url"), - dq: !item["dq"] ? item["dq"] : uint8ArrayToString(item["dq"], "base64url"), - qi: !item["qi"] ? item["qi"] : uint8ArrayToString(item["qi"], "base64url"), - p: !item["p"] ? item["p"] : uint8ArrayToString(item["p"], "base64url"), - q: !item["q"] ? item["q"] : uint8ArrayToString(item["q"], "base64url"), - k: !item["k"] ? item["k"] : uint8ArrayToString(item["k"], "base64url"), - key_hsm: !item["t"] - ? item["t"] - : uint8ArrayToString(item["t"], "base64url"), - crv: item["crv"], - x: !item["x"] ? item["x"] : uint8ArrayToString(item["x"], "base64url"), - y: !item["y"] ? item["y"] : uint8ArrayToString(item["y"], "base64url"), - }; -} - -export function jsonWebKeyDeserializer(item: any): JsonWebKey { - return { - kid: item["kid"], - kty: item["kty"], - keyOps: !item["key_ops"] - ? item["key_ops"] - : item["key_ops"].map((p: any) => { - return p; - }), - n: !item["n"] - ? item["n"] - : typeof item["n"] === "string" - ? stringToUint8Array(item["n"], "base64url") - : item["n"], - e: !item["e"] - ? item["e"] - : typeof item["e"] === "string" - ? stringToUint8Array(item["e"], "base64url") - : item["e"], - d: !item["d"] - ? item["d"] - : typeof item["d"] === "string" - ? stringToUint8Array(item["d"], "base64url") - : item["d"], - dp: !item["dp"] - ? item["dp"] - : typeof item["dp"] === "string" - ? stringToUint8Array(item["dp"], "base64url") - : item["dp"], - dq: !item["dq"] - ? item["dq"] - : typeof item["dq"] === "string" - ? stringToUint8Array(item["dq"], "base64url") - : item["dq"], - qi: !item["qi"] - ? item["qi"] - : typeof item["qi"] === "string" - ? stringToUint8Array(item["qi"], "base64url") - : item["qi"], - p: !item["p"] - ? item["p"] - : typeof item["p"] === "string" - ? stringToUint8Array(item["p"], "base64url") - : item["p"], - q: !item["q"] - ? item["q"] - : typeof item["q"] === "string" - ? stringToUint8Array(item["q"], "base64url") - : item["q"], - k: !item["k"] - ? item["k"] - : typeof item["k"] === "string" - ? stringToUint8Array(item["k"], "base64url") - : item["k"], - t: !item["key_hsm"] - ? item["key_hsm"] - : typeof item["key_hsm"] === "string" - ? stringToUint8Array(item["key_hsm"], "base64url") - : item["key_hsm"], - crv: item["crv"], - x: !item["x"] - ? item["x"] - : typeof item["x"] === "string" - ? stringToUint8Array(item["x"], "base64url") - : item["x"], - y: !item["y"] - ? item["y"] - : typeof item["y"] === "string" - ? stringToUint8Array(item["y"], "base64url") - : item["y"], - }; -} - -/** The key vault error exception. */ -export interface KeyVaultError { - /** The key vault server error. */ - readonly error?: ErrorModel; -} - -export function keyVaultErrorDeserializer(item: any): KeyVaultError { - return { - error: !item["error"] ? item["error"] : errorDeserializer(item["error"]), - }; -} - -/** The key vault server error. */ -export interface ErrorModel { - /** The error code. */ - readonly code?: string; - /** The error message. */ - readonly message?: string; - /** The key vault server error. */ - readonly innerError?: ErrorModel; -} - -export function errorDeserializer(item: any): ErrorModel { - return { - code: item["code"], - message: item["message"], - innerError: !item["innererror"] - ? item["innererror"] - : errorDeserializer(item["innererror"]), - }; -} - -/** The key import parameters. */ -export interface KeyImportParameters { - /** Whether to import as a hardware key (HSM) or software key. */ - hsm?: boolean; - /** The Json web key */ - key: JsonWebKey; - /** The key management attributes. */ - keyAttributes?: KeyAttributes; - /** Application specific metadata in the form of key-value pairs. */ - tags?: Record; - /** The policy rules under which the key can be exported. */ - releasePolicy?: KeyReleasePolicy; -} - -export function keyImportParametersSerializer(item: KeyImportParameters): any { - return { - Hsm: item["hsm"], - key: jsonWebKeySerializer(item["key"]), - attributes: !item["keyAttributes"] - ? item["keyAttributes"] - : keyAttributesSerializer(item["keyAttributes"]), - tags: item["tags"], - release_policy: !item["releasePolicy"] - ? item["releasePolicy"] - : keyReleasePolicySerializer(item["releasePolicy"]), - }; -} - -/** A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info */ -export interface DeletedKeyBundle { - /** The Json web key. */ - key?: JsonWebKey; - /** The key management attributes. */ - attributes?: KeyAttributes; - /** Application specific metadata in the form of key-value pairs. */ - tags?: Record; - /** True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. */ - readonly managed?: boolean; - /** The policy rules under which the key can be exported. */ - releasePolicy?: KeyReleasePolicy; - /** The url of the recovery object, used to identify and recover the deleted key. */ - recoveryId?: string; - /** The time when the key is scheduled to be purged, in UTC */ - readonly scheduledPurgeDate?: Date; - /** The time when the key was deleted, in UTC */ - readonly deletedDate?: Date; -} - -export function deletedKeyBundleDeserializer(item: any): DeletedKeyBundle { - return { - key: !item["key"] ? item["key"] : jsonWebKeyDeserializer(item["key"]), - attributes: !item["attributes"] - ? item["attributes"] - : keyAttributesDeserializer(item["attributes"]), - tags: item["tags"], - managed: item["managed"], - releasePolicy: !item["release_policy"] - ? item["release_policy"] - : keyReleasePolicyDeserializer(item["release_policy"]), - recoveryId: item["recoveryId"], - scheduledPurgeDate: !item["scheduledPurgeDate"] - ? item["scheduledPurgeDate"] - : new Date(item["scheduledPurgeDate"] * 1000), - deletedDate: !item["deletedDate"] - ? item["deletedDate"] - : new Date(item["deletedDate"] * 1000), - }; -} - -/** The key update parameters. */ -export interface KeyUpdateParameters { - /** Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. */ - keyOps?: JsonWebKeyOperation[]; - /** The attributes of a key managed by the key vault service. */ - keyAttributes?: KeyAttributes; - /** Application specific metadata in the form of key-value pairs. */ - tags?: Record; - /** The policy rules under which the key can be exported. */ - releasePolicy?: KeyReleasePolicy; -} - -export function keyUpdateParametersSerializer(item: KeyUpdateParameters): any { - return { - key_ops: !item["keyOps"] - ? item["keyOps"] - : item["keyOps"].map((p: any) => { - return p; - }), - attributes: !item["keyAttributes"] - ? item["keyAttributes"] - : keyAttributesSerializer(item["keyAttributes"]), - tags: item["tags"], - release_policy: !item["releasePolicy"] - ? item["releasePolicy"] - : keyReleasePolicySerializer(item["releasePolicy"]), - }; -} - -/** The key list result. */ -export interface _KeyListResult { - /** A response message containing a list of keys in the key vault along with a link to the next page of keys. */ - readonly value?: KeyItem[]; - /** The URL to get the next set of keys. */ - readonly nextLink?: string; -} - -export function _keyListResultDeserializer(item: any): _KeyListResult { - return { - value: !item["value"] - ? item["value"] - : keyItemArrayDeserializer(item["value"]), - nextLink: item["nextLink"], - }; -} - -export function keyItemArrayDeserializer(result: Array): any[] { - return result.map((item) => { - return keyItemDeserializer(item); - }); -} - -/** The key item containing key metadata. */ -export interface KeyItem { - /** Key identifier. */ - kid?: string; - /** The key management attributes. */ - attributes?: KeyAttributes; - /** Application specific metadata in the form of key-value pairs. */ - tags?: Record; - /** True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. */ - readonly managed?: boolean; -} - -export function keyItemDeserializer(item: any): KeyItem { - return { - kid: item["kid"], - attributes: !item["attributes"] - ? item["attributes"] - : keyAttributesDeserializer(item["attributes"]), - tags: item["tags"], - managed: item["managed"], - }; -} - -/** The backup key result, containing the backup blob. */ -export interface BackupKeyResult { - /** The backup blob containing the backed up key. */ - readonly value?: Uint8Array; -} - -export function backupKeyResultDeserializer(item: any): BackupKeyResult { - return { - value: !item["value"] - ? item["value"] - : typeof item["value"] === "string" - ? stringToUint8Array(item["value"], "base64url") - : item["value"], - }; -} - -/** The key restore parameters. */ -export interface KeyRestoreParameters { - /** The backup blob associated with a key bundle. */ - keyBundleBackup: Uint8Array; -} - -export function keyRestoreParametersSerializer( - item: KeyRestoreParameters, -): any { - return { value: uint8ArrayToString(item["keyBundleBackup"], "base64url") }; -} - -/** The key operations parameters. */ -export interface KeyOperationsParameters { - /** algorithm identifier */ - algorithm: JsonWebKeyEncryptionAlgorithm; - /** The value to operate on. */ - value: Uint8Array; - /** Cryptographically random, non-repeating initialization vector for symmetric algorithms. */ - iv?: Uint8Array; - /** Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. */ - aad?: Uint8Array; - /** The tag to authenticate when performing decryption with an authenticated algorithm. */ - tag?: Uint8Array; -} - -export function keyOperationsParametersSerializer( - item: KeyOperationsParameters, -): any { - return { - alg: item["algorithm"], - value: uint8ArrayToString(item["value"], "base64url"), - iv: !item["iv"] ? item["iv"] : uint8ArrayToString(item["iv"], "base64url"), - aad: !item["aad"] - ? item["aad"] - : uint8ArrayToString(item["aad"], "base64url"), - tag: !item["tag"] - ? item["tag"] - : uint8ArrayToString(item["tag"], "base64url"), - }; -} - -/** An algorithm used for encryption and decryption. */ -export enum KnownJsonWebKeyEncryptionAlgorithm { - /** RSAES using Optimal Asymmetric Encryption Padding (OAEP), as described in https://tools.ietf.org/html/rfc3447, with the default parameters specified by RFC 3447 in Section A.2.1. Those default parameters are using a hash function of SHA-1 and a mask generation function of MGF1 with SHA-1. */ - RSA_OAEP = "RSA-OAEP", - /** RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 and a mask generation function of MGF1 with SHA-256. */ - RSA_OAEP256 = "RSA-OAEP-256", - /** RSAES-PKCS1-V1_5 key encryption, as described in https://tools.ietf.org/html/rfc3447. */ - RSA1_5 = "RSA1_5", - /** 128-bit AES-GCM. */ - A128_GCM = "A128GCM", - /** 192-bit AES-GCM. */ - A192_GCM = "A192GCM", - /** 256-bit AES-GCM. */ - A256_GCM = "A256GCM", - /** 128-bit AES key wrap. */ - A128_KW = "A128KW", - /** 192-bit AES key wrap. */ - A192_KW = "A192KW", - /** 256-bit AES key wrap. */ - A256_KW = "A256KW", - /** 128-bit AES-CBC. */ - A128_CBC = "A128CBC", - /** 192-bit AES-CBC. */ - A192_CBC = "A192CBC", - /** 256-bit AES-CBC. */ - A256_CBC = "A256CBC", - /** 128-bit AES-CBC with PKCS padding. */ - A128_CBCPAD = "A128CBCPAD", - /** 192-bit AES-CBC with PKCS padding. */ - A192_CBCPAD = "A192CBCPAD", - /** 256-bit AES-CBC with PKCS padding. */ - A256_CBCPAD = "A256CBCPAD", - /** CKM AES key wrap. */ - CKM_AES_KEY_WRAP = "CKM_AES_KEY_WRAP", - /** CKM AES key wrap with padding. */ - CKM_AES_KEY_WRAP_PAD = "CKM_AES_KEY_WRAP_PAD", -} - -/** - * An algorithm used for encryption and decryption. \ - * {@link KnownJsonWebKeyEncryptionAlgorithm} can be used interchangeably with JsonWebKeyEncryptionAlgorithm, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **RSA-OAEP**: RSAES using Optimal Asymmetric Encryption Padding (OAEP), as described in https:\//tools.ietf.org\/html\/rfc3447, with the default parameters specified by RFC 3447 in Section A.2.1. Those default parameters are using a hash function of SHA-1 and a mask generation function of MGF1 with SHA-1. \ - * **RSA-OAEP-256**: RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 and a mask generation function of MGF1 with SHA-256. \ - * **RSA1_5**: RSAES-PKCS1-V1_5 key encryption, as described in https:\//tools.ietf.org\/html\/rfc3447. \ - * **A128GCM**: 128-bit AES-GCM. \ - * **A192GCM**: 192-bit AES-GCM. \ - * **A256GCM**: 256-bit AES-GCM. \ - * **A128KW**: 128-bit AES key wrap. \ - * **A192KW**: 192-bit AES key wrap. \ - * **A256KW**: 256-bit AES key wrap. \ - * **A128CBC**: 128-bit AES-CBC. \ - * **A192CBC**: 192-bit AES-CBC. \ - * **A256CBC**: 256-bit AES-CBC. \ - * **A128CBCPAD**: 128-bit AES-CBC with PKCS padding. \ - * **A192CBCPAD**: 192-bit AES-CBC with PKCS padding. \ - * **A256CBCPAD**: 256-bit AES-CBC with PKCS padding. \ - * **CKM_AES_KEY_WRAP**: CKM AES key wrap. \ - * **CKM_AES_KEY_WRAP_PAD**: CKM AES key wrap with padding. - */ -export type JsonWebKeyEncryptionAlgorithm = string; - -/** The key operation result. */ -export interface KeyOperationResult { - /** Key identifier */ - readonly kid?: string; - /** The result of the operation. */ - readonly result?: Uint8Array; - /** Cryptographically random, non-repeating initialization vector for symmetric algorithms. */ - readonly iv?: Uint8Array; - /** The tag to authenticate when performing decryption with an authenticated algorithm. */ - readonly authenticationTag?: Uint8Array; - /** Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. */ - readonly additionalAuthenticatedData?: Uint8Array; -} - -export function keyOperationResultDeserializer(item: any): KeyOperationResult { - return { - kid: item["kid"], - result: !item["value"] - ? item["value"] - : typeof item["value"] === "string" - ? stringToUint8Array(item["value"], "base64url") - : item["value"], - iv: !item["iv"] - ? item["iv"] - : typeof item["iv"] === "string" - ? stringToUint8Array(item["iv"], "base64url") - : item["iv"], - authenticationTag: !item["tag"] - ? item["tag"] - : typeof item["tag"] === "string" - ? stringToUint8Array(item["tag"], "base64url") - : item["tag"], - additionalAuthenticatedData: !item["aad"] - ? item["aad"] - : typeof item["aad"] === "string" - ? stringToUint8Array(item["aad"], "base64url") - : item["aad"], - }; -} - -/** The key operations parameters. */ -export interface KeySignParameters { - /** The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. */ - algorithm: JsonWebKeySignatureAlgorithm; - /** The value to operate on. */ - value: Uint8Array; -} - -export function keySignParametersSerializer(item: KeySignParameters): any { - return { - alg: item["algorithm"], - value: uint8ArrayToString(item["value"], "base64url"), - }; -} - -/** The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. */ -export enum KnownJsonWebKeySignatureAlgorithm { - /** RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https://tools.ietf.org/html/rfc7518 */ - PS256 = "PS256", - /** RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https://tools.ietf.org/html/rfc7518 */ - PS384 = "PS384", - /** RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https://tools.ietf.org/html/rfc7518 */ - PS512 = "PS512", - /** RSASSA-PKCS1-v1_5 using SHA-256, as described in https://tools.ietf.org/html/rfc7518 */ - RS256 = "RS256", - /** RSASSA-PKCS1-v1_5 using SHA-384, as described in https://tools.ietf.org/html/rfc7518 */ - RS384 = "RS384", - /** RSASSA-PKCS1-v1_5 using SHA-512, as described in https://tools.ietf.org/html/rfc7518 */ - RS512 = "RS512", - /** Reserved */ - RSNULL = "RSNULL", - /** ECDSA using P-256 and SHA-256, as described in https://tools.ietf.org/html/rfc7518. */ - ES256 = "ES256", - /** ECDSA using P-384 and SHA-384, as described in https://tools.ietf.org/html/rfc7518 */ - ES384 = "ES384", - /** ECDSA using P-521 and SHA-512, as described in https://tools.ietf.org/html/rfc7518 */ - ES512 = "ES512", - /** ECDSA using P-256K and SHA-256, as described in https://tools.ietf.org/html/rfc7518 */ - ES256_K = "ES256K", -} - -/** - * The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. \ - * {@link KnownJsonWebKeySignatureAlgorithm} can be used interchangeably with JsonWebKeySignatureAlgorithm, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PS256**: RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **PS384**: RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **PS512**: RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **RS256**: RSASSA-PKCS1-v1_5 using SHA-256, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **RS384**: RSASSA-PKCS1-v1_5 using SHA-384, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **RS512**: RSASSA-PKCS1-v1_5 using SHA-512, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **RSNULL**: Reserved \ - * **ES256**: ECDSA using P-256 and SHA-256, as described in https:\//tools.ietf.org\/html\/rfc7518. \ - * **ES384**: ECDSA using P-384 and SHA-384, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **ES512**: ECDSA using P-521 and SHA-512, as described in https:\//tools.ietf.org\/html\/rfc7518 \ - * **ES256K**: ECDSA using P-256K and SHA-256, as described in https:\//tools.ietf.org\/html\/rfc7518 - */ -export type JsonWebKeySignatureAlgorithm = string; - -/** The key verify parameters. */ -export interface KeyVerifyParameters { - /** The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. */ - algorithm: JsonWebKeySignatureAlgorithm; - /** The digest used for signing. */ - digest: Uint8Array; - /** The signature to be verified. */ - signature: Uint8Array; -} - -export function keyVerifyParametersSerializer(item: KeyVerifyParameters): any { - return { - alg: item["algorithm"], - digest: uint8ArrayToString(item["digest"], "base64url"), - value: uint8ArrayToString(item["signature"], "base64url"), - }; -} - -/** The key verify result. */ -export interface KeyVerifyResult { - /** True if the signature is verified, otherwise false. */ - readonly value?: boolean; -} - -export function keyVerifyResultDeserializer(item: any): KeyVerifyResult { - return { - value: item["value"], - }; -} - -/** The release key parameters. */ -export interface KeyReleaseParameters { - /** The attestation assertion for the target of the key release. */ - targetAttestationToken: string; - /** A client provided nonce for freshness. */ - nonce?: string; - /** The encryption algorithm to use to protected the exported key material */ - enc?: KeyEncryptionAlgorithm; -} - -export function keyReleaseParametersSerializer( - item: KeyReleaseParameters, -): any { - return { - target: item["targetAttestationToken"], - nonce: item["nonce"], - enc: item["enc"], - }; -} - -/** The encryption algorithm to use to protected the exported key material */ -export enum KnownKeyEncryptionAlgorithm { - /** The CKM_RSA_AES_KEY_WRAP key wrap mechanism. */ - CKM_RSA_AES_KEY_WRAP = "CKM_RSA_AES_KEY_WRAP", - /** The RSA_AES_KEY_WRAP_256 key wrap mechanism. */ - RSA_AES_KEY_WRAP_256 = "RSA_AES_KEY_WRAP_256", - /** The RSA_AES_KEY_WRAP_384 key wrap mechanism. */ - RSA_AES_KEY_WRAP_384 = "RSA_AES_KEY_WRAP_384", -} - -/** - * The encryption algorithm to use to protected the exported key material \ - * {@link KnownKeyEncryptionAlgorithm} can be used interchangeably with KeyEncryptionAlgorithm, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **CKM_RSA_AES_KEY_WRAP**: The CKM_RSA_AES_KEY_WRAP key wrap mechanism. \ - * **RSA_AES_KEY_WRAP_256**: The RSA_AES_KEY_WRAP_256 key wrap mechanism. \ - * **RSA_AES_KEY_WRAP_384**: The RSA_AES_KEY_WRAP_384 key wrap mechanism. - */ -export type KeyEncryptionAlgorithm = string; - -/** The release result, containing the released key. */ -export interface KeyReleaseResult { - /** A signed object containing the released key. */ - readonly value?: string; -} - -export function keyReleaseResultDeserializer(item: any): KeyReleaseResult { - return { - value: item["value"], - }; -} - -/** A list of keys that have been deleted in this vault. */ -export interface _DeletedKeyListResult { - /** A response message containing a list of deleted keys in the key vault along with a link to the next page of deleted keys. */ - readonly value?: DeletedKeyItem[]; - /** The URL to get the next set of deleted keys. */ - readonly nextLink?: string; -} - -export function _deletedKeyListResultDeserializer( - item: any, -): _DeletedKeyListResult { - return { - value: !item["value"] - ? item["value"] - : deletedKeyItemArrayDeserializer(item["value"]), - nextLink: item["nextLink"], - }; -} - -export function deletedKeyItemArrayDeserializer( - result: Array, -): any[] { - return result.map((item) => { - return deletedKeyItemDeserializer(item); - }); -} - -/** The deleted key item containing the deleted key metadata and information about deletion. */ -export interface DeletedKeyItem { - /** Key identifier. */ - kid?: string; - /** The key management attributes. */ - attributes?: KeyAttributes; - /** Application specific metadata in the form of key-value pairs. */ - tags?: Record; - /** True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. */ - readonly managed?: boolean; - /** The url of the recovery object, used to identify and recover the deleted key. */ - recoveryId?: string; - /** The time when the key is scheduled to be purged, in UTC */ - readonly scheduledPurgeDate?: Date; - /** The time when the key was deleted, in UTC */ - readonly deletedDate?: Date; -} - -export function deletedKeyItemDeserializer(item: any): DeletedKeyItem { - return { - kid: item["kid"], - attributes: !item["attributes"] - ? item["attributes"] - : keyAttributesDeserializer(item["attributes"]), - tags: item["tags"], - managed: item["managed"], - recoveryId: item["recoveryId"], - scheduledPurgeDate: !item["scheduledPurgeDate"] - ? item["scheduledPurgeDate"] - : new Date(item["scheduledPurgeDate"] * 1000), - deletedDate: !item["deletedDate"] - ? item["deletedDate"] - : new Date(item["deletedDate"] * 1000), - }; -} - -/** Management policy for a key. */ -export interface KeyRotationPolicy { - /** The key policy id. */ - readonly id?: string; - /** Actions that will be performed by Key Vault over the lifetime of a key. For preview, lifetimeActions can only have two items at maximum: one for rotate, one for notify. Notification time would be default to 30 days before expiry and it is not configurable. */ - lifetimeActions?: LifetimeActions[]; - /** The key rotation policy attributes. */ - attributes?: KeyRotationPolicyAttributes; -} - -export function keyRotationPolicySerializer(item: KeyRotationPolicy): any { - return { - lifetimeActions: !item["lifetimeActions"] - ? item["lifetimeActions"] - : lifetimeActionsArraySerializer(item["lifetimeActions"]), - attributes: !item["attributes"] - ? item["attributes"] - : keyRotationPolicyAttributesSerializer(item["attributes"]), - }; -} - -export function keyRotationPolicyDeserializer(item: any): KeyRotationPolicy { - return { - id: item["id"], - lifetimeActions: !item["lifetimeActions"] - ? item["lifetimeActions"] - : lifetimeActionsArrayDeserializer(item["lifetimeActions"]), - attributes: !item["attributes"] - ? item["attributes"] - : keyRotationPolicyAttributesDeserializer(item["attributes"]), - }; -} - -export function lifetimeActionsArraySerializer( - result: Array, -): any[] { - return result.map((item) => { - return lifetimeActionsSerializer(item); - }); -} - -export function lifetimeActionsArrayDeserializer( - result: Array, -): any[] { - return result.map((item) => { - return lifetimeActionsDeserializer(item); - }); -} - -/** Action and its trigger that will be performed by Key Vault over the lifetime of a key. */ -export interface LifetimeActions { - /** The condition that will execute the action. */ - trigger?: LifetimeActionsTrigger; - /** The action that will be executed. */ - action?: LifetimeActionsType; -} - -export function lifetimeActionsSerializer(item: LifetimeActions): any { - return { - trigger: !item["trigger"] - ? item["trigger"] - : lifetimeActionsTriggerSerializer(item["trigger"]), - action: !item["action"] - ? item["action"] - : lifetimeActionsTypeSerializer(item["action"]), - }; -} - -export function lifetimeActionsDeserializer(item: any): LifetimeActions { - return { - trigger: !item["trigger"] - ? item["trigger"] - : lifetimeActionsTriggerDeserializer(item["trigger"]), - action: !item["action"] - ? item["action"] - : lifetimeActionsTypeDeserializer(item["action"]), - }; -} - -/** A condition to be satisfied for an action to be executed. */ -export interface LifetimeActionsTrigger { - /** Time after creation to attempt to rotate. It only applies to rotate. It will be in ISO 8601 duration format. Example: 90 days : "P90D" */ - timeAfterCreate?: string; - /** Time before expiry to attempt to rotate or notify. It will be in ISO 8601 duration format. Example: 90 days : "P90D" */ - timeBeforeExpiry?: string; -} - -export function lifetimeActionsTriggerSerializer( - item: LifetimeActionsTrigger, -): any { - return { - timeAfterCreate: item["timeAfterCreate"], - timeBeforeExpiry: item["timeBeforeExpiry"], - }; -} - -export function lifetimeActionsTriggerDeserializer( - item: any, -): LifetimeActionsTrigger { - return { - timeAfterCreate: item["timeAfterCreate"], - timeBeforeExpiry: item["timeBeforeExpiry"], - }; -} - -/** The action that will be executed. */ -export interface LifetimeActionsType { - /** The type of the action. The value should be compared case-insensitively. */ - type?: KeyRotationPolicyAction; -} - -export function lifetimeActionsTypeSerializer(item: LifetimeActionsType): any { - return { type: item["type"] }; -} - -export function lifetimeActionsTypeDeserializer( - item: any, -): LifetimeActionsType { - return { - type: item["type"], - }; -} - -/** The type of the action. The value should be compared case-insensitively. */ -export type KeyRotationPolicyAction = "Rotate" | "Notify"; - -/** The key rotation policy attributes. */ -export interface KeyRotationPolicyAttributes { - /** The expiryTime will be applied on the new key version. It should be at least 28 days. It will be in ISO 8601 Format. Examples: 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: P1Y10D */ - expiryTime?: string; - /** The key rotation policy created time in UTC. */ - readonly created?: Date; - /** The key rotation policy's last updated time in UTC. */ - readonly updated?: Date; -} - -export function keyRotationPolicyAttributesSerializer( - item: KeyRotationPolicyAttributes, -): any { - return { expiryTime: item["expiryTime"] }; -} - -export function keyRotationPolicyAttributesDeserializer( - item: any, -): KeyRotationPolicyAttributes { - return { - expiryTime: item["expiryTime"], - created: !item["created"] - ? item["created"] - : new Date(item["created"] * 1000), - updated: !item["updated"] - ? item["updated"] - : new Date(item["updated"] * 1000), - }; -} - -/** The get random bytes request object. */ -export interface GetRandomBytesRequest { - /** The requested number of random bytes. */ - count: number; -} - -export function getRandomBytesRequestSerializer( - item: GetRandomBytesRequest, -): any { - return { count: item["count"] }; -} - -/** The get random bytes response object containing the bytes. */ -export interface RandomBytes { - /** The bytes encoded as a base64url string. */ - value: Uint8Array; -} - -export function randomBytesDeserializer(item: any): RandomBytes { - return { - value: - typeof item["value"] === "string" - ? stringToUint8Array(item["value"], "base64url") - : item["value"], - }; -} - -/** The available API versions. */ -export enum KnownVersions { - /** The 7.5 API version. */ - "v7.5" = "7.5", - /** The 7.6-preview.1 API version. */ - "v7.6_preview.1" = "7.6-preview.1", -} diff --git a/sdk/keyvault/keyvault-keys/src/generated/static-helpers/pagingHelpers.ts b/sdk/keyvault/keyvault-keys/src/generated/static-helpers/pagingHelpers.ts deleted file mode 100644 index 97a81e74e301..000000000000 --- a/sdk/keyvault/keyvault-keys/src/generated/static-helpers/pagingHelpers.ts +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { - Client, - createRestError, - PathUncheckedResponse, -} from "@azure-rest/core-client"; -import { RestError } from "@azure/core-rest-pipeline"; - -/** - * Options for the byPage method - */ -export interface PageSettings { - /** - * A reference to a specific page to start iterating from. - */ - continuationToken?: string; -} - -/** - * An interface that describes a page of results. - */ -export type ContinuablePage = TPage & { - /** - * The token that keeps track of where to continue the iterator - */ - continuationToken?: string; -}; - -/** - * An interface that allows async iterable iteration both to completion and by page. - */ -export interface PagedAsyncIterableIterator< - TElement, - TPage = TElement[], - TPageSettings extends PageSettings = PageSettings, -> { - /** - * The next method, part of the iteration protocol - */ - next(): Promise>; - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator< - TElement, - TPage, - TPageSettings - >; - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: ( - settings?: TPageSettings, - ) => AsyncIterableIterator>; -} - -/** - * An interface that describes how to communicate with the service. - */ -export interface PagedResult< - TElement, - TPage = TElement[], - TPageSettings extends PageSettings = PageSettings, -> { - /** - * Link to the first page of results. - */ - firstPageLink?: string; - /** - * A method that returns a page of results. - */ - getPage: ( - pageLink?: string, - ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; - /** - * a function to implement the `byPage` method on the paged async iterator. - */ - byPage?: ( - settings?: TPageSettings, - ) => AsyncIterableIterator>; - - /** - * A function to extract elements from a page. - */ - toElements?: (page: TPage) => TElement[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - -/** - * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator - */ -export function buildPagedAsyncIterator< - TElement, - TPage = TElement[], - TPageSettings extends PageSettings = PageSettings, - TResponse extends PathUncheckedResponse = PathUncheckedResponse, ->( - client: Client, - getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => PromiseLike, - expectedStatuses: string[], - options: BuildPagedAsyncIteratorOptions = {}, -): PagedAsyncIterableIterator { - const itemName = options.itemName ?? "value"; - const nextLinkName = options.nextLinkName ?? "nextLink"; - const pagedResult: PagedResult = { - getPage: async (pageLink?: string) => { - const result = - pageLink === undefined - ? await getInitialResponse() - : await client.pathUnchecked(pageLink).get(); - checkPagingRequest(result, expectedStatuses); - const results = await processResponseBody(result as TResponse); - const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName) as TPage; - return { - page: values, - nextPageLink: nextLink, - }; - }, - byPage: (settings?: TPageSettings) => { - const { continuationToken } = settings ?? {}; - return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, - }); - }, - }; - return getPagedAsyncIterator(pagedResult); -} - -/** - * returns an async iterator that iterates over results. It also has a `byPage` - * method that returns pages of items at once. - * - * @param pagedResult - an object that specifies how to get pages. - * @returns a paged async iterator that iterates over results. - */ - -function getPagedAsyncIterator< - TElement, - TPage = TElement[], - TPageSettings extends PageSettings = PageSettings, ->( - pagedResult: PagedResult, -): PagedAsyncIterableIterator { - const iter = getItemAsyncIterator( - pagedResult, - ); - return { - next() { - return iter.next(); - }, - [Symbol.asyncIterator]() { - return this; - }, - byPage: - pagedResult?.byPage ?? - ((settings?: TPageSettings) => { - const { continuationToken } = settings ?? {}; - return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, - }); - }), - }; -} - -async function* getItemAsyncIterator< - TElement, - TPage, - TPageSettings extends PageSettings, ->( - pagedResult: PagedResult, -): AsyncIterableIterator { - const pages = getPageAsyncIterator(pagedResult); - for await (const page of pages) { - yield* page as unknown as TElement[]; - } -} - -async function* getPageAsyncIterator< - TElement, - TPage, - TPageSettings extends PageSettings, ->( - pagedResult: PagedResult, - options: { - pageLink?: string; - } = {}, -): AsyncIterableIterator> { - const { pageLink } = options; - let response = await pagedResult.getPage( - pageLink ?? pagedResult.firstPageLink, - ); - if (!response) { - return; - } - let result = response.page as ContinuablePage; - result.continuationToken = response.nextPageLink; - yield result; - while (response.nextPageLink) { - response = await pagedResult.getPage(response.nextPageLink); - if (!response) { - return; - } - result = response.page as ContinuablePage; - result.continuationToken = response.nextPageLink; - yield result; - } -} - -/** - * Gets for the value of nextLink in the body - */ -function getNextLink(body: unknown, nextLinkName?: string): string | undefined { - if (!nextLinkName) { - return undefined; - } - - const nextLink = (body as Record)[nextLinkName]; - - if ( - typeof nextLink !== "string" && - typeof nextLink !== "undefined" && - nextLink !== null - ) { - throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}`, - ); - } - - if (nextLink === null) { - return undefined; - } - - return nextLink; -} - -/** - * Gets the elements of the current request in the body. - */ -function getElements(body: unknown, itemName: string): T[] { - const value = (body as Record)[itemName] as T[]; - if (!Array.isArray(value)) { - throw new RestError( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, - ); - } - - return value ?? []; -} - -/** - * Checks if a request failed - */ -function checkPagingRequest( - response: PathUncheckedResponse, - expectedStatuses: string[], -): void { - if (!expectedStatuses.includes(response.status)) { - throw createRestError( - `Pagination failed with unexpected statusCode ${response.status}`, - response, - ); - } -} diff --git a/sdk/keyvault/keyvault-keys/src/identifier.ts b/sdk/keyvault/keyvault-keys/src/identifier.ts deleted file mode 100644 index 3caf2d82fde4..000000000000 --- a/sdk/keyvault/keyvault-keys/src/identifier.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { parseKeyVaultIdentifier } from "@azure/keyvault-common"; - -/** - * Represents the segments that compose a Key Vault Key Id. - */ -export interface KeyVaultKeyIdentifier { - /** - * The complete representation of the Key Vault Key Id. For example: - * - * https://.vault.azure.net/keys// - * - */ - sourceId: string; - - /** - * The URL of the Azure Key Vault instance to which the Key belongs. - */ - vaultUrl: string; - - /** - * The version of Key Vault Key. Might be undefined. - */ - version?: string; - - /** - * The name of the Key Vault Key. - */ - name: string; -} - -/** - * Parses the given Key Vault Key Id. An example is: - * - * https://.vault.azure.net/keys// - * - * On parsing the above Id, this function returns: - *```ts - * { - * sourceId: "https://.vault.azure.net/keys//", - * vaultUrl: "https://.vault.azure.net", - * version: "", - * name: "" - * } - *``` - * @param id - The Id of the Key Vault Key. - */ -export function parseKeyVaultKeyIdentifier(id: string): KeyVaultKeyIdentifier { - const urlParts = id.split("/"); - const collection = urlParts[3]; - - return { - sourceId: id, - ...parseKeyVaultIdentifier(collection, id), - }; -} diff --git a/sdk/keyvault/keyvault-keys/src/index.ts b/sdk/keyvault/keyvault-keys/src/index.ts deleted file mode 100644 index d68eaec1270b..000000000000 --- a/sdk/keyvault/keyvault-keys/src/index.ts +++ /dev/null @@ -1,966 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/// - -import type { TokenCredential } from "@azure/core-auth"; - -import { logger } from "./log.js"; - -import { PageSettings, PagedAsyncIterableIterator } from "@azure/core-paging"; -import { PollOperationState, PollerLike } from "@azure/core-lro"; - -import { DeletionRecoveryLevel, KnownDeletionRecoveryLevel } from "./generated/models/index.js"; -import type { KeyVaultClientOptionalParams } from "./generated/keyVaultClient.js"; -import { KeyVaultClient } from "./generated/keyVaultClient.js"; -import { SDK_VERSION } from "./constants.js"; -import { keyVaultAuthenticationPolicy } from "@azure/keyvault-common"; - -import { DeleteKeyPoller } from "./lro/delete/poller.js"; -import { RecoverDeletedKeyPoller } from "./lro/recover/poller.js"; - -import { - BackupKeyOptions, - BeginDeleteKeyOptions, - BeginRecoverDeletedKeyOptions, - CreateEcKeyOptions, - CreateKeyOptions, - CreateOctKeyOptions, - CreateRsaKeyOptions, - CryptographyClientOptions, - CryptographyOptions, - DeletedKey, - GetCryptographyClientOptions, - GetDeletedKeyOptions, - GetKeyOptions, - GetKeyRotationPolicyOptions, - GetRandomBytesOptions, - ImportKeyOptions, - JsonWebKey, - KeyClientOptions, - KeyExportEncryptionAlgorithm, - KeyOperation, - KeyPollerOptions, - KeyProperties, - KeyReleasePolicy, - KeyRotationLifetimeAction, - KeyRotationPolicy, - KeyRotationPolicyAction, - KeyRotationPolicyProperties, - KeyType, - KeyVaultKey, - KnownKeyExportEncryptionAlgorithm, - KnownKeyOperations, - KnownKeyTypes, - LATEST_API_VERSION, - ListDeletedKeysOptions, - ListPropertiesOfKeyVersionsOptions, - ListPropertiesOfKeysOptions, - PurgeDeletedKeyOptions, - ReleaseKeyOptions, - ReleaseKeyResult, - RestoreKeyBackupOptions, - RotateKeyOptions, - UpdateKeyPropertiesOptions, - UpdateKeyRotationPolicyOptions, -} from "./keysModels.js"; - -import { CryptographyClient } from "./cryptographyClient.js"; - -import { - AesCbcDecryptParameters, - AesCbcEncryptParameters, - AesCbcEncryptionAlgorithm, - AesGcmDecryptParameters, - AesGcmEncryptParameters, - AesGcmEncryptionAlgorithm, - DecryptOptions, - DecryptParameters, - DecryptResult, - EncryptOptions, - EncryptParameters, - EncryptResult, - EncryptionAlgorithm, - KeyCurveName, - KeyWrapAlgorithm, - KnownEncryptionAlgorithms, - KnownKeyCurveNames, - KnownSignatureAlgorithms, - RsaDecryptParameters, - RsaEncryptParameters, - RsaEncryptionAlgorithm, - SignOptions, - SignResult, - SignatureAlgorithm, - UnwrapKeyOptions, - UnwrapResult, - VerifyDataOptions, - VerifyOptions, - VerifyResult, - WrapKeyOptions, - WrapResult, -} from "./cryptographyClientModels.js"; - -import { KeyVaultKeyIdentifier, parseKeyVaultKeyIdentifier } from "./identifier.js"; -import { - getDeletedKeyFromDeletedKeyItem, - getKeyFromKeyBundle, - getKeyPropertiesFromKeyItem, - keyRotationTransformations, - mapPagedAsyncIterable, -} from "./transformations.js"; -import { tracingClient } from "./tracing.js"; -import { bearerTokenAuthenticationPolicyName } from "@azure/core-rest-pipeline"; - -export { - CryptographyClientOptions, - KeyClientOptions, - BackupKeyOptions, - CreateEcKeyOptions, - CreateKeyOptions, - CreateRsaKeyOptions, - CreateOctKeyOptions, - CryptographyClient, - CryptographyOptions, - RsaEncryptionAlgorithm, - RsaDecryptParameters, - AesGcmEncryptionAlgorithm, - AesGcmDecryptParameters, - AesCbcEncryptionAlgorithm, - AesCbcDecryptParameters, - DecryptParameters, - DecryptOptions, - DecryptResult, - DeletedKey, - DeletionRecoveryLevel, - KnownDeletionRecoveryLevel, - RsaEncryptParameters, - AesGcmEncryptParameters, - AesCbcEncryptParameters, - EncryptParameters, - EncryptOptions, - EncryptResult, - GetDeletedKeyOptions, - GetKeyOptions, - GetRandomBytesOptions, - ImportKeyOptions, - JsonWebKey, - KeyCurveName, - KnownKeyCurveNames, - KnownKeyExportEncryptionAlgorithm, - EncryptionAlgorithm, - KnownEncryptionAlgorithms, - KeyOperation, - KnownKeyOperations, - KeyType, - KnownKeyTypes, - KeyPollerOptions, - BeginDeleteKeyOptions, - BeginRecoverDeletedKeyOptions, - KeyProperties, - SignatureAlgorithm, - KnownSignatureAlgorithms, - KeyVaultKey, - KeyWrapAlgorithm, - ListPropertiesOfKeysOptions, - ListPropertiesOfKeyVersionsOptions, - ListDeletedKeysOptions, - PageSettings, - PagedAsyncIterableIterator, - KeyVaultKeyIdentifier, - parseKeyVaultKeyIdentifier, - PollOperationState, - PollerLike, - PurgeDeletedKeyOptions, - RestoreKeyBackupOptions, - RotateKeyOptions, - SignOptions, - SignResult, - UnwrapKeyOptions, - UnwrapResult, - UpdateKeyPropertiesOptions, - VerifyOptions, - VerifyDataOptions, - VerifyResult, - WrapKeyOptions, - WrapResult, - ReleaseKeyOptions, - ReleaseKeyResult, - KeyReleasePolicy, - KeyExportEncryptionAlgorithm, - GetCryptographyClientOptions, - KeyRotationPolicyAction, - KeyRotationPolicyProperties, - KeyRotationPolicy, - KeyRotationLifetimeAction, - UpdateKeyRotationPolicyOptions, - GetKeyRotationPolicyOptions, - logger, -}; - -/** - * The KeyClient provides methods to manage {@link KeyVaultKey} in the - * Azure Key Vault. The client supports creating, retrieving, updating, - * deleting, purging, backing up, restoring and listing KeyVaultKeys. The - * client also supports listing {@link DeletedKey} for a soft-delete enabled Azure Key - * Vault. - */ -export class KeyClient { - /** - * The base URL to the vault - */ - public readonly vaultUrl: string; - - /** - * A reference to the auto-generated Key Vault HTTP client. - */ - private readonly client: KeyVaultClient; - - /** - * A reference to the credential that was used to construct this client. - * Later used to instantiate a {@link CryptographyClient} with the same credential. - */ - private readonly credential: TokenCredential; - - /** - * Creates an instance of KeyClient. - * - * Example usage: - * ```ts - * import { KeyClient } from "@azure/keyvault-keys"; - * import { DefaultAzureCredential } from "@azure/identity"; - * - * let vaultUrl = `https://.vault.azure.net`; - * let credentials = new DefaultAzureCredential(); - * - * let client = new KeyClient(vaultUrl, credentials); - * ``` - * @param vaultUrl - the URL of the Key Vault. It should have this shape: `https://${your-key-vault-name}.vault.azure.net`. You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.ms/azsdk/blog/vault-uri for details. - * @param credential - An object that implements the `TokenCredential` interface used to authenticate requests to the service. Use the \@azure/identity package to create a credential that suits your needs. - * @param pipelineOptions - Pipeline options used to configure Key Vault API requests. Omit this parameter to use the default pipeline configuration. - */ - constructor( - vaultUrl: string, - credential: TokenCredential, - pipelineOptions: KeyClientOptions = {}, - ) { - this.vaultUrl = vaultUrl; - - const libInfo = `azsdk-js-keyvault-keys/${SDK_VERSION}`; - - const userAgentOptions = pipelineOptions.userAgentOptions; - - pipelineOptions.userAgentOptions = { - userAgentPrefix: - userAgentOptions && userAgentOptions.userAgentPrefix - ? `${userAgentOptions.userAgentPrefix} ${libInfo}` - : libInfo, - }; - - const internalPipelineOptions: KeyVaultClientOptionalParams = { - ...pipelineOptions, - apiVersion: pipelineOptions.serviceVersion || LATEST_API_VERSION, - loggingOptions: { - logger: logger.info, - additionalAllowedHeaderNames: [ - "x-ms-keyvault-region", - "x-ms-keyvault-network-info", - "x-ms-keyvault-service-version", - ], - }, - }; - - this.credential = credential; - this.client = new KeyVaultClient(vaultUrl, credential, internalPipelineOptions); - - this.client.pipeline.removePolicy({ name: bearerTokenAuthenticationPolicyName }); - this.client.pipeline.addPolicy(keyVaultAuthenticationPolicy(credential, pipelineOptions)); - // Workaround for: https://github.com/Azure/azure-sdk-for-js/issues/31843 - this.client.pipeline.addPolicy({ - name: "ContentTypePolicy", - sendRequest(request, next) { - const contentType = request.headers.get("Content-Type") ?? ""; - if (contentType.startsWith("application/json")) { - request.headers.set("Content-Type", "application/json"); - } - return next(request); - }, - }); - } - - /** - * The create key operation can be used to create any key type in Azure Key Vault. If the named key - * already exists, Azure Key Vault creates a new version of the key. It requires the keys/create - * permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * // Create an elliptic-curve key: - * let result = await client.createKey("MyKey", "EC"); - * ``` - * Creates a new key, stores it, then returns key parameters and properties to the client. - * @param name - The name of the key. - * @param keyType - The type of the key. One of the following: 'EC', 'EC-HSM', 'RSA', 'RSA-HSM', 'oct'. - * @param options - The optional parameters. - */ - public createKey( - name: string, - keyType: KeyType, - options: CreateKeyOptions = {}, - ): Promise { - return tracingClient.withSpan("KeyClient.createKey", options, async (updatedOptions) => { - const response = await this.client.createKey( - name, - { - kty: keyType, - curve: options?.curve, - keyAttributes: { - enabled: options?.enabled, - notBefore: options?.notBefore, - expires: options?.expiresOn, - exportable: options?.exportable, - }, - keyOps: options?.keyOps, - keySize: options?.keySize, - releasePolicy: options?.releasePolicy, - tags: options?.tags, - }, - updatedOptions, - ); - return getKeyFromKeyBundle(response); - }); - } - - /** - * The createEcKey method creates a new elliptic curve key in Azure Key Vault. If the named key - * already exists, Azure Key Vault creates a new version of the key. It requires the keys/create - * permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * let result = await client.createEcKey("MyKey", { curve: "P-256" }); - * ``` - * Creates a new key, stores it, then returns key parameters and properties to the client. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public async createEcKey(name: string, options?: CreateEcKeyOptions): Promise { - const keyType = options?.hsm ? KnownKeyTypes.ECHSM : KnownKeyTypes.EC; - return this.createKey(name, keyType, options); - } - - /** - * The createRSAKey method creates a new RSA key in Azure Key Vault. If the named key - * already exists, Azure Key Vault creates a new version of the key. It requires the keys/create - * permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * let result = await client.createRsaKey("MyKey", { keySize: 2048 }); - * ``` - * Creates a new key, stores it, then returns key parameters and properties to the client. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public async createRsaKey(name: string, options?: CreateRsaKeyOptions): Promise { - const keyType = options?.hsm ? KnownKeyTypes.RSAHSM : KnownKeyTypes.RSA; - return this.createKey(name, keyType, options); - } - - /** - * The createOctKey method creates a new OCT key in Azure Key Vault. If the named key - * already exists, Azure Key Vault creates a new version of the key. It requires the keys/create - * permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * let result = await client.createOctKey("MyKey", { hsm: true }); - * ``` - * Creates a new key, stores it, then returns key parameters and properties to the client. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public async createOctKey(name: string, options?: CreateOctKeyOptions): Promise { - const keyType = options?.hsm ? KnownKeyTypes.OctHSM : KnownKeyTypes.Oct; - return this.createKey(name, keyType, options); - } - - /** - * The import key operation may be used to import any key type into an Azure Key Vault. If the - * named key already exists, Azure Key Vault creates a new version of the key. This operation - * requires the keys/import permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * // Key contents in myKeyContents - * let result = await client.importKey("MyKey", myKeyContents); - * ``` - * Imports an externally created key, stores it, and returns key parameters and properties - * to the client. - * @param name - Name for the imported key. - * @param key - The JSON web key. - * @param options - The optional parameters. - */ - public importKey( - name: string, - key: JsonWebKey, - options: ImportKeyOptions = {}, - ): Promise { - return tracingClient.withSpan(`KeyClient.importKey`, options, async (updatedOptions) => { - const { enabled, notBefore, expiresOn: expires, exportable, releasePolicy, tags } = options; - const keyAttributes = { - enabled, - notBefore, - expires, - exportable, - }; - const parameters = { - key, - hsm: options?.hardwareProtected, - keyAttributes, - releasePolicy, - tags, - }; - const response = await this.client.importKey(name, parameters, updatedOptions); - return getKeyFromKeyBundle(response); - }); - } - - /** - * Gets a {@link CryptographyClient} for the given key. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * // get a cryptography client for a given key - * let cryptographyClient = client.getCryptographyClient("MyKey"); - * ``` - * @param name - The name of the key used to perform cryptographic operations. - * @param version - Optional version of the key used to perform cryptographic operations. - * @returns - A {@link CryptographyClient} using the same options, credentials, and http client as this {@link KeyClient} - */ - public getCryptographyClient( - keyName: string, - options?: GetCryptographyClientOptions, - ): CryptographyClient { - const keyUrl = new URL( - ["keys", keyName, options?.keyVersion].filter(Boolean).join("/"), - this.vaultUrl, - ); - - // The goals of this method are discoverability and performance (by sharing a client and pipeline). - // The existing cryptography client does not accept a pipeline as an argument, nor does it expose it. - // In order to avoid publicly exposing the pipeline we will pass in the underlying client as an undocumented - // property to the constructor so that crypto providers downstream can use it. - const constructorOptions: CryptographyClientOptions & { generatedClient: KeyVaultClient } = { - generatedClient: this.client, - }; - const cryptoClient = new CryptographyClient( - keyUrl.toString(), - this.credential, - constructorOptions, - ); - return cryptoClient; - } - - /** - * The delete operation applies to any key stored in Azure Key Vault. Individual versions - * of a key can not be deleted, only all versions of a given key at once. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the key is deleted. - * - * This operation requires the keys/delete permission. - * - * Example usage: - * ```ts - * const client = new KeyClient(url, credentials); - * await client.createKey("MyKey", "EC"); - * const poller = await client.beginDeleteKey("MyKey"); - * - * // Serializing the poller - * const serialized = poller.toString(); - * // A new poller can be created with: - * // await client.beginDeleteKey("MyKey", { resumeFrom: serialized }); - * - * // Waiting until it's done - * const deletedKey = await poller.pollUntilDone(); - * console.log(deletedKey); - * ``` - * Deletes a key from a specified key vault. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public async beginDeleteKey( - name: string, - options: BeginDeleteKeyOptions = {}, - ): Promise, DeletedKey>> { - const poller = new DeleteKeyPoller({ - name, - client: this.client, - intervalInMs: options.intervalInMs, - resumeFrom: options.resumeFrom, - operationOptions: options, - }); - - // This will initialize the poller's operation (the deletion of the key). - await poller.poll(); - - return poller; - } - - /** - * The updateKeyProperties method changes specified properties of an existing stored key. Properties that - * are not specified in the request are left unchanged. The value of a key itself cannot be - * changed. This operation requires the keys/set permission. - * - * Example usage: - * ```ts - * let keyName = "MyKey"; - * let client = new KeyClient(vaultUrl, credentials); - * let key = await client.getKey(keyName); - * let result = await client.updateKeyProperties(keyName, key.properties.version, { enabled: false }); - * ``` - * Updates the properties associated with a specified key in a given key vault. - * @param name - The name of the key. - * @param keyVersion - The version of the key. - * @param options - The optional parameters. - */ - public updateKeyProperties( - name: string, - keyVersion: string, - options?: UpdateKeyPropertiesOptions, - ): Promise; - /** - * The updateKeyProperties method changes specified properties of the latest version of an existing stored key. Properties that - * are not specified in the request are left unchanged. The value of a key itself cannot be - * changed. This operation requires the keys/set permission. - * - * Example usage: - * ```ts - * let keyName = "MyKey"; - * let client = new KeyClient(vaultUrl, credentials); - * let key = await client.getKey(keyName); - * let result = await client.updateKeyProperties(keyName, { enabled: false }); - * ``` - * Updates the properties associated with a specified key in a given key vault. - * @param name - The name of the key. - * @param keyVersion - The version of the key. - * @param options - The optional parameters. - */ - public updateKeyProperties( - name: string, - options?: UpdateKeyPropertiesOptions, - ): Promise; - public updateKeyProperties( - ...args: [string, string, UpdateKeyPropertiesOptions?] | [string, UpdateKeyPropertiesOptions?] - ): Promise { - const [name, keyVersion, options] = this.disambiguateUpdateKeyPropertiesArgs(args); - return tracingClient.withSpan( - `KeyClient.updateKeyProperties`, - options, - async (updatedOptions) => { - const response = await this.client.updateKey( - name, - keyVersion, - { - keyAttributes: { - enabled: options?.enabled, - notBefore: options?.notBefore, - expires: options?.expiresOn, - }, - keyOps: options?.keyOps, - releasePolicy: options?.releasePolicy, - tags: options?.tags, - }, - updatedOptions, - ); - return getKeyFromKeyBundle(response); - }, - ); - } - - /** - * Standardizes an overloaded arguments collection for the updateKeyProperties method. - * - * @param args - The arguments collection. - * @returns - The standardized arguments collection. - */ - private disambiguateUpdateKeyPropertiesArgs( - args: [string, string, UpdateKeyPropertiesOptions?] | [string, UpdateKeyPropertiesOptions?], - ): [string, string, UpdateKeyPropertiesOptions] { - if (typeof args[1] === "string") { - // [name, keyVersion, options?] => [name, keyVersion, options || {}] - return [args[0], args[1], args[2] || {}]; - } else { - // [name, options?] => [name , "", options || {}] - return [args[0], "", args[1] || {}]; - } - } - - /** - * The getKey method gets a specified key and is applicable to any key stored in Azure Key Vault. - * This operation requires the keys/get permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * let key = await client.getKey("MyKey"); - * ``` - * Get a specified key from a given key vault. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public getKey(name: string, options: GetKeyOptions = {}): Promise { - return tracingClient.withSpan(`KeyClient.getKey`, options, async (updatedOptions) => { - const response = await this.client.getKey( - name, - options && options.version ? options.version : "", - updatedOptions, - ); - return getKeyFromKeyBundle(response); - }); - } - - /** - * The getDeletedKey method returns the specified deleted key along with its properties. - * This operation requires the keys/get permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * let key = await client.getDeletedKey("MyDeletedKey"); - * ``` - * Gets the specified deleted key. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public getDeletedKey(name: string, options: GetDeletedKeyOptions = {}): Promise { - return tracingClient.withSpan(`KeyClient.getDeletedKey`, options, async (updatedOptions) => { - const response = await this.client.getDeletedKey(name, updatedOptions); - return getKeyFromKeyBundle(response); - }); - } - - /** - * The purge deleted key operation removes the key permanently, without the possibility of - * recovery. This operation can only be enabled on a soft-delete enabled vault. This operation - * requires the keys/purge permission. - * - * Example usage: - * ```ts - * const client = new KeyClient(url, credentials); - * const deletePoller = await client.beginDeleteKey("MyKey") - * await deletePoller.pollUntilDone(); - * await client.purgeDeletedKey("MyKey"); - * ``` - * Permanently deletes the specified key. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public purgeDeletedKey(name: string, options: PurgeDeletedKeyOptions = {}): Promise { - return tracingClient.withSpan(`KeyClient.purgeDeletedKey`, options, async (updatedOptions) => { - await this.client.purgeDeletedKey(name, updatedOptions); - }); - } - - /** - * Recovers the deleted key in the specified vault. This operation can only be performed on a - * soft-delete enabled vault. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the deleted key is recovered. - * - * This operation requires the keys/recover permission. - * - * Example usage: - * ```ts - * const client = new KeyClient(url, credentials); - * await client.createKey("MyKey", "EC"); - * const deletePoller = await client.beginDeleteKey("MyKey"); - * await deletePoller.pollUntilDone(); - * const poller = await client.beginRecoverDeletedKey("MyKey"); - * - * // Serializing the poller - * const serialized = poller.toString(); - * // A new poller can be created with: - * // await client.beginRecoverDeletedKey("MyKey", { resumeFrom: serialized }); - * - * // Waiting until it's done - * const key = await poller.pollUntilDone(); - * console.log(key); - * ``` - * Recovers the deleted key to the latest version. - * @param name - The name of the deleted key. - * @param options - The optional parameters. - */ - public async beginRecoverDeletedKey( - name: string, - options: BeginRecoverDeletedKeyOptions = {}, - ): Promise, DeletedKey>> { - const poller = new RecoverDeletedKeyPoller({ - name, - client: this.client, - intervalInMs: options.intervalInMs, - resumeFrom: options.resumeFrom, - operationOptions: options, - }); - // This will initialize the poller's operation (the deletion of the key). - await poller.poll(); - return poller; - } - - /** - * Requests that a backup of the specified key be downloaded to the client. All versions of the - * key will be downloaded. This operation requires the keys/backup permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * let backupContents = await client.backupKey("MyKey"); - * ``` - * Backs up the specified key. - * @param name - The name of the key. - * @param options - The optional parameters. - */ - public backupKey(name: string, options: BackupKeyOptions = {}): Promise { - return tracingClient.withSpan(`KeyClient.backupKey`, options, async (updatedOptions) => { - const response = await this.client.backupKey(name, updatedOptions); - return response.value; - }); - } - - /** - * Restores a backed up key, and all its versions, to a vault. This operation requires the - * keys/restore permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * let backupContents = await client.backupKey("MyKey"); - * // ... - * let key = await client.restoreKeyBackup(backupContents); - * ``` - * Restores a backed up key to a vault. - * @param backup - The backup blob associated with a key bundle. - * @param options - The optional parameters. - */ - public async restoreKeyBackup( - backup: Uint8Array, - options: RestoreKeyBackupOptions = {}, - ): Promise { - return tracingClient.withSpan(`KeyClient.restoreKeyBackup`, options, async (updatedOptions) => { - const response = await this.client.restoreKey({ keyBundleBackup: backup }, updatedOptions); - return getKeyFromKeyBundle(response); - }); - } - - /** - * Gets the requested number of bytes containing random values from a managed HSM. - * This operation requires the managedHsm/rng permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(vaultUrl, credentials); - * let { bytes } = await client.getRandomBytes(10); - * ``` - * @param count - The number of bytes to generate between 1 and 128 inclusive. - * @param options - The optional parameters. - */ - public getRandomBytes(count: number, options: GetRandomBytesOptions = {}): Promise { - return tracingClient.withSpan("KeyClient.getRandomBytes", options, async (updatedOptions) => { - const response = await this.client.getRandomBytes({ count }, updatedOptions); - return response.value!; - }); - } - - /** - * Rotates the key based on the key policy by generating a new version of the key. This operation requires the keys/rotate permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(vaultUrl, credentials); - * let key = await client.rotateKey("MyKey"); - * ``` - * - * @param name - The name of the key to rotate. - * @param options - The optional parameters. - */ - public rotateKey(name: string, options: RotateKeyOptions = {}): Promise { - return tracingClient.withSpan("KeyClient.rotateKey", options, async (updatedOptions) => { - const key = await this.client.rotateKey(name, updatedOptions); - return getKeyFromKeyBundle(key); - }); - } - - /** - * Releases a key from a managed HSM. - * - * The release key operation is applicable to all key types. The operation requires the key to be marked exportable and the keys/release permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(vaultUrl, credentials); - * let result = await client.releaseKey("myKey", target) - * ``` - * - * @param name - The name of the key. - * @param targetAttestationToken - The attestation assertion for the target of the key release. - * @param options - The optional parameters. - */ - public releaseKey( - name: string, - targetAttestationToken: string, - options: ReleaseKeyOptions = {}, - ): Promise { - return tracingClient.withSpan("KeyClient.releaseKey", options, async (updatedOptions) => { - const { nonce, algorithm, ...rest } = updatedOptions; - const result = await this.client.release( - name, - options?.version || "", - { - targetAttestationToken, - enc: algorithm, - nonce, - }, - rest, - ); - - return { value: result.value! }; - }); - } - - /** - * Gets the rotation policy of a Key Vault Key. - * By default, all keys have a policy that will notify 30 days before expiry. - * - * This operation requires the keys/get permission. - * Example usage: - * ```ts - * let client = new KeyClient(vaultUrl, credentials); - * let result = await client.getKeyRotationPolicy("myKey"); - * ``` - * - * @param keyName - The name of the key. - * @param options - The optional parameters. - */ - public getKeyRotationPolicy( - keyName: string, - options: GetKeyRotationPolicyOptions = {}, - ): Promise { - return tracingClient.withSpan("KeyClient.getKeyRotationPolicy", options, async () => { - const policy = await this.client.getKeyRotationPolicy(keyName); - return keyRotationTransformations.generatedToPublic(policy); - }); - } - - /** - * Updates the rotation policy of a Key Vault Key. - * This operation requires the keys/update permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(vaultUrl, credentials); - * const setPolicy = await client.updateKeyRotationPolicy("MyKey", myPolicy); - * ``` - * - * @param keyName - The name of the key. - * @param policyProperties - The {@link KeyRotationPolicyProperties} for the policy. - * @param options - The optional parameters. - */ - public updateKeyRotationPolicy( - keyName: string, - policy: KeyRotationPolicyProperties, - options: UpdateKeyRotationPolicyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "KeyClient.updateKeyRotationPolicy", - options, - async (updatedOptions) => { - const result = await this.client.updateKeyRotationPolicy( - keyName, - keyRotationTransformations.propertiesToGenerated(policy), - updatedOptions, - ); - return keyRotationTransformations.generatedToPublic(result); - }, - ); - } - - /** - * Iterates all versions of the given key in the vault. The full key identifier, properties, and tags are provided - * in the response. This operation requires the keys/list permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * for await (const keyProperties of client.listPropertiesOfKeyVersions("MyKey")) { - * const key = await client.getKey(keyProperties.name); - * console.log("key version: ", key); - * } - * ``` - * @param name - Name of the key to fetch versions for - * @param options - The optional parameters. - */ - public listPropertiesOfKeyVersions( - name: string, - options: ListPropertiesOfKeyVersionsOptions = {}, - ): PagedAsyncIterableIterator { - return mapPagedAsyncIterable( - options, - (mappedOptions) => this.client.getKeyVersions(name, mappedOptions), - getKeyPropertiesFromKeyItem, - ); - } - - /** - * Iterates the latest version of all keys in the vault. The full key identifier and properties are provided - * in the response. No values are returned for the keys. This operations requires the keys/list permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * for await (const keyProperties of client.listPropertiesOfKeys()) { - * const key = await client.getKey(keyProperties.name); - * console.log("key: ", key); - * } - * ``` - * List all keys in the vault - * @param options - The optional parameters. - */ - public listPropertiesOfKeys( - options: ListPropertiesOfKeysOptions = {}, - ): PagedAsyncIterableIterator { - return mapPagedAsyncIterable( - options, - this.client.getKeys.bind(this.client), - getKeyPropertiesFromKeyItem, - ); - } - - /** - * Iterates the deleted keys in the vault. The full key identifier and properties are provided - * in the response. No values are returned for the keys. This operations requires the keys/list permission. - * - * Example usage: - * ```ts - * let client = new KeyClient(url, credentials); - * for await (const deletedKey of client.listDeletedKeys()) { - * console.log("deleted key: ", deletedKey); - * } - * ``` - * List all keys in the vault - * @param options - The optional parameters. - */ - public listDeletedKeys( - options: ListDeletedKeysOptions = {}, - ): PagedAsyncIterableIterator { - return mapPagedAsyncIterable( - options, - this.client.getDeletedKeys.bind(this.client), - getDeletedKeyFromDeletedKeyItem, - ); - } -} diff --git a/sdk/keyvault/keyvault-keys/src/keysModels.ts b/sdk/keyvault/keyvault-keys/src/keysModels.ts deleted file mode 100644 index 45101684375d..000000000000 --- a/sdk/keyvault/keyvault-keys/src/keysModels.ts +++ /dev/null @@ -1,733 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type * as coreClient from "@azure-rest/core-client"; -import type { ExtendedCommonClientOptions } from "@azure/core-http-compat"; - -import type { DeletionRecoveryLevel } from "./generated/models/index.js"; -import { - JsonWebKeyOperation as KeyOperation, - JsonWebKeyType as KeyType, -} from "./generated/models/index.js"; - -import type { KeyCurveName } from "./cryptographyClientModels.js"; - -export { KeyType, KeyOperation }; - -/** - * The latest supported Key Vault service API version - */ -export const LATEST_API_VERSION = "7.5"; - -/** - * The optional parameters accepted by the KeyVault's KeyClient - */ -export interface KeyClientOptions extends ExtendedCommonClientOptions { - /** - * The version of the KeyVault's service API to make calls against. - */ - serviceVersion?: string; - - /** - * Whether to disable verification that the authentication challenge resource matches the Key Vault or Managed HSM domain. - * Defaults to false. - */ - disableChallengeResourceVerification?: boolean; -} - -/** - * The optional parameters accepted by the KeyVault's CryptographyClient - */ -export interface CryptographyClientOptions extends KeyClientOptions {} - -/** - * As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18 - */ -export interface JsonWebKey { - /** - * Key identifier. - */ - kid?: string; - /** - * JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. Possible values include: - * 'EC', 'EC-HSM', 'RSA', 'RSA-HSM', 'oct', "oct-HSM" - */ - kty?: KeyType; - /** - * Json web key operations. For more - * information on possible key operations, see KeyOperation. - */ - keyOps?: KeyOperation[]; - /** - * RSA modulus. - */ - n?: Uint8Array; - /** - * RSA public exponent. - */ - e?: Uint8Array; - /** - * RSA private exponent, or the D component of an EC private key. - */ - d?: Uint8Array; - /** - * RSA private key parameter. - */ - dp?: Uint8Array; - /** - * RSA private key parameter. - */ - dq?: Uint8Array; - /** - * RSA private key parameter. - */ - qi?: Uint8Array; - /** - * RSA secret prime. - */ - p?: Uint8Array; - /** - * RSA secret prime, with `p < q`. - */ - q?: Uint8Array; - /** - * Symmetric key. - */ - k?: Uint8Array; - /** - * HSM Token, used with 'Bring Your Own Key'. - */ - t?: Uint8Array; - /** - * Elliptic curve name. For valid values, see KeyCurveName. Possible values include: - * 'P-256', 'P-384', 'P-521', 'P-256K' - */ - crv?: KeyCurveName; - /** - * X component of an EC public key. - */ - x?: Uint8Array; - /** - * Y component of an EC public key. - */ - y?: Uint8Array; -} - -/** - * An interface representing a Key Vault Key, with its name, value and {@link KeyProperties}. - */ -export interface KeyVaultKey { - /** - * The key value. - */ - key?: JsonWebKey; - /** - * The name of the key. - */ - name: string; - /** - * Key identifier. - */ - id?: string; - /** - * JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. Possible values include: - * 'EC', 'EC-HSM', 'RSA', 'RSA-HSM', 'oct', "oct-HSM" - */ - keyType?: KeyType; - /** - * Operations allowed on this key - */ - keyOperations?: KeyOperation[]; - /** - * The properties of the key. - */ - properties: KeyProperties; -} - -/** - * An interface representing the Properties of {@link KeyVaultKey} - */ -export interface KeyProperties { - /** - * Key identifier. - */ - id?: string; - /** - * The name of the key. - */ - name: string; - /** - * The vault URI. - */ - vaultUrl: string; - /** - * The version of the key. May be undefined. - */ - version?: string; - /** - * Determines whether the object is enabled. - */ - enabled?: boolean; - /** - * Not before date in UTC. - */ - notBefore?: Date; - /** - * Expiry date in UTC. - */ - expiresOn?: Date; - /** - * Application specific metadata in the form of key-value pairs. - */ - tags?: { [propertyName: string]: string }; - /** - * Creation time in UTC. - * **NOTE: This property will not be serialized. It can only be populated by - * the server.** - */ - readonly createdOn?: Date; - /** - * Last updated time in UTC. - * **NOTE: This property will not be serialized. It can only be populated by - * the server.** - */ - readonly updatedOn?: Date; - /** - * Reflects the deletion recovery level currently in effect for keys in the current vault. - * If it contains 'Purgeable' the key can be permanently deleted by a privileged - * user; otherwise, only the system can purge the key, at the end of the - * retention interval. Possible values include: 'Purgeable', - * 'Recoverable+Purgeable', 'Recoverable', - * 'Recoverable+ProtectedSubscription' - * **NOTE: This property will not be serialized. It can only be populated by - * the server.** - */ - readonly recoveryLevel?: DeletionRecoveryLevel; - /** - * The retention dates of the softDelete data. - * The value should be `>=7` and `<=90` when softDelete enabled. - * **NOTE: This property will not be serialized. It can only be populated by the server.** - */ - recoverableDays?: number; - - /** - * True if the secret's lifetime is managed by - * key vault. If this is a secret backing a certificate, then managed will be - * true. - * **NOTE: This property will not be serialized. It can only be populated by - * the server.** - */ - readonly managed?: boolean; - - /** - * Indicates whether the private key can be exported. - */ - exportable?: boolean; - - /** - * A {@link KeyReleasePolicy} object specifying the rules under which the key can be exported. - */ - releasePolicy?: KeyReleasePolicy; - - /** - * The underlying HSM Platform. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly hsmPlatform?: string; -} - -/** - * An interface representing a deleted Key Vault Key. - */ -export interface DeletedKey { - /** - * The key value. - */ - key?: JsonWebKey; - /** - * The name of the key. - */ - name: string; - /** - * Key identifier. - */ - id?: string; - /** - * JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. Possible values include: - * 'EC', 'EC-HSM', 'RSA', 'RSA-HSM', 'oct', "oct-HSM" - */ - keyType?: KeyType; - /** - * Operations allowed on this key - */ - keyOperations?: KeyOperation[]; - /** - * The properties of the key. - */ - properties: KeyProperties & { - /** - * The url of the recovery object, used to - * identify and recover the deleted key. - */ - readonly recoveryId?: string; - /** - * The time when the key is scheduled to be purged, in UTC - * **NOTE: This property will not be serialized. It can only be populated by - * the server.** - */ - readonly scheduledPurgeDate?: Date; - /** - * The time when the key was deleted, in UTC - * **NOTE: This property will not be serialized. It can only be populated by - * the server.** - */ - deletedOn?: Date; - }; -} - -/** - * The policy rules under which a key can be exported. - */ -export interface KeyReleasePolicy { - /** - * Content type and version of key release policy. - * - * Defaults to "application/json; charset=utf-8" if omitted. - */ - contentType?: string; - - /** - * The policy rules under which the key can be released. Encoded based on the {@link KeyReleasePolicy.contentType}. - * - * For more information regarding the release policy grammar for Azure Key Vault, please refer to: - * - https://aka.ms/policygrammarkeys for Azure Key Vault release policy grammar. - * - https://aka.ms/policygrammarmhsm for Azure Managed HSM release policy grammar. - */ - encodedPolicy?: Uint8Array; - - /** Marks a release policy as immutable. An immutable release policy cannot be changed or updated after being marked immutable. */ - immutable?: boolean; -} - -/** - * An interface representing the optional parameters that can be - * passed to {@link createKey} - */ -export interface CreateKeyOptions extends coreClient.OperationOptions { - /** - * Application specific metadata in the form of key-value pairs. - */ - tags?: { [propertyName: string]: string }; - /** - * Json web key operations. For more - * information on possible key operations, see KeyOperation. - */ - keyOps?: KeyOperation[]; - /** - * Determines whether the object is enabled. - */ - enabled?: boolean; - /** - * Not before date in UTC. - */ - notBefore?: Date; - /** - * Expiry date in UTC. - */ - readonly expiresOn?: Date; - /** - * The key size in bits. For example: 2048, 3072, or 4096 for RSA. - */ - keySize?: number; - /** - * Elliptic curve name. For valid values, see KeyCurveName. - * Possible values include: 'P-256', 'P-384', 'P-521', 'P-256K' - */ - curve?: KeyCurveName; - /** - * Whether to import as a hardware key (HSM) or software key. - */ - hsm?: boolean; - - /** - * Indicates whether the private key can be exported. - */ - exportable?: boolean; - - /** - * A {@link KeyReleasePolicy} object specifying the rules under which the key can be exported. - */ - releasePolicy?: KeyReleasePolicy; -} - -/** - * An interface representing the optional parameters that can be - * passed to {@link beginDeleteKey} and {@link beginRecoverDeletedKey} - */ -export interface KeyPollerOptions extends coreClient.OperationOptions { - /** - * Time between each polling - */ - intervalInMs?: number; - /** - * A serialized poller, used to resume an existing operation - */ - resumeFrom?: string; -} - -/** - * An interface representing the optional parameters that can be - * passed to {@link beginDeleteKey} - */ -export interface BeginDeleteKeyOptions extends KeyPollerOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link beginRecoverDeletedKey} - */ -export interface BeginRecoverDeletedKeyOptions extends KeyPollerOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link createEcKey} - */ -export interface CreateEcKeyOptions extends CreateKeyOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link createRsaKey} - */ -export interface CreateRsaKeyOptions extends CreateKeyOptions { - /** The public exponent for a RSA key. */ - publicExponent?: number; -} - -/** - * An interface representing the optional parameters that can be - * passed to {@link createOctKey} - */ -export interface CreateOctKeyOptions extends CreateKeyOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link importKey} - */ -export interface ImportKeyOptions extends coreClient.OperationOptions { - /** - * Application specific metadata in the form of key-value pairs. - */ - tags?: { [propertyName: string]: string }; - /** - * Whether to import as a hardware key (HSM) or software key. - */ - hardwareProtected?: boolean; - /** - * Determines whether the object is enabled. - */ - enabled?: boolean; - /** - * Not before date in UTC. - */ - notBefore?: Date; - /** - * Expiry date in UTC. - */ - expiresOn?: Date; - - /** - * Indicates whether the private key can be exported. - */ - exportable?: boolean; - - /** - * A {@link KeyReleasePolicy} object specifying the rules under which the key can be exported. - */ - releasePolicy?: KeyReleasePolicy; -} - -/** - * Options for {@link updateKeyProperties}. - */ -export interface UpdateKeyPropertiesOptions extends coreClient.OperationOptions { - /** - * Json web key operations. For more - * information on possible key operations, see KeyOperation. - */ - keyOps?: KeyOperation[]; - /** - * Determines whether the object is enabled. - */ - enabled?: boolean; - /** - * Not before date in UTC. - */ - notBefore?: Date; - /** - * Expiry date in UTC. - */ - expiresOn?: Date; - /** - * Application specific metadata in the form of key-value pairs. - */ - tags?: { [propertyName: string]: string }; - - /** - * A {@link KeyReleasePolicy} object specifying the rules under which the key can be exported. - * Only valid if the key is marked exportable, which cannot be changed after key creation. - */ - releasePolicy?: KeyReleasePolicy; -} - -/** - * Options for {@link getKey}. - */ -export interface GetKeyOptions extends coreClient.OperationOptions { - /** - * The version of the secret to retrieve. If not - * specified the latest version of the secret will be retrieved. - */ - version?: string; -} - -/** - * An interface representing optional parameters for KeyClient paged operations passed to {@link listKeys}. - */ -export interface ListKeysOptions extends coreClient.OperationOptions {} - -/** - * An interface representing optional parameters for KeyClient paged operations passed to {@link listPropertiesOfKeys}. - */ -export interface ListPropertiesOfKeysOptions extends coreClient.OperationOptions {} - -/** - * An interface representing optional parameters for KeyClient paged operations passed to {@link listPropertiesOfKeyVersions}. - */ -export interface ListPropertiesOfKeyVersionsOptions extends coreClient.OperationOptions {} - -/** - * An interface representing optional parameters for KeyClient paged operations passed to {@link listDeletedKeys}. - */ -export interface ListDeletedKeysOptions extends coreClient.OperationOptions {} - -/** - * Options for {@link getDeletedKey}. - */ -export interface GetDeletedKeyOptions extends coreClient.OperationOptions {} - -/** - * Options for {@link purgeDeletedKey}. - */ -export interface PurgeDeletedKeyOptions extends coreClient.OperationOptions {} - -/** - * @internal - * Options for {@link recoverDeletedKey}. - */ -export interface RecoverDeletedKeyOptions extends coreClient.OperationOptions {} - -/** - * @internal - * Options for {@link deleteKey}. - */ -export interface DeleteKeyOptions extends coreClient.OperationOptions {} - -/** - * Options for {@link backupKey}. - */ -export interface BackupKeyOptions extends coreClient.OperationOptions {} - -/** - * Options for {@link restoreKeyBackup}. - */ -export interface RestoreKeyBackupOptions extends coreClient.OperationOptions {} - -/** - * An interface representing the options of the cryptography API methods, go to the {@link CryptographyClient} for more information. - */ -export interface CryptographyOptions extends coreClient.OperationOptions {} - -/** - * Options for {@link KeyClient.getRandomBytes} - */ -export interface GetRandomBytesOptions extends coreClient.OperationOptions {} - -/** - * Options for {@link KeyClient.releaseKey} - */ -export interface ReleaseKeyOptions extends coreClient.OperationOptions { - /** A client provided nonce for freshness. */ - nonce?: string; - - /** The {@link KeyExportEncryptionAlgorithm} to for protecting the exported key material. */ - algorithm?: KeyExportEncryptionAlgorithm; - - /** - * The version of the key to release. Defaults to the latest version of the key if omitted. - */ - version?: string; -} - -/** - * Result of the {@link KeyClient.releaseKey} operation. - */ -export interface ReleaseKeyResult { - /** A signed token containing the released key. */ - value: string; -} - -/** Known values of {@link KeyOperation} that the service accepts. */ -export enum KnownKeyOperations { - /** Key operation - encrypt */ - Encrypt = "encrypt", - /** Key operation - decrypt */ - Decrypt = "decrypt", - /** Key operation - sign */ - Sign = "sign", - /** Key operation - verify */ - Verify = "verify", - /** Key operation - wrapKey */ - WrapKey = "wrapKey", - /** Key operation - unwrapKey */ - UnwrapKey = "unwrapKey", - /** Key operation - import */ - Import = "import", -} - -/** Known values of {@link KeyExportEncryptionAlgorithm} that the service accepts. */ -export enum KnownKeyExportEncryptionAlgorithm { - /** CKM_RSA_AES_KEY_WRAP Key Export Encryption Algorithm */ - CkmRsaAesKeyWrap = "CKM_RSA_AES_KEY_WRAP", - /** RSA_AES_KEY_WRAP_256 Key Export Encryption Algorithm */ - RsaAesKeyWrap256 = "RSA_AES_KEY_WRAP_256", - /** RSA_AES_KEY_WRAP_384 Key Export Encryption Algorithm */ - RsaAesKeyWrap384 = "RSA_AES_KEY_WRAP_384", -} - -/** - * JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - */ -export enum KnownKeyTypes { - /** Elliptic Curve. */ - EC = "EC", - /** Elliptic Curve with a private key which is stored in the HSM. */ - ECHSM = "EC-HSM", - /** RSA (https://tools.ietf.org/html/rfc3447) */ - RSA = "RSA", - /** RSA with a private key which is stored in the HSM. */ - RSAHSM = "RSA-HSM", - /** Octet sequence (used to represent symmetric keys) */ - Oct = "oct", - /** Octet sequence (used to represent symmetric keys) which is stored the HSM. */ - OctHSM = "oct-HSM", -} - -/* eslint-disable tsdoc/syntax */ -/** - * Defines values for KeyEncryptionAlgorithm. - * {@link KnownKeyExportEncryptionAlgorithm} can be used interchangeably with KeyEncryptionAlgorithm, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **CKM_RSA_AES_KEY_WRAP** \ - * **RSA_AES_KEY_WRAP_256** \ - * **RSA_AES_KEY_WRAP_384** - */ -export type KeyExportEncryptionAlgorithm = string; -/* eslint-enable tsdoc/syntax */ - -/** - * Options for {@link KeyClient.getCryptographyClient}. - */ -export interface GetCryptographyClientOptions { - /** - * The version of the key to use for cryptographic operations. - * - * When undefined, the latest version of the key will be used. - */ - keyVersion?: string; -} - -/** - * Options for {@link KeyClient.rotateKey} - */ -export interface RotateKeyOptions extends coreClient.OperationOptions {} - -/** - * The properties of a key rotation policy that the client can set for a given key. - * - * You may also reset the key rotation policy to its default values by setting lifetimeActions to an empty array. - */ -export interface KeyRotationPolicyProperties { - /** - * Optional key expiration period used to define the duration after which a newly rotated key will expire, defined as an ISO 8601 duration. - */ - expiresIn?: string; - - /** - * Actions that will be performed by Key Vault over the lifetime of a key. - * - * You may also pass an empty array to restore to its default values. - */ - lifetimeActions?: KeyRotationLifetimeAction[]; -} - -/** - * The complete key rotation policy that belongs to a key. - */ -export interface KeyRotationPolicy extends KeyRotationPolicyProperties { - /** - * The identifier of the Key Rotation Policy. - * May be undefined if a policy has not been explicitly set. - */ - readonly id?: string; - - /** - * The created time in UTC. - * May be undefined if a policy has not been explicitly set. - */ - readonly createdOn?: Date; - - /** - * The last updated time in UTC. - * May be undefined if a policy has not been explicitly set. - */ - readonly updatedOn?: Date; -} - -/** - * An action and its corresponding trigger that will be performed by Key Vault over the lifetime of a key. - */ -export interface KeyRotationLifetimeAction { - /** - * Time after creation to attempt the specified action, defined as an ISO 8601 duration. - */ - timeAfterCreate?: string; - - /** - * Time before expiry to attempt the specified action, defined as an ISO 8601 duration. - */ - timeBeforeExpiry?: string; - - /** - * The action that will be executed. - */ - action: KeyRotationPolicyAction; -} - -/** - * The action that will be executed. - */ -export type KeyRotationPolicyAction = "Rotate" | "Notify"; - -/** - * Options for {@link KeyClient.updateKeyRotationPolicy} - */ -export interface UpdateKeyRotationPolicyOptions extends coreClient.OperationOptions {} - -/** - * Options for {@link KeyClient.getRotationPolicy} - */ -export interface GetKeyRotationPolicyOptions extends coreClient.OperationOptions {} diff --git a/sdk/keyvault/keyvault-keys/src/log.ts b/sdk/keyvault/keyvault-keys/src/log.ts deleted file mode 100644 index 85b78ecc5382..000000000000 --- a/sdk/keyvault/keyvault-keys/src/log.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { createClientLogger } from "@azure/logger"; - -/** - * The \@azure/logger configuration for this package. - */ -export const logger = createClientLogger("keyvault-keys"); diff --git a/sdk/keyvault/keyvault-keys/src/lro/delete/operation.ts b/sdk/keyvault/keyvault-keys/src/lro/delete/operation.ts deleted file mode 100644 index b6e9d5287072..000000000000 --- a/sdk/keyvault/keyvault-keys/src/lro/delete/operation.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { AbortSignalLike } from "@azure/abort-controller"; -import type { OperationOptions } from "@azure-rest/core-client"; -import type { KeyVaultClient } from "../../generated/keyVaultClient.js"; -import type { DeleteKeyOptions, DeletedKey, GetDeletedKeyOptions } from "../../keysModels.js"; -import { tracingClient } from "../../tracing.js"; -import { getKeyFromKeyBundle } from "../../transformations.js"; -import type { KeyVaultKeyPollOperationState } from "../keyVaultKeyPoller.js"; -import { KeyVaultKeyPollOperation } from "../keyVaultKeyPoller.js"; - -/** - * An interface representing the state of a delete key's poll operation - */ -export interface DeleteKeyPollOperationState extends KeyVaultKeyPollOperationState {} - -export class DeleteKeyPollOperation extends KeyVaultKeyPollOperation< - DeleteKeyPollOperationState, - DeletedKey -> { - constructor( - public state: DeleteKeyPollOperationState, - private client: KeyVaultClient, - private operationOptions: OperationOptions = {}, - ) { - super(state, { cancelMessage: "Canceling the deletion of a key is not supported." }); - } - - /** - * Sends a delete request for the given Key Vault Key's name to the Key Vault service. - * Since the Key Vault Key won't be immediately deleted, we have {@link beginDeleteKey}. - */ - private deleteKey(name: string, options: DeleteKeyOptions = {}): Promise { - return tracingClient.withSpan("DeleteKeyPoller.deleteKey", options, async (updatedOptions) => { - const response = await this.client.deleteKey(name, updatedOptions); - return getKeyFromKeyBundle(response); - }); - } - - /** - * The getDeletedKey method returns the specified deleted key along with its properties. - * This operation requires the keys/get permission. - */ - private getDeletedKey(name: string, options: GetDeletedKeyOptions = {}): Promise { - return tracingClient.withSpan( - "DeleteKeyPoller.getDeletedKey", - options, - async (updatedOptions) => { - const response = await this.client.getDeletedKey(name, updatedOptions); - return getKeyFromKeyBundle(response); - }, - ); - } - - /** - * Reaches to the service and updates the delete key's poll operation. - */ - public async update( - options: { - abortSignal?: AbortSignalLike; - fireProgress?: (state: DeleteKeyPollOperationState) => void; - } = {}, - ): Promise { - const state = this.state; - const { name } = state; - - if (options.abortSignal) { - this.operationOptions.abortSignal = options.abortSignal; - } - - if (!state.isStarted) { - const deletedKey = await this.deleteKey(name, this.operationOptions); - state.isStarted = true; - state.result = deletedKey; - if (!deletedKey.properties.recoveryId) { - state.isCompleted = true; - } - } - - if (!state.isCompleted) { - try { - state.result = await this.getDeletedKey(name, this.operationOptions); - state.isCompleted = true; - } catch (error: any) { - if (error.statusCode === 403) { - // At this point, the resource exists but the user doesn't have access to it. - state.isCompleted = true; - } else if (error.statusCode !== 404) { - state.error = error; - state.isCompleted = true; - throw error; - } - } - } - - return this; - } -} diff --git a/sdk/keyvault/keyvault-keys/src/lro/delete/poller.ts b/sdk/keyvault/keyvault-keys/src/lro/delete/poller.ts deleted file mode 100644 index 9c07d92cf516..000000000000 --- a/sdk/keyvault/keyvault-keys/src/lro/delete/poller.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { DeleteKeyPollOperationState } from "./operation.js"; -import { DeleteKeyPollOperation } from "./operation.js"; -import type { DeletedKey } from "../../keysModels.js"; -import type { KeyVaultKeyPollerOptions } from "../keyVaultKeyPoller.js"; -import { KeyVaultKeyPoller } from "../keyVaultKeyPoller.js"; - -/** - * Class that creates a poller that waits until a key finishes being deleted. - */ -export class DeleteKeyPoller extends KeyVaultKeyPoller { - constructor(options: KeyVaultKeyPollerOptions) { - const { client, name, operationOptions, intervalInMs = 2000, resumeFrom } = options; - - let state: DeleteKeyPollOperationState | undefined; - - if (resumeFrom) { - state = JSON.parse(resumeFrom).state; - } - - const operation = new DeleteKeyPollOperation( - { - ...state, - name, - }, - client, - operationOptions, - ); - - super(operation); - - this.intervalInMs = intervalInMs; - } -} diff --git a/sdk/keyvault/keyvault-keys/src/lro/keyVaultKeyPoller.ts b/sdk/keyvault/keyvault-keys/src/lro/keyVaultKeyPoller.ts deleted file mode 100644 index 3ce34d31e1fe..000000000000 --- a/sdk/keyvault/keyvault-keys/src/lro/keyVaultKeyPoller.ts +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { OperationOptions } from "@azure-rest/core-client"; -import { delay } from "@azure/core-util"; -import type { PollOperation, PollOperationState } from "@azure/core-lro"; -import { Poller } from "@azure/core-lro"; -import type { KeyVaultClient } from "../generated/keyVaultClient.js"; - -/** - * Common parameters to a Key Vault Key Poller. - */ -export interface KeyVaultKeyPollerOptions { - client: KeyVaultClient; - name: string; - operationOptions?: OperationOptions; - intervalInMs?: number; - resumeFrom?: string; -} - -/** - * An interface representing the state of a Key Vault Key Poller's operation. - */ -export interface KeyVaultKeyPollOperationState extends PollOperationState { - /** - * The name of the key. - */ - name: string; -} - -/** - * Common properties and methods of the Key Vault Key Pollers. - */ -export abstract class KeyVaultKeyPoller< - TState extends KeyVaultKeyPollOperationState, - TResult, -> extends Poller { - /** - * Defines how much time the poller is going to wait before making a new request to the service. - */ - public intervalInMs: number = 2000; - - /** - * The method used by the poller to wait before attempting to update its operation. - */ - async delay(): Promise { - return delay(this.intervalInMs); - } -} - -/** - * Optional parameters to the KeyVaultKeyPollOperation - */ -export interface KeyVaultKeyPollOperationOptions { - cancelMessage?: string; -} - -/** - * Common properties and methods of the Key Vault Key Poller operations. - */ -export class KeyVaultKeyPollOperation implements PollOperation { - private cancelMessage: string = ""; - - constructor( - public state: TState, - options: KeyVaultKeyPollOperationOptions = {}, - ) { - if (options.cancelMessage) { - this.cancelMessage = options.cancelMessage; - } - } - - /** - * Meant to reach to the service and update the Poller operation. - */ - public async update(): Promise> { - throw new Error("Operation not supported."); - } - - /** - * Meant to reach to the service and cancel the Poller operation. - */ - public async cancel(): Promise> { - throw new Error(this.cancelMessage); - } - - /** - * Serializes the Poller operation. - */ - public toString(): string { - return JSON.stringify({ - state: this.state, - }); - } -} diff --git a/sdk/keyvault/keyvault-keys/src/lro/recover/operation.ts b/sdk/keyvault/keyvault-keys/src/lro/recover/operation.ts deleted file mode 100644 index f44efbd4757e..000000000000 --- a/sdk/keyvault/keyvault-keys/src/lro/recover/operation.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { AbortSignalLike } from "@azure/abort-controller"; -import type { OperationOptions } from "@azure-rest/core-client"; -import type { KeyVaultClient } from "../../generated/keyVaultClient.js"; -import type { GetKeyOptions, KeyVaultKey, RecoverDeletedKeyOptions } from "../../keysModels.js"; -import { tracingClient } from "../../tracing.js"; -import { getKeyFromKeyBundle } from "../../transformations.js"; -import type { KeyVaultKeyPollOperationState } from "../keyVaultKeyPoller.js"; -import { KeyVaultKeyPollOperation } from "../keyVaultKeyPoller.js"; - -/** - * An interface representing the state of a delete key's poll operation - */ -export interface RecoverDeletedKeyPollOperationState - extends KeyVaultKeyPollOperationState {} - -export class RecoverDeletedKeyPollOperation extends KeyVaultKeyPollOperation< - RecoverDeletedKeyPollOperationState, - KeyVaultKey -> { - constructor( - public state: RecoverDeletedKeyPollOperationState, - private client: KeyVaultClient, - private operationOptions: OperationOptions = {}, - ) { - super(state, { cancelMessage: "Canceling the recovery of a deleted key is not supported." }); - } - - /** - * The getKey method gets a specified key and is applicable to any key stored in Azure Key Vault. - * This operation requires the keys/get permission. - */ - private getKey(name: string, options: GetKeyOptions = {}): Promise { - return tracingClient.withSpan( - "RecoverDeleteKeyPoller.getKey", - options, - async (updatedOptions) => { - const response = await this.client.getKey( - name, - updatedOptions?.version || "", - updatedOptions, - ); - return getKeyFromKeyBundle(response); - }, - ); - } - - /** - * Sends a request to recover a deleted Key Vault Key based on the given name. - * Since the Key Vault Key won't be immediately recover the deleted key, we have {@link beginRecoverDeletedKey}. - */ - private async recoverDeletedKey( - name: string, - options: RecoverDeletedKeyOptions = {}, - ): Promise { - return tracingClient.withSpan( - "RecoverDeletedKeyPoller.recoverDeleteKey", - options, - async (updatedOptions) => { - const response = await this.client.recoverDeletedKey(name, updatedOptions); - return getKeyFromKeyBundle(response); - }, - ); - } - - /** - * Reaches to the service and updates the delete key's poll operation. - */ - public async update( - options: { - abortSignal?: AbortSignalLike; - fireProgress?: (state: RecoverDeletedKeyPollOperationState) => void; - } = {}, - ): Promise { - const state = this.state; - const { name } = state; - - const operationOptions = this.operationOptions; - if (options.abortSignal) { - operationOptions.abortSignal = options.abortSignal; - } - - if (!state.isStarted) { - try { - state.result = await this.getKey(name, operationOptions); - state.isCompleted = true; - } catch { - // Nothing to do here. - } - if (!state.isCompleted) { - state.result = await this.recoverDeletedKey(name, operationOptions); - state.isStarted = true; - } - } - - if (!state.isCompleted) { - try { - state.result = await this.getKey(name, operationOptions); - state.isCompleted = true; - } catch (error: any) { - if (error.statusCode === 403) { - // At this point, the resource exists but the user doesn't have access to it. - state.isCompleted = true; - } else if (error.statusCode !== 404) { - state.error = error; - state.isCompleted = true; - throw error; - } - } - } - - return this; - } -} diff --git a/sdk/keyvault/keyvault-keys/src/lro/recover/poller.ts b/sdk/keyvault/keyvault-keys/src/lro/recover/poller.ts deleted file mode 100644 index abf0121d575d..000000000000 --- a/sdk/keyvault/keyvault-keys/src/lro/recover/poller.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { RecoverDeletedKeyPollOperationState } from "./operation.js"; -import { RecoverDeletedKeyPollOperation } from "./operation.js"; -import type { KeyVaultKey } from "../../keysModels.js"; -import type { KeyVaultKeyPollerOptions } from "../keyVaultKeyPoller.js"; -import { KeyVaultKeyPoller } from "../keyVaultKeyPoller.js"; - -/** - * Class that deletes a poller that waits until a key finishes being deleted - */ -export class RecoverDeletedKeyPoller extends KeyVaultKeyPoller< - RecoverDeletedKeyPollOperationState, - KeyVaultKey -> { - constructor(options: KeyVaultKeyPollerOptions) { - const { client, name, operationOptions, intervalInMs = 2000, resumeFrom } = options; - - let state: RecoverDeletedKeyPollOperationState | undefined; - - if (resumeFrom) { - state = JSON.parse(resumeFrom).state; - } - - const operation = new RecoverDeletedKeyPollOperation( - { - ...state, - name, - }, - client, - operationOptions, - ); - - super(operation); - - this.intervalInMs = intervalInMs; - } -} diff --git a/sdk/keyvault/keyvault-keys/src/tracing.ts b/sdk/keyvault/keyvault-keys/src/tracing.ts deleted file mode 100644 index 6f1ba6f74983..000000000000 --- a/sdk/keyvault/keyvault-keys/src/tracing.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { createTracingClient } from "@azure/core-tracing"; -import { SDK_VERSION } from "./constants.js"; - -export const tracingClient = createTracingClient({ - namespace: "Microsoft.KeyVault", - packageName: "@azure/keyvault-keys", - packageVersion: SDK_VERSION, -}); diff --git a/sdk/keyvault/keyvault-keys/src/transformations.ts b/sdk/keyvault/keyvault-keys/src/transformations.ts deleted file mode 100644 index facd0ac3276a..000000000000 --- a/sdk/keyvault/keyvault-keys/src/transformations.ts +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - DeletedKeyBundle, - DeletedKeyItem, - KeyRotationPolicy as GeneratedPolicy, - KeyAttributes, - KeyBundle, - KeyItem, - LifetimeActions, -} from "./generated/models/index.js"; -import { parseKeyVaultKeyIdentifier } from "./identifier.js"; -import type { - DeletedKey, - KeyProperties, - KeyRotationPolicy, - KeyRotationPolicyAction, - KeyRotationPolicyProperties, - KeyVaultKey, -} from "./keysModels.js"; -import type { PagedAsyncIterableIterator, PageSettings } from "./generated/index.js"; -import type { OperationOptions } from "@azure-rest/core-client"; - -/** - * @internal - * Shapes the exposed {@link KeyVaultKey} based on either a received key bundle or deleted key bundle. - */ -export function getKeyFromKeyBundle( - bundle: KeyBundle | DeletedKeyBundle, -): KeyVaultKey | DeletedKey { - const keyBundle = bundle as KeyBundle; - const deletedKeyBundle = bundle as DeletedKeyBundle; - - const parsedId = parseKeyVaultKeyIdentifier(keyBundle.key!.kid!); - - const attributes: KeyAttributes = keyBundle.attributes || {}; - delete keyBundle.attributes; - - const resultObject: KeyVaultKey | DeletedKey = { - key: keyBundle.key, - id: keyBundle.key ? keyBundle.key.kid : undefined, - name: parsedId.name, - keyOperations: keyBundle.key ? keyBundle.key.keyOps : undefined, - keyType: keyBundle.key ? keyBundle.key.kty : undefined, - properties: { - tags: keyBundle.tags, - - enabled: attributes.enabled, - notBefore: attributes.notBefore, - expiresOn: attributes.expires, - createdOn: attributes.created, - updatedOn: attributes.updated, - recoverableDays: attributes.recoverableDays, - recoveryLevel: attributes.recoveryLevel, - exportable: attributes.exportable, - releasePolicy: keyBundle.releasePolicy, - hsmPlatform: attributes.hsmPlatform, - - vaultUrl: parsedId.vaultUrl, - version: parsedId.version, - name: parsedId.name, - managed: keyBundle.managed, - - id: keyBundle.key ? keyBundle.key.kid : undefined, - }, - }; - - if (deletedKeyBundle.recoveryId) { - (resultObject as any).properties.recoveryId = deletedKeyBundle.recoveryId; - (resultObject as any).properties.scheduledPurgeDate = deletedKeyBundle.scheduledPurgeDate; - (resultObject as any).properties.deletedOn = deletedKeyBundle.deletedDate; - } - - return resultObject; -} - -/** - * @internal - * Shapes the exposed {@link DeletedKey} based on a received KeyItem. - */ -export function getDeletedKeyFromDeletedKeyItem(keyItem: DeletedKeyItem): DeletedKey { - const commonProperties = getKeyPropertiesFromKeyItem(keyItem); - - return { - key: { - kid: keyItem.kid, - }, - id: keyItem.kid, - name: commonProperties.name, - properties: { - ...commonProperties, - recoveryId: keyItem.recoveryId, - scheduledPurgeDate: keyItem.scheduledPurgeDate, - deletedOn: keyItem.deletedDate, - }, - }; -} - -/** - * @internal - * Shapes the exposed {@link KeyProperties} based on a received KeyItem. - */ -export function getKeyPropertiesFromKeyItem(keyItem: KeyItem): KeyProperties { - const parsedId = parseKeyVaultKeyIdentifier(keyItem.kid!); - const attributes = keyItem.attributes || {}; - - const resultObject: KeyProperties = { - createdOn: attributes.created, - enabled: attributes?.enabled, - expiresOn: attributes?.expires, - id: keyItem.kid, - managed: keyItem.managed, - name: parsedId.name, - notBefore: attributes?.notBefore, - recoverableDays: attributes?.recoverableDays, - recoveryLevel: attributes?.recoveryLevel, - hsmPlatform: attributes?.hsmPlatform, - tags: keyItem.tags, - updatedOn: attributes.updated, - vaultUrl: parsedId.vaultUrl, - version: parsedId.version, - }; - - return resultObject; -} - -const actionTypeCaseInsensitiveMapping: Record = { - rotate: "Rotate", - notify: "Notify", -}; - -function getNormalizedActionType(caseInsensitiveActionType: string): KeyRotationPolicyAction { - const result = actionTypeCaseInsensitiveMapping[caseInsensitiveActionType.toLowerCase()]; - if (result) { - return result; - } - - throw new Error(`Unrecognized action type: ${caseInsensitiveActionType}`); -} - -/** - * @internal - */ -export const keyRotationTransformations = { - propertiesToGenerated: function ( - parameters: KeyRotationPolicyProperties, - ): Partial { - const policy: GeneratedPolicy = { - attributes: { - expiryTime: parameters.expiresIn, - }, - lifetimeActions: parameters.lifetimeActions?.map((action) => { - const generatedAction: LifetimeActions = { - action: { type: action.action }, - trigger: {}, - }; - - if (action.timeAfterCreate) { - generatedAction.trigger!.timeAfterCreate = action.timeAfterCreate; - } - - if (action.timeBeforeExpiry) { - generatedAction.trigger!.timeBeforeExpiry = action.timeBeforeExpiry; - } - - return generatedAction; - }), - }; - return policy; - }, - generatedToPublic(generated: GeneratedPolicy): KeyRotationPolicy { - const policy: KeyRotationPolicy = { - id: generated.id, - createdOn: generated.attributes?.created, - updatedOn: generated.attributes?.updated, - expiresIn: generated.attributes?.expiryTime, - lifetimeActions: generated.lifetimeActions?.map((action) => { - return { - action: getNormalizedActionType(action.action!.type!), - timeAfterCreate: action.trigger?.timeAfterCreate, - timeBeforeExpiry: action.trigger?.timeBeforeExpiry, - }; - }), - }; - return policy; - }, -}; - -/** - * A helper supporting compatibility between modular and legacy paged async iterables. - * - * Provides the following compatibility: - * 1. Maps the values of the paged async iterable using the provided mapper function. - * 2. Supports `maxPageSize` operation on the paged async iterable. - * - * TODO: move this to keyvault-common once everything is merged - */ -export function mapPagedAsyncIterable< - TGenerated, - TPublic, - TOptions extends OperationOptions & { maxresults?: number }, ->( - options: TOptions, - operation: (options: TOptions) => PagedAsyncIterableIterator, - mapper: (x: TGenerated) => TPublic, -): PagedAsyncIterableIterator { - let iter: ReturnType | undefined = undefined; - return { - async next() { - iter ??= operation({ ...options, maxresults: undefined }); - const result = await iter.next(); - - return { - ...result, - value: result.value && mapper(result.value), - }; - }, - [Symbol.asyncIterator]() { - return this; - }, - async *byPage(settings?: TSettings) { - // Pass the maxPageSize value to the underlying page operation - const iteratorByPage = operation({ ...options, maxresults: settings?.maxPageSize }).byPage( - settings, - ); - for await (const page of iteratorByPage) { - yield page.map(mapper); - } - }, - }; -} diff --git a/sdk/keyvault/keyvault-keys/swagger/README.md b/sdk/keyvault/keyvault-keys/swagger/README.md deleted file mode 100644 index 65242f4a8b3f..000000000000 --- a/sdk/keyvault/keyvault-keys/swagger/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# KeyVault Keys Swagger Configuration - -> see https://aka.ms/autorest - -```yaml -package-name: "@azure/keyvault-keys" -azure-arm: false -generate-metadata: false -add-credentials: false -core-http-compat-mode: true -use-core-v2: true -license-header: MICROSOFT_MIT_NO_VERSION -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/7452e1cc7db72fbc6cd9539b390d8b8e5c2a1864/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.5/keys.json -output-folder: ../ -source-code-folder-path: ./src/generated -disable-async-iterators: true -api-version-parameter: choice -package-version: 4.9.1 -use-extension: - "@autorest/typescript": "6.0.0-beta.19" -``` - -## Customizations for Track 2 Generator - -See the [AutoRest samples](https://github.com/Azure/autorest/tree/master/Samples/3b-custom-transformations) -for more about how we're customizing things. - -### Rename aad as KeyOperationsParameters - -```yaml -directive: - - from: swagger-document - where: $.definitions.KeyOperationsParameters.properties.aad - transform: > - $["x-ms-client-name"] = "additionalAuthenticatedData"; - - from: swagger-document - where: $.definitions.KeyOperationsParameters.properties.tag - transform: > - $["x-ms-client-name"] = "authenticationTag" -``` - -### Update swagger enum values for LifetimeActionsType to reflect what the service actually returns - -```yaml -directive: - - from: swagger-document - where: $.definitions.LifetimeActionsType.properties["type"]["x-ms-enum"] - transform: > - $.values[0].value = "Rotate"; - $.values[1].value = "Notify"; -``` - -### Rename KeyReleasePolicy.data to KeyReleasePolicy.encodedPolicy - -```yaml -directive: - - from: swagger-document - where: $.definitions.KeyReleasePolicy.properties.data - transform: > - $["x-ms-client-name"] = "encodedPolicy"; -``` - -## Rename certain models back to what they were before 7.4 - -```yaml -directive: - - from: certificates.json - where: $.definitions.Action - transform: $.properties.action_type["x-ms-enum"].name = "ActionType"; - - from: keys.json - where: $.definitions.LifetimeActionsType - transform: $.properties.type["x-ms-enum"].name = "ActionType"; -``` diff --git a/sdk/keyvault/keyvault-keys/test/README.md b/sdk/keyvault/keyvault-keys/test/README.md deleted file mode 100644 index ec2f9a0a11fd..000000000000 --- a/sdk/keyvault/keyvault-keys/test/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Testing - -## Overview - -To test this project, make sure to build it by following our [building instructions](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md#building), then follow the [testing instructions](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md#testing). - -You can use existing Azure resources for the live tests, or generate new ones by using our [New-TestResources.ps1](https://github.com/Azure/azure-sdk-for-js/blob/main/eng/common/TestResources/New-TestResources.ps1) script, which will use a [Bicep template](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/test-resources.bicep) that already has all of the the necessary configurations. - -## Managed HSM tests - -Some tests require an Azure Managed HSM to run in live mode, which will need to be deployed and activated. To do so you'll want to pass `enableHsm` as an ARM template parameter. - -As an example: - -```powershell -New-TestResources.ps1 -ServiceDirectory 'keyvault' -ArmTemplateParameters @{ "enableHsm" = $true } -``` - -The `New-TestResources` script will ensure that the Managed HSM is activated; however, if you are creating your own Managed HSM there are additional steps required to set up the correct permissions and activate the HSM. Please see [Activate Your Managed HSM](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/README.md#activate-your-managed-hsm) for more information. - -> Managed HSMs do have an hourly cost even when not in-use. Please review the [Azure Dedicated HSM Pricing page](https://azure.microsoft.com/pricing/details/azure-dedicated-hsm/#pricing) and clean up the resources when not in use. - -Tests that require a managed HSM will be skipped if the `AZURE_MANAGEDHSM_URI` environment variable is not defined in live mode. - -The Azure resource that is used by the tests in this project is: - -- An [Azure Key Vault](https://learn.microsoft.com/azure/key-vault/general/basic-concepts). Your Azure Active Directory application needs to be added to the Access Policies of the Key Vault. The steps are provided [below](#aad-based-authentication). -- An [Azure Key Vault Managed HSM](https://learn.microsoft.com/azure/key-vault/general/basic-concepts). Your Azure Active Directory application needs to be added to the Access Policies of the Key Vault. The steps are provided [below](#aad-based-authentication). -- An [Azure Web App for Containers](https://learn.microsoft.com/azure/app-service/tutorial-custom-container?pivots=container-linux) is used to deploy a mock attestation service that is used to generate tokens and verify tokens by the HSM. The source code for the attestation service is hosted on [GitHub](https://github.com/Azure/azure-sdk-tools/tree/main/tools/keyvault-mock-attestation) and is deployed by the same ARM template. - -To run the live tests, you will also need to set the below environment variables: - -- `TEST_MODE`: Should have `live` assigned. -- `AZURE_CLIENT_ID`: The client ID of an Azure Active Directory application. -- `AZURE_CLIENT_SECRET`: The client secret of an Azure Active Directory application. -- `AZURE_TENANT_ID`: The Tenant ID of your organization in Azure Active Directory. -- `KEYVAULT_URI`: The URI of the KeyVault to use. -- `AZURE_KEYVAULT_ATTESTATION_URI`: The URI of the mock attestation service used for Secure Key Release tests. - -In addition, when running HSM based live tests the following environment variables are required: - -> If `AZURE_MANAGEDHSM_URI` is not defined, these tests will be skipped in live mode. - -- `AZURE_MANAGEDHSM_URI`: The URI of the Azure Managed HSM to use in the Managed HSM tests. - -The live tests in this project will create, modify and delete [keys](https://learn.microsoft.com/azure/key-vault/keys/about-keys) inside of the provided Azure Key Vault. - -## AAD based authentication - -The following steps will help you setup the AAD credentials. - -### Register a new application in AAD - -- Follow [Documentation to register a new application](https://learn.microsoft.com/azure/active-directory/develop/quickstart-register-app) in the Azure Active Directory (in the Azure portal). -- Note down the `CLIENT_ID` and `TENANT_ID`. -- In the "Certificates & Secrets" tab, create a secret and note that down. - -### Allow your registered application to access your Key Vault - -- In the Azure portal, go to your Azure Key Vault. -- In the left-side-navbar of your Azure Key Vault in the Azure portal, go to the `Access Policies` section, then click the `+ Add Access Policy` button. -- In the `Add access policy` page, select all the permissions for Keys, Secrets and Certificates. -- For the `Select principal` field, click on the `None selected`. A panel will appear at the right of the window. Search for your Azure Active Directory application, click the application on the search results, then click "Select" at the bottom. -- Once your application is selected, click the "Add" button. -- Click the `Save` button at the top of the Access Policies section of your Key Vault. -- For more information on securing your Key Vault: [Learn more](https://learn.microsoft.com/azure/key-vault/general/secure-your-key-vault) - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fkeyvault%2Fkeyvault-keys%2Ftest%2FREADME.png) diff --git a/sdk/keyvault/keyvault-keys/test/internal/aesCryptography.spec.ts b/sdk/keyvault/keyvault-keys/test/internal/aesCryptography.spec.ts deleted file mode 100644 index 1ead945c7d2a..000000000000 --- a/sdk/keyvault/keyvault-keys/test/internal/aesCryptography.spec.ts +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import type { - AesCbcEncryptionAlgorithm, - JsonWebKey, - KeyClient, - KeyVaultKey, -} from "../../src/index.js"; -import { CryptographyClient } from "../../src/index.js"; -import { getKey, stringToUint8Array, uint8ArrayToString } from "../public/utils/crypto.js"; -import TestClient from "../public/utils/testClient.js"; -import { authenticate, envSetupForPlayback } from "../public/utils/testAuthentication.js"; -import { Recorder, env, isLiveMode } from "@azure-tools/test-recorder"; -import { RemoteCryptographyProvider } from "../../src/cryptography/remoteCryptographyProvider.js"; -import type { ClientSecretCredential } from "@azure/identity"; -import { describe, it, expect, beforeEach, afterEach } from "vitest"; - -describe("AesCryptographyProvider internal tests", function () { - for (const keySize of [128, 192, 256]) { - let cryptoClient: CryptographyClient; - const encryptionAlgorithm = `A${keySize}CBCPAD` as AesCbcEncryptionAlgorithm; - let jwk: JsonWebKey; - - beforeEach(function () { - jwk = { - keyOps: ["encrypt", "decrypt", "wrapKey", "unwrapKey"], - k: getKey(keySize >> 3), // Generate a symmetric key for testing - kty: "oct", - }; - - cryptoClient = new CryptographyClient(jwk); - }); - - describe(`AES-CBC with PKCS padding (${keySize})`, () => { - describe("local-only tests", async function () { - it("encrypts and decrypts locally", async function (ctx) { - const text = ctx.task.name; - const encryptResult = await cryptoClient.encrypt({ - algorithm: encryptionAlgorithm, - plaintext: stringToUint8Array(text), - // Test the client generating an IV - }); - - const decryptResult = await cryptoClient.decrypt({ - algorithm: encryptionAlgorithm, - ciphertext: encryptResult.result!, - iv: encryptResult.iv!, - }); - expect(uint8ArrayToString(decryptResult.result)).toEqual(text); - }); - - it("validates the key type", async function (ctx) { - const text = ctx.task.name; - jwk.kty = "RSA"; - - await expect( - cryptoClient.encrypt({ - algorithm: encryptionAlgorithm, - plaintext: stringToUint8Array(text), - iv: getKey(16), - }), - ).rejects.toThrow(/Key type does not match/); - - await expect( - cryptoClient.decrypt({ - algorithm: encryptionAlgorithm, - ciphertext: stringToUint8Array(text), - iv: getKey(16), - }), - ).rejects.toThrow(/Key type does not match/); - }); - - it("validates the key length", async function (ctx) { - const text = ctx.task.name; - jwk.k = getKey((keySize >> 3) - 1); - - await expect( - cryptoClient.encrypt({ - algorithm: encryptionAlgorithm, - plaintext: stringToUint8Array(text), - iv: getKey(16), - }), - ).rejects.toThrow(/Key must be at least \d+ bits/); - - await expect( - cryptoClient.decrypt({ - algorithm: encryptionAlgorithm, - ciphertext: stringToUint8Array(text), - iv: getKey(16), - }), - ).rejects.toThrow(/Key must be at least \d+ bits/); - }); - }); - - describe("local-remote tests", async function () { - const keyPrefix = `CRUD${env.KEY_NAME || "KeyName"}`; - let keySuffix: string; - let credential: ClientSecretCredential; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - let keyVaultKey: KeyVaultKey; - let remoteProvider: RemoteCryptographyProvider; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - - if (!authentication.hsmClient) { - // Managed HSM is not deployed for this run due to service resource restrictions so we skip these tests. - // This is only necessary while Managed HSM is in preview. - ctx.skip(); - } - - client = authentication.hsmClient; - credential = authentication.credential; - testClient = new TestClient(authentication.hsmClient); - keySuffix = authentication.keySuffix; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - it("encrypts locally and decrypts remotely", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - keyVaultKey = await client.importKey(keyName, jwk, {}); - remoteProvider = new RemoteCryptographyProvider( - keyVaultKey, - credential, - recorder.configureClientOptions({ - disableChallengeResourceVerification: !isLiveMode(), - }), - ); - - const text = ctx.task.name; - const iv = getKey(16); - const encryptResult = await cryptoClient.encrypt({ - algorithm: encryptionAlgorithm, - plaintext: stringToUint8Array(text), - iv: iv, - }); - - const decryptResult = await remoteProvider.decrypt({ - algorithm: encryptionAlgorithm, - ciphertext: encryptResult.result!, - iv: encryptResult.iv!, - }); - expect(uint8ArrayToString(decryptResult.result)).toEqual(text); - await testClient.flushKey(keyName); - }); - - it("encrypts remotely and decrypts locally", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - keyVaultKey = await client.importKey(keyName, jwk, {}); - remoteProvider = new RemoteCryptographyProvider( - keyVaultKey, - credential, - recorder.configureClientOptions({ - disableChallengeResourceVerification: !isLiveMode(), - }), - ); - - const text = ctx.task.name; - const iv = getKey(16); - const encryptResult = await remoteProvider.encrypt({ - algorithm: encryptionAlgorithm, - plaintext: stringToUint8Array(text), - iv, - }); - - const decryptResult = await cryptoClient.decrypt({ - algorithm: encryptionAlgorithm, - ciphertext: encryptResult.result!, - iv: encryptResult.iv || iv, - }); - - expect(uint8ArrayToString(decryptResult.result)).toEqual(text); - await testClient.flushKey(keyName); - }); - }); - }); - } -}); diff --git a/sdk/keyvault/keyvault-keys/test/internal/crypto.spec.ts b/sdk/keyvault/keyvault-keys/test/internal/crypto.spec.ts deleted file mode 100644 index 597ea2830d6f..000000000000 --- a/sdk/keyvault/keyvault-keys/test/internal/crypto.spec.ts +++ /dev/null @@ -1,455 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { TokenCredential } from "@azure/core-auth"; -import type { DecryptParameters, EncryptParameters, KeyVaultKey } from "../../src/index.js"; -import { CryptographyClient, KeyClient } from "../../src/index.js"; -import { RsaCryptographyProvider } from "../../src/cryptography/rsaCryptographyProvider.js"; -import type { JsonWebKey } from "../../src/index.js"; -import { stringToUint8Array } from "../public/utils/crypto.js"; -import type { CryptographyProvider } from "../../src/cryptography/models.js"; -import { RemoteCryptographyProvider } from "../../src/cryptography/remoteCryptographyProvider.js"; -import { NoOpCredential } from "@azure-tools/test-credential"; -import type { SendRequest } from "@azure/core-rest-pipeline"; -import { RestError, createHttpHeaders } from "@azure/core-rest-pipeline"; -import type { MockInstance } from "vitest"; -import { describe, it, assert, expect, vi, beforeEach, afterEach } from "vitest"; - -describe("internal crypto tests", () => { - const tokenCredential: TokenCredential = { - getToken: () => Promise.resolve(null), - }; - - describe("with a Key identifier", () => { - it("parses the vaultUrl", () => { - const client = new CryptographyClient( - "https://my.vault.azure.net/keys/keyId/v1", - tokenCredential, - ); - assert.equal(client.vaultUrl, "https://my.vault.azure.net"); - }); - - it("throws if id is invalid", () => { - assert.throws( - () => new CryptographyClient("foo", tokenCredential), - /not a valid Key Vault key ID/, - ); - }); - - it("allows version to be omitted", () => { - const client = new CryptographyClient( - "https://my.vault.azure.net/keys/keyId", - tokenCredential, - ); - assert.equal(client.vaultUrl, "https://my.vault.azure.net"); - }); - }); - - describe("with a KeyVault Key", () => { - let key: KeyVaultKey; - beforeEach(() => { - key = { - name: "key", - id: "https://azure_keyvault.vault.azure.net/keys/keyId/v1", - properties: { - name: "key", - vaultUrl: "foo", - }, - }; - }); - - describe("checkKeyValidity", () => { - it("Checking that the key's notBefore is respected", async function () { - const notBefore = new Date(Date.now() + 60 * 1000 * 60 * 24); // Now + 24h - key.properties.notBefore = notBefore; - const cryptoClient = new CryptographyClient(key, tokenCredential); - await expect(cryptoClient.encrypt("RSA1_5", stringToUint8Array(""))).rejects.toThrow( - `Key ${key.id} can't be used before ${notBefore.toISOString()}`, - ); - }); - - it("Checking that the key's expires is respected", async function () { - const expiresOn = new Date(Date.now() - 60 * 1000 * 60 * 24); // Now - 24h - key.properties.expiresOn = expiresOn; - const cryptoClient = new CryptographyClient(key, tokenCredential); - await expect(cryptoClient.encrypt("RSA1_5", stringToUint8Array(""))).rejects.toThrow( - `Key ${key.id} expired at ${expiresOn.toISOString()}`, - ); - }); - - it("validates key operations", async () => { - const cryptoClient = new CryptographyClient(key, tokenCredential); - key.keyOperations = ["encrypt"]; - await expect(cryptoClient.decrypt("RSA1_5", stringToUint8Array(""))).rejects.toThrow(); - }); - - it("parses the vaultUrl", () => { - const client = new CryptographyClient(key, tokenCredential); - assert.equal(client.vaultUrl, "https://azure_keyvault.vault.azure.net"); - }); - it("throws if id is invalid", () => { - key.id = "invalid_id"; - assert.throws( - () => new CryptographyClient(key, tokenCredential), - /not a valid Key Vault key ID/, - ); - }); - }); - }); - - describe("with a JsonWebKey", () => { - let key: JsonWebKey; - - beforeEach(() => { - key = {}; - }); - - it("validates key operations", async () => { - const cryptoClient = new CryptographyClient(key); - key.keyOps = ["encrypt"]; - await expect(cryptoClient.decrypt("RSA1_5", stringToUint8Array(""))).rejects.toThrow( - /Operation decrypt is not supported/, - ); - }); - }); - - describe("from a keyClient", () => { - it("shares the generated client", () => { - const keyClient = new KeyClient("https://my.vault.azure.net/", tokenCredential); - const cryptoClient = keyClient.getCryptographyClient("keyId", { keyVersion: "v1" }); - assert.strictEqual(keyClient["client"], cryptoClient["remoteProvider"]!["client"]); - }); - - it("supports omitting key version", () => { - const keyClient = new KeyClient("https://my.vault.azure.net/", tokenCredential); - const cryptoClient = keyClient.getCryptographyClient("keyId"); - assert.strictEqual(keyClient["client"], cryptoClient["remoteProvider"]!["client"]); - }); - }); - - describe("Parameter passing to encrypt / decrypt", function () { - let client: CryptographyClient; - let cryptoProvider: CryptographyProvider; - let encryptStub: MockInstance; - let decryptStub: MockInstance; - - beforeEach(() => { - const key = { - id: "https://my.vault.azure.net/keys/keyId/v1", - name: "fake key", - properties: { name: "fake key", vaultUrl: "https://keyvault.vault.azure.net" }, - }; - client = new CryptographyClient(key, tokenCredential); - cryptoProvider = new RemoteCryptographyProvider(key, tokenCredential); - encryptStub = vi - .spyOn(cryptoProvider, "encrypt") - .mockReturnValue(Promise.resolve({ algorithm: "", result: stringToUint8Array("") })); - decryptStub = vi - .spyOn(cryptoProvider, "decrypt") - .mockReturnValue(Promise.resolve({ algorithm: "", result: stringToUint8Array("") })); - vi.spyOn(cryptoProvider, "isSupported").mockReturnValue(true); - client["providers"] = [cryptoProvider]; - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - describe("Encrypt parameter mapping", async function () { - it("maps parameters correctly when using the previous API", async function (ctx) { - const text = stringToUint8Array(ctx.task.name!); - await client.encrypt("RSA1_5", text, { requestOptions: { timeout: 5 } }); - - expect(encryptStub).toHaveBeenCalledWith( - { algorithm: "RSA1_5", plaintext: text }, - expect.objectContaining({ requestOptions: { timeout: 5 } }), - ); - }); - - it("maps parameters correctly when using the current API", async function (ctx) { - const text = stringToUint8Array(ctx.task.name!); - - await client.encrypt( - { algorithm: "RSA1_5", plaintext: text }, - { requestOptions: { timeout: 5 } }, - ); - - expect(encryptStub).toHaveBeenCalledWith( - { algorithm: "RSA1_5", plaintext: text }, - expect.objectContaining({ requestOptions: { timeout: 5 } }), - ); - }); - }); - - describe("Decrypt parameter mapping", async function () { - it("maps parameters correctly when using the previous API", async function (ctx) { - const text = stringToUint8Array(ctx.task.name!); - await client.decrypt("RSA1_5", text, { requestOptions: { timeout: 5 } }); - - expect(decryptStub).toHaveBeenCalledWith( - { algorithm: "RSA1_5", ciphertext: text }, - expect.objectContaining({ requestOptions: { timeout: 5 } }), - ); - }); - - it("maps parameters correctly when using the current API", async function (ctx) { - const text = stringToUint8Array(ctx.task.name!); - - await client.decrypt( - { algorithm: "RSA1_5", ciphertext: text }, - { requestOptions: { timeout: 5 } }, - ); - - expect(decryptStub).toHaveBeenCalledWith( - { algorithm: "RSA1_5", ciphertext: text }, - expect.objectContaining({ requestOptions: { timeout: 5 } }), - ); - }); - }); - }); - - describe("RSA local cryptography tests", function () { - it("throws a validation error when the key is invalid", function () { - const rsaProvider = new RsaCryptographyProvider({ kty: "AES", keyOps: ["encrypt"] }); - assert.throws( - () => rsaProvider.encrypt({ algorithm: "RSA1_5", plaintext: stringToUint8Array("foo") }), - "Key type does not match the algorithm RSA", - ); - }); - }); - - describe("cryptography client error handling", function () { - let cryptoClient: CryptographyClient; - let localProvider: RsaCryptographyProvider; - - beforeEach(() => { - localProvider = new RsaCryptographyProvider({}); - vi.spyOn(localProvider, "isSupported").mockReturnValue(true); - for (const operation of [ - "encrypt", - "decrypt", - "sign", - "wrapKey", - "unwrapKey", - "signData", - "verify", - "verifyData", - ] as const) { - vi.spyOn(localProvider, operation).mockImplementation(() => { - throw new Error("Local error"); - }); - } - }); - - afterEach(function () { - vi.restoreAllMocks(); - }); - - describe("hybrid mode", function () { - let remoteProvider: RemoteCryptographyProvider; - - beforeEach(() => { - const key: KeyVaultKey = { - name: "key", - id: "https://my_keyvault.vault.azure.net/keys/id/version", - properties: { - name: "key", - vaultUrl: "http://my_keyvault.vault.azure.net", - id: "https://my_keyvault.vault.azure.net/keys/id/version", - }, - key: { - kid: "https://my_keyvault.vault.azure.net/keys/id/version", - }, - }; - - remoteProvider = new RemoteCryptographyProvider(key, tokenCredential); - cryptoClient = new CryptographyClient(key, tokenCredential); - - // Setup the crypto client with our stubs - cryptoClient["providers"] = [localProvider, remoteProvider]; - cryptoClient["remoteProvider"] = remoteProvider; - }); - - describe("when creating the client with an identifier", function () { - it("falls back to the remote provider when the key cannot be fetched due to permissions", async function () { - const sendSignRequest: SendRequest = (request) => - Promise.resolve({ - status: 200, - headers: createHttpHeaders(), - request: request, - bodyAsText: JSON.stringify({ - key: { - kid: `https://my_keyvault.vault.azure.net/keys/keyName/id`, - value: "signature", - }, - }), - }); - - const sendRequest = vi.fn(); - sendRequest.mockImplementation(sendSignRequest); - sendRequest.mockReturnValueOnce( - Promise.reject(new RestError("Forbidden", { statusCode: 403 })), - ); - - const idCryptoClient = new CryptographyClient( - "https://myvault.vault.azure.net/keys/keyName/id", - new NoOpCredential(), - { - httpClient: { - sendRequest, - }, - }, - ); - - await idCryptoClient.sign("RS256", new Uint8Array([1, 2, 3])); - }); - }); - - describe("when a local provider errors", function () { - it("remotes the encrypt operation", async function () { - const remoteStub = vi - .spyOn(remoteProvider, "encrypt") - .mockResolvedValue({ algorithm: "", result: new Uint8Array(0) }); - - const parameters: EncryptParameters = { - algorithm: "RSA-OAEP", - plaintext: stringToUint8Array("text"), - }; - - await cryptoClient.encrypt(parameters); - expect(remoteStub).toHaveBeenCalledWith(parameters, expect.anything()); - }); - - it("remotes the decrypt operation", async function () { - const remoteStub = vi - .spyOn(remoteProvider, "decrypt") - .mockResolvedValue({ algorithm: "", result: new Uint8Array(0) }); - - const parameters: DecryptParameters = { - algorithm: "RSA-OAEP", - ciphertext: stringToUint8Array("text"), - }; - await cryptoClient.decrypt(parameters); - expect(remoteStub).toHaveBeenCalledWith(parameters, expect.anything()); - }); - - it("remotes the wrapKey operation", async function () { - const remoteStub = vi - .spyOn(remoteProvider, "wrapKey") - .mockResolvedValue({ algorithm: "A128KW", result: new Uint8Array(0) }); - - const keyToWrap = stringToUint8Array("myKey"); - await cryptoClient.wrapKey("RSA-OAEP", keyToWrap); - expect(remoteStub).toHaveBeenCalledWith("RSA-OAEP", keyToWrap, expect.anything()); - }); - - it("remotes the unwrapKey operation", async function () { - const remoteStub = vi - .spyOn(remoteProvider, "unwrapKey") - .mockResolvedValue({ algorithm: "A128KW", result: new Uint8Array(0) }); - - const wrappedKey = stringToUint8Array("myKey"); - await cryptoClient.unwrapKey("RSA-OAEP", wrappedKey); - expect(remoteStub).toHaveBeenCalledWith("RSA-OAEP", wrappedKey, expect.anything()); - }); - - it("remotes the sign operation", async function () { - const remoteStub = vi - .spyOn(remoteProvider, "sign") - .mockResolvedValue({ algorithm: "PS256", result: new Uint8Array(0) }); - - const data = stringToUint8Array("myKey"); - await cryptoClient.sign("PS256", data); - expect(remoteStub).toHaveBeenCalledWith("PS256", data, expect.anything()); - }); - - it("remotes the signData operation", async function () { - const remoteStub = vi - .spyOn(remoteProvider, "signData") - .mockResolvedValue({ algorithm: "PS256", result: new Uint8Array(0) }); - - const data = stringToUint8Array("myKey"); - await cryptoClient.signData("PS256", data); - expect(remoteStub).toHaveBeenCalledWith("PS256", data, expect.anything()); - }); - - it("remotes the verify operation", async function () { - const remoteStub = vi.spyOn(remoteProvider, "verify").mockResolvedValue({ result: true }); - - const data = stringToUint8Array("myKey"); - const sig = stringToUint8Array("sig"); - await cryptoClient.verify("PS256", data, sig); - expect(remoteStub).toHaveBeenCalledWith("PS256", data, sig, expect.anything()); - }); - - it("remotes the verifyData operation", async function () { - const remoteStub = vi - .spyOn(remoteProvider, "verifyData") - .mockResolvedValue({ result: true }); - - const data = stringToUint8Array("myKey"); - const sig = stringToUint8Array("sig"); - await cryptoClient.verifyData("PS256", data, sig); - expect(remoteStub).toHaveBeenCalledWith("PS256", data, sig, expect.anything()); - }); - }); - }); - - describe("local only mode", function () { - beforeEach(() => { - const jwk: JsonWebKey = {}; - localProvider = new RsaCryptographyProvider(jwk); - vi.spyOn(localProvider, "isSupported").mockReturnValue(true); - - cryptoClient = new CryptographyClient(jwk); - - // Setup the crypto client with our stubs - cryptoClient["providers"] = [localProvider]; - }); - - describe("when a local provider errors", function () { - it("throws the original encrypt exception", async function () { - await expect( - cryptoClient.encrypt({ algorithm: "RSA-OAEP", plaintext: stringToUint8Array("text") }), - ).rejects.toThrow(); - }); - - it("throws the original decrypt exception", async function () { - await expect( - cryptoClient.decrypt({ algorithm: "RSA-OAEP", ciphertext: stringToUint8Array("text") }), - ).rejects.toThrow(); - }); - - it("throws the original wrapKey exception", async function () { - await expect( - cryptoClient.wrapKey("RSA-OAEP", stringToUint8Array("myKey")), - ).rejects.toThrow(); - }); - - it("throws the original unwrapKey exception", async function () { - await expect( - cryptoClient.unwrapKey("RSA-OAEP", stringToUint8Array("myKey")), - ).rejects.toThrow(); - }); - it("throws the original sign exception", async function () { - await expect(cryptoClient.sign("PS256", stringToUint8Array("data"))).rejects.toThrow(); - }); - it("throws the original signData exception", async function () { - await expect( - cryptoClient.signData("PS256", stringToUint8Array("data")), - ).rejects.toThrow(); - }); - it("throws the original verify exception", async function () { - await expect( - cryptoClient.verify("PS256", stringToUint8Array("data"), stringToUint8Array("sig")), - ).rejects.toThrow(); - }); - it("throws the original verifyData exception", async function () { - await expect( - cryptoClient.verifyData("PS256", stringToUint8Array("data"), stringToUint8Array("sig")), - ).rejects.toThrow(); - }); - }); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/internal/lroUnexpectedErrors.spec.ts b/sdk/keyvault/keyvault-keys/test/internal/lroUnexpectedErrors.spec.ts deleted file mode 100644 index 4e9c222dfbd1..000000000000 --- a/sdk/keyvault/keyvault-keys/test/internal/lroUnexpectedErrors.spec.ts +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { RestError } from "@azure/core-rest-pipeline"; -import { DeleteKeyPoller } from "../../src/lro/delete/poller.js"; -import { RecoverDeletedKeyPoller } from "../../src/lro/recover/poller.js"; -import { describe, it, assert } from "vitest"; - -describe("The LROs properly throw on unexpected errors", () => { - describe("delete LRO", () => { - it("403 doesn't throw", async function () { - const code = 403; - const client: any = { - async deleteKey(): Promise { - return { - key: { - kid: "https://keyVaultName.vault.azure.net/version/name/version", - }, - recoveryId: "something", - }; - }, - async getDeletedKey(): Promise { - throw new RestError(`${code}`, { statusCode: code }); - }, - }; - const poller = new DeleteKeyPoller({ - name: "name", - client, - }); - - await poller.pollUntilDone(); - - assert.isTrue(poller.getOperationState().isCompleted); - }); - - it("404 doesn't throw", async function () { - const code = 404; - const client: any = { - async deleteKey(): Promise { - return { - key: { - kid: "https://keyVaultName.vault.azure.net/version/name/version", - }, - recoveryId: "something", - }; - }, - async getDeletedKey(): Promise { - throw new RestError(`${code}`, { statusCode: code }); - }, - }; - const poller = new DeleteKeyPoller({ - name: "name", - client, - }); - - await poller.poll(); - await poller.poll(); - - assert.isUndefined(poller.getOperationState().isCompleted); - }); - - it("Errors other than 403 and 404 throw", async function () { - const codes = [401, 402, 405, 500]; - for (const code of codes) { - const client: any = { - async deleteKey(): Promise { - return { - key: { - kid: "https://keyVaultName.vault.azure.net/version/name/version", - }, - recoveryId: "something", - }; - }, - async getDeletedKey(): Promise { - throw new RestError(`${code}`, { statusCode: code }); - }, - }; - const poller = new DeleteKeyPoller({ - name: "name", - client, - }); - - let error: Error | null = null; - try { - await poller.pollUntilDone(); - } catch (e: any) { - error = e; - } - - assert.equal((error as any).statusCode, code); - } - }); - }); - - describe("recover LRO", () => { - it("403 doesn't throw", async function () { - const code = 403; - const client: any = { - async recoverDeletedKey(): Promise { - return { - key: { - kid: "https://keyVaultName.vault.azure.net/version/name/version", - }, - recoveryId: "something", - }; - }, - async getKey(): Promise { - throw new RestError(`${code}`, { statusCode: code }); - }, - }; - const poller = new RecoverDeletedKeyPoller({ - name: "name", - client, - }); - - await poller.pollUntilDone(); - - assert.isTrue(poller.getOperationState().isCompleted); - }); - - it("404 doesn't throw", async function () { - const code = 404; - const client: any = { - async recoverDeletedKey(): Promise { - return { - key: { - kid: "https://keyVaultName.vault.azure.net/version/name/version", - }, - recoveryId: "something", - }; - }, - async getKey(): Promise { - throw new RestError(`${code}`, { statusCode: code }); - }, - }; - const poller = new RecoverDeletedKeyPoller({ - name: "name", - client, - }); - - await poller.poll(); - await poller.poll(); - - assert.isUndefined(poller.getOperationState().isCompleted); - }); - - it("Errors other than 403 and 404 throw", async function () { - const codes = [401, 402, 405, 500]; - for (const code of codes) { - const client: any = { - async recoverDeletedKey(): Promise { - return { - key: { - kid: "https://keyVaultName.vault.azure.net/version/name/version", - }, - recoveryId: "something", - }; - }, - async getKey(): Promise { - throw new RestError(`${code}`, { statusCode: code }); - }, - }; - const poller = new RecoverDeletedKeyPoller({ - name: "name", - client, - }); - - let error: Error | null = null; - try { - await poller.pollUntilDone(); - } catch (e: any) { - error = e; - } - - assert.equal((error as any).statusCode, code); - } - }); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/internal/recoverBackupRestore.spec.ts b/sdk/keyvault/keyvault-keys/test/internal/recoverBackupRestore.spec.ts deleted file mode 100644 index dfb0f39f9576..000000000000 --- a/sdk/keyvault/keyvault-keys/test/internal/recoverBackupRestore.spec.ts +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import type { KeyClient } from "../../src/index.js"; -import { testPollerProperties } from "../public/utils/recorderUtils.js"; -import { Recorder, env, isPlaybackMode, isRecordMode } from "@azure-tools/test-recorder"; -import { authenticate, envSetupForPlayback } from "../public/utils/testAuthentication.js"; -import type TestClient from "../public/utils/testClient.js"; -import { RestoreKeyBackupPoller } from "../public/utils/lro/restore/poller.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("Keys client - restore keys and recover backups", () => { - const keyPrefix = `backupRestore${env.KEY_NAME || "KeyName"}`; - let keySuffix: string; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - keySuffix = authentication.keySuffix; - client = authentication.client; - testClient = authentication.testClient; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - // The tests follow - - it("can recover a deleted key", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const deletePoller = await client.beginDeleteKey(keyName, testPollerProperties); - assert.equal( - deletePoller.getResult()!.name, - keyName, - "Unexpected key name in result from deletePoller.getResult().", - ); - await deletePoller.pollUntilDone(); - - const getDeletedResult = await deletePoller.getResult(); - assert.equal(getDeletedResult!.name, keyName, "Unexpected key name in result from getKey()."); - - const recoverPoller = await client.beginRecoverDeletedKey(keyName, testPollerProperties); - await recoverPoller.pollUntilDone(); - const getResult = await client.getKey(keyName); - assert.equal(getResult.name, keyName, "Unexpected key name in result from getKey()."); - await testClient.flushKey(keyName); - }); - - it("fails if one tries to recover a non-existing deleted key", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - let error; - try { - const recoverPoller = await client.beginRecoverDeletedKey(keyName, testPollerProperties); - await recoverPoller.pollUntilDone(); - throw Error("Expecting an error but not catching one."); - } catch (e: any) { - error = e; - } - assert.equal(error.code, "KeyNotFound"); - assert.equal(error.statusCode, 404); - }); - - it("can generate a backup of a key", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const result = await client.backupKey(keyName); - assert.equal(Buffer.isBuffer(result), true, "Unexpected return value from backupKey()"); - assert.ok(result!.length > 0, "Unexpected length of buffer from backupKey()"); - await testClient.flushKey(keyName); - }); - - it("fails to generate a backup of a non-existing key", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - let error; - try { - await client.backupKey(keyName); - throw Error("Expecting an error but not catching one."); - } catch (e: any) { - error = e; - } - assert.equal(error.code, "KeyNotFound"); - assert.equal(error.statusCode, 404); - }); - - if (isRecordMode() || isPlaybackMode()) { - // This test can't run live, - // since the purge operation currently can't be expected to finish anytime soon. - it("can restore a key with a given backup", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const backup = await client.backupKey(keyName); - const deletePoller = await client.beginDeleteKey(keyName, testPollerProperties); - await deletePoller.pollUntilDone(); - await client.purgeDeletedKey(keyName); - - // One would normally do this, but this can't immediately happen after the resource is purged: - // await client.restoreKeyBackup(backup as Uint8Array); - - // This test implementation of a restore poller only applies for backups that have been recently deleted. - // Backups might not be ready to be restored in an unknown amount of time. - // If this is useful to you, please open an issue at: https://github.com/Azure/azure-sdk-for-js/issues - const restorePoller = new RestoreKeyBackupPoller({ - backup: backup!, - client, - intervalInMs: testPollerProperties.intervalInMs, - }); - - const restoredKey = await restorePoller.pollUntilDone(); - - assert.equal(restoredKey.name, keyName); - await testClient.flushKey(keyName); - }); - } - - it("fails to restore a key with a malformed backup", async function () { - const backup = new Uint8Array(8693); - let error; - try { - await client.restoreKeyBackup(backup); - throw Error("Expecting an error but not catching one."); - } catch (e: any) { - error = e; - } - assert.equal( - error.message, - "Backup blob contains invalid or corrupt version.", - "Unexpected error from restoreKeyBackup()", - ); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/internal/serviceVersionParameter.spec.ts b/sdk/keyvault/keyvault-keys/test/internal/serviceVersionParameter.spec.ts deleted file mode 100644 index ae8baf523ee3..000000000000 --- a/sdk/keyvault/keyvault-keys/test/internal/serviceVersionParameter.spec.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { KeyClient } from "../../src/index.js"; -import { LATEST_API_VERSION } from "../../src/keysModels.js"; -import type { - HttpClient, - PipelineRequest, - PipelineResponse, - SendRequest, -} from "@azure/core-rest-pipeline"; -import { createHttpHeaders } from "@azure/core-rest-pipeline"; -import { ClientSecretCredential } from "@azure/identity"; -import type { MockInstance } from "vitest"; -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - -describe("The Keys client should set the serviceVersion", () => { - const keyVaultUrl = `https://keyvaultname.vault.azure.net`; - - const mockHttpClient: HttpClient = { - async sendRequest(request: PipelineRequest): Promise { - return { - status: 200, - headers: createHttpHeaders(), - request: request, - bodyAsText: JSON.stringify({ - key: { - kid: `${keyVaultUrl}/keys/keyName/id`, - }, - }), - }; - }, - }; - - let spy: MockInstance; - let credential: ClientSecretCredential; - beforeEach(async () => { - spy = vi.spyOn(mockHttpClient, "sendRequest"); - - credential = new ClientSecretCredential("tenant", "client", "secret"); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("it should default to the latest API version", async function () { - const client = new KeyClient(keyVaultUrl, credential, { - httpClient: mockHttpClient, - }); - await client.createKey("keyName", "RSA"); - - expect(spy).toHaveBeenCalledWith( - expect.objectContaining({ - url: `https://keyvaultname.vault.azure.net/keys/keyName/create?api-version=${LATEST_API_VERSION}`, - }), - ); - }); - - it("it should allow us to specify an API version from a specific set of versions", async function () { - const client = new KeyClient(keyVaultUrl, credential, { - serviceVersion: "7.0", - httpClient: mockHttpClient, - }); - await client.createKey("keyName", "RSA"); - - expect(spy).toHaveBeenCalledWith( - expect.objectContaining({ - url: `https://keyvaultname.vault.azure.net/keys/keyName/create?api-version=7.0`, - }), - ); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/internal/transformations.spec.ts b/sdk/keyvault/keyvault-keys/test/internal/transformations.spec.ts deleted file mode 100644 index b0de5fde0a5b..000000000000 --- a/sdk/keyvault/keyvault-keys/test/internal/transformations.spec.ts +++ /dev/null @@ -1,344 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import type { - DeletedKeyBundle, - DeletedKeyItem, - KeyRotationPolicy as GeneratedKeyRotationPolicy, - KeyBundle, -} from "../../src/generated/index.js"; -import type { - DeletedKey, - KeyProperties, - KeyRotationPolicy, - KeyRotationPolicyProperties, - KeyVaultKey, -} from "../../src/keysModels.js"; -import { - getDeletedKeyFromDeletedKeyItem, - getKeyFromKeyBundle, - getKeyPropertiesFromKeyItem, - keyRotationTransformations, -} from "../../src/transformations.js"; -import { stringToUint8Array } from "../public/utils/crypto.js"; -import { describe, it, assert, expect } from "vitest"; - -describe("Transformations", () => { - const releasePolicy = { - contentType: "content type", - data: stringToUint8Array("release policy"), - }; - it("KeyBundle to KeyVaultKey", () => { - const date = new Date(); - const bundle: KeyBundle = { - key: { - kid: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - kty: "oct-HSM", - keyOps: ["encrypt", "decrypt"], - }, - attributes: { - exportable: true, - recoverableDays: 1, - recoveryLevel: "Recoverable", - enabled: true, - notBefore: date, - expires: date, - created: date, - updated: date, - hsmPlatform: "hsmPlatform", - }, - releasePolicy, - tags: { - tag_name: "tag_value", - }, - managed: false, - }; - - const expectedResult: KeyVaultKey = { - key: { - kid: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - kty: "oct-HSM", - keyOps: ["encrypt", "decrypt"], - }, - name: "transformations", - id: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - keyType: "oct-HSM", - keyOperations: ["encrypt", "decrypt"], - properties: { - id: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - name: "transformations", - vaultUrl: "https://azure_managedhsm.managedhsm.azure.net", - version: "f03e8b3d76554e8b9749994bcf72fc61", - enabled: true, - notBefore: date, - expiresOn: date, - tags: { - tag_name: "tag_value", - }, - exportable: true, - releasePolicy, - createdOn: date, - updatedOn: date, - recoveryLevel: "Recoverable", - recoverableDays: 1, - managed: false, - hsmPlatform: "hsmPlatform", - }, - }; - - const key: KeyVaultKey = getKeyFromKeyBundle(bundle); - assert.deepEqual(key, expectedResult); - }); - - it("KeyBundle to DeletedKey", () => { - const date = new Date(); - const bundle: DeletedKeyBundle = { - key: { - kid: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - kty: "oct-HSM", - keyOps: ["encrypt", "decrypt"], - }, - attributes: { - recoverableDays: 1, - recoveryLevel: "Recoverable", - enabled: true, - notBefore: date, - expires: date, - created: date, - updated: date, - exportable: false, - hsmPlatform: "hsmPlatform", - }, - tags: { - tag_name: "tag_value", - }, - managed: false, - recoveryId: "recovery-id", - releasePolicy, - scheduledPurgeDate: date, - deletedDate: date, - }; - - const expectedResult: DeletedKey = { - key: { - kid: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - kty: "oct-HSM", - keyOps: ["encrypt", "decrypt"], - }, - name: "transformations", - id: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - keyType: "oct-HSM", - keyOperations: ["encrypt", "decrypt"], - properties: { - id: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - name: "transformations", - vaultUrl: "https://azure_managedhsm.managedhsm.azure.net", - version: "f03e8b3d76554e8b9749994bcf72fc61", - enabled: true, - notBefore: date, - expiresOn: date, - tags: { - tag_name: "tag_value", - }, - releasePolicy, - exportable: false, - createdOn: date, - updatedOn: date, - recoveryLevel: "Recoverable", - recoverableDays: 1, - managed: false, - recoveryId: "recovery-id", - scheduledPurgeDate: date, - deletedOn: date, - hsmPlatform: "hsmPlatform", - }, - }; - - const key: DeletedKey = getKeyFromKeyBundle(bundle); - assert.deepEqual(key, expectedResult); - }); - - it("DeletedKeyItem to DeletedKey", () => { - const date = new Date(); - const item: DeletedKeyItem = { - kid: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - attributes: { - recoverableDays: 1, - recoveryLevel: "Recoverable", - enabled: true, - notBefore: date, - expires: date, - created: date, - updated: date, - hsmPlatform: "hsmPlatform", - }, - tags: { - tag_name: "tag_value", - }, - managed: false, - recoveryId: "recovery-id", - scheduledPurgeDate: date, - deletedDate: date, - }; - - const expectedResult: DeletedKey = { - key: { - kid: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - }, - name: "transformations", - id: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - properties: { - id: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - name: "transformations", - vaultUrl: "https://azure_managedhsm.managedhsm.azure.net", - version: "f03e8b3d76554e8b9749994bcf72fc61", - enabled: true, - notBefore: date, - expiresOn: date, - tags: { - tag_name: "tag_value", - }, - createdOn: date, - updatedOn: date, - recoveryLevel: "Recoverable", - recoverableDays: 1, - managed: false, - recoveryId: "recovery-id", - scheduledPurgeDate: date, - deletedOn: date, - hsmPlatform: "hsmPlatform", - }, - }; - - const key: DeletedKey = getDeletedKeyFromDeletedKeyItem(item); - assert.deepEqual(key, expectedResult); - }); - - it("KeyItem to KeyProperties", () => { - const date = new Date(); - const item: DeletedKeyItem = { - kid: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - attributes: { - recoverableDays: 1, - recoveryLevel: "Recoverable", - enabled: true, - notBefore: date, - expires: date, - created: date, - updated: date, - hsmPlatform: "hsmPlatform", - }, - tags: { - tag_name: "tag_value", - }, - managed: false, - recoveryId: "recovery-id", - scheduledPurgeDate: date, - deletedDate: date, - }; - - const expectedResult: KeyProperties = { - id: "https://azure_managedhsm.managedhsm.azure.net/keys/transformations/f03e8b3d76554e8b9749994bcf72fc61", - name: "transformations", - vaultUrl: "https://azure_managedhsm.managedhsm.azure.net", - version: "f03e8b3d76554e8b9749994bcf72fc61", - enabled: true, - notBefore: date, - expiresOn: date, - tags: { - tag_name: "tag_value", - }, - createdOn: date, - updatedOn: date, - recoveryLevel: "Recoverable", - recoverableDays: 1, - managed: false, - hsmPlatform: "hsmPlatform", - }; - - const key: KeyProperties = getKeyPropertiesFromKeyItem(item); - assert.deepEqual(key, expectedResult); - }); - - describe("keyRotationTransformations", () => { - it("converts generated to public", () => { - const date = new Date(); - const generated: GeneratedKeyRotationPolicy = { - attributes: { - created: date, - expiryTime: "P30D", - updated: date, - }, - id: "policy-id", - lifetimeActions: [ - { - action: { type: "Rotate" }, - trigger: { timeAfterCreate: "P90D", timeBeforeExpiry: "P90D" }, - }, - { - action: { type: "Notify" }, - trigger: { timeAfterCreate: "P90D", timeBeforeExpiry: "P90D" }, - }, - ], - }; - - const expected: KeyRotationPolicy = { - createdOn: date, - expiresIn: "P30D", - updatedOn: date, - id: "policy-id", - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P90D", - timeBeforeExpiry: "P90D", - }, - { - action: "Notify", - timeAfterCreate: "P90D", - timeBeforeExpiry: "P90D", - }, - ], - }; - - assert.deepEqual(keyRotationTransformations.generatedToPublic(generated), expected); - }); - - it("converts properties to generated", () => { - const publicPolicy: KeyRotationPolicyProperties = { - expiresIn: "P30D", - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P90D", - timeBeforeExpiry: "P90D", - }, - { - action: "Notify", - timeAfterCreate: "P90D", - timeBeforeExpiry: "P90D", - }, - ], - }; - - const expected: GeneratedKeyRotationPolicy = { - attributes: { - expiryTime: "P30D", - }, - lifetimeActions: [ - { - action: { type: "Rotate" }, - trigger: { timeAfterCreate: "P90D", timeBeforeExpiry: "P90D" }, - }, - { - action: { type: "Notify" }, - trigger: { timeAfterCreate: "P90D", timeBeforeExpiry: "P90D" }, - }, - ], - }; - - expect(keyRotationTransformations.propertiesToGenerated(publicPolicy)).to.deep.equal( - expected, - ); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/internal/userAgent.spec.ts b/sdk/keyvault/keyvault-keys/test/internal/userAgent.spec.ts deleted file mode 100644 index 9e2137f450f5..000000000000 --- a/sdk/keyvault/keyvault-keys/test/internal/userAgent.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { KeyClient } from "../../src/index.js"; -import { SDK_VERSION } from "../../src/constants.js"; -import { describe, it, assert } from "vitest"; - -describe("Keys client's user agent", () => { - it("SDK_VERSION and user-agent should match", async function () { - let userAgent: string | undefined; - const client = new KeyClient( - "https://myvault.vault.azure.net", - { - getToken: async () => { - return { - token: "my-test-token", - expiresOnTimestamp: 111111111111, - }; - }, - }, - { - httpClient: { - sendRequest: async (request) => { - userAgent = request.headers.get("user-agent") ?? request.headers.get("x-ms-useragent"); - throw new Error("only a test"); - }, - }, - }, - ); - - try { - await client.getKey("foo"); - } catch { - // no-op, we don't care about the response, only the user-agent header - } - assert.exists(userAgent, "Expected a User-Agent header to be sent"); - assert.include(userAgent!, `azsdk-js-keyvault-keys/${SDK_VERSION}`); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/crypto.hsm.spec.ts b/sdk/keyvault/keyvault-keys/test/public/crypto.hsm.spec.ts deleted file mode 100644 index bb8e8f6fc0f0..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/crypto.hsm.spec.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { isLiveMode, Recorder } from "@azure-tools/test-recorder"; -import type { ClientSecretCredential } from "@azure/identity"; -import type { NoOpCredential } from "@azure-tools/test-credential"; - -import type { KeyClient, KeyVaultKey } from "../../src/index.js"; -import { CryptographyClient } from "../../src/index.js"; -import { authenticate, envSetupForPlayback } from "./utils/testAuthentication.js"; -import { stringToUint8Array, uint8ArrayToString } from "./utils/crypto.js"; -import TestClient from "./utils/testClient.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("CryptographyClient for managed HSM (skipped if MHSM is not deployed)", () => { - let hsmClient: KeyClient; - let testClient: TestClient; - let cryptoClient: CryptographyClient; - let recorder: Recorder; - let credential: ClientSecretCredential | NoOpCredential; - let keyName: string; - let keyVaultKey: KeyVaultKey; - let keySuffix: string; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - - if (!authentication.hsmClient) { - // Managed HSM is not deployed for this run due to service resource restrictions so we skip these tests. - // This is only necessary while Managed HSM is in preview. - ctx.skip(); - } - - hsmClient = authentication.hsmClient; - testClient = new TestClient(authentication.hsmClient); - credential = authentication.credential; - keySuffix = authentication.keySuffix; - keyName = testClient.formatName("cryptography-client-test" + keySuffix); - }); - - afterEach(async function () { - await recorder.stop(); - }); - - describe("with AES crypto algorithms", async function () { - it("encrypts and decrypts using AES-GCM", async function (ctx) { - keyVaultKey = await hsmClient.createKey(keyName, "AES", { keySize: 256 }); - cryptoClient = new CryptographyClient( - keyVaultKey.id!, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: !isLiveMode() }), - ); - const text = ctx.task.name; - const encryptResult = await cryptoClient.encrypt({ - algorithm: "A256GCM", - plaintext: stringToUint8Array(text), - }); - assert.exists(encryptResult.iv); - assert.exists(encryptResult.authenticationTag); - - const decryptResult = await cryptoClient.decrypt({ - algorithm: "A256GCM", - ciphertext: encryptResult.result!, - iv: encryptResult.iv!, - authenticationTag: encryptResult.authenticationTag!, - }); - assert.equal(text, uint8ArrayToString(decryptResult.result)); - await testClient?.flushKey(keyName); - }); - - it("encrypts and decrypts using AES-CBC", async function (ctx) { - keyVaultKey = await hsmClient.createKey(keyName, "AES", { keySize: 256 }); - cryptoClient = new CryptographyClient( - keyVaultKey.id!, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: !isLiveMode() }), - ); - const text = ctx.task.name; - // We are using a predictable IV to support our recorded tests; however, you should use a cryptographically secure IV or omit it and - // let the client library generate it for you. - const iv = stringToUint8Array("xxxxxxxxxxxxxxxx"); - const encryptResult = await cryptoClient.encrypt({ - algorithm: "A256CBCPAD", - plaintext: stringToUint8Array(text), - iv, - }); - - const decryptResult = await cryptoClient.decrypt({ - algorithm: "A256CBCPAD", - ciphertext: encryptResult.result!, - iv, - }); - assert.equal(uint8ArrayToString(decryptResult.result), text); - await testClient?.flushKey(keyName); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/identifier.spec.ts b/sdk/keyvault/keyvault-keys/test/public/identifier.spec.ts deleted file mode 100644 index dcad51021106..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/identifier.spec.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { parseKeyVaultKeyIdentifier } from "../../src/identifier.js"; -import { describe, it, assert } from "vitest"; - -describe("Key Vault Keys Identifier", () => { - it("It should work with a URI of a key before it gets a version", async function () { - const uri = "https://keyvault-name.vault.azure.net/keys/key-name/pending"; - const identifier = parseKeyVaultKeyIdentifier(uri); - - assert.deepEqual(identifier, { - sourceId: "https://keyvault-name.vault.azure.net/keys/key-name/pending", - vaultUrl: "https://keyvault-name.vault.azure.net", - version: "pending", - name: "key-name", - }); - }); - - it("It should work with a URI of a key with a specific version", async function () { - const uri = "https://keyvault-name.vault.azure.net/keys/key-name/version"; - const identifier = parseKeyVaultKeyIdentifier(uri); - - assert.deepEqual(identifier, { - sourceId: "https://keyvault-name.vault.azure.net/keys/key-name/version", - vaultUrl: "https://keyvault-name.vault.azure.net", - version: "version", - name: "key-name", - }); - }); - - it("It should work with a deleted key recovery ID", async function () { - const uri = "https://keyvault-name.vault.azure.net/deletedkeys/deleted-key"; - const identifier = parseKeyVaultKeyIdentifier(uri); - - assert.deepEqual(identifier, { - sourceId: "https://keyvault-name.vault.azure.net/deletedkeys/deleted-key", - vaultUrl: "https://keyvault-name.vault.azure.net", - name: "deleted-key", - version: undefined, - }); - }); - - it("It should work when using a URL that contains a port", async function () { - const uri = "https://localhost:8443/keys/key-name/version"; - const identifier = parseKeyVaultKeyIdentifier(uri); - - assert.deepEqual(identifier, { - sourceId: "https://localhost:8443/keys/key-name/version", - vaultUrl: "https://localhost:8443", - version: "version", - name: "key-name", - }); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/import.spec.ts b/sdk/keyvault/keyvault-keys/test/public/import.spec.ts deleted file mode 100644 index 0f3c1ac85b3e..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/import.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { Recorder, env } from "@azure-tools/test-recorder"; - -import type { KeyClient } from "../../src/index.js"; -import { authenticate, envSetupForPlayback } from "./utils/testAuthentication.js"; -import type TestClient from "./utils/testClient.js"; -import { createRsaKey } from "./utils/crypto.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("Keys client - import keys", () => { - const prefix = `import${env.CERTIFICATE_NAME || "KeyName"}`; - let suffix: string; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - const authentication = await authenticate(recorder); - suffix = authentication.keySuffix; - client = authentication.client; - testClient = authentication.testClient; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - // The tests follow - - it("can import a key", async function (ctx) { - const jsonWebKey = createRsaKey(); - const keyName = testClient.formatName(`${prefix}-${ctx.task.name}-${suffix}`); - const key = await client.importKey(keyName, jsonWebKey); - assert.equal(key.key!.e!.toString(), jsonWebKey.e!.toString()); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/keyClient.hsm.spec.ts b/sdk/keyvault/keyvault-keys/test/public/keyClient.hsm.spec.ts deleted file mode 100644 index ac12d427fecf..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/keyClient.hsm.spec.ts +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { Recorder, env, isPlaybackMode } from "@azure-tools/test-recorder"; -import type { KeyClient } from "../../src/index.js"; -import { authenticate, envSetupForPlayback } from "./utils/testAuthentication.js"; -import TestClient from "./utils/testClient.js"; -import type { CreateOctKeyOptions } from "../../src/keysModels.js"; -import { KnownKeyExportEncryptionAlgorithm } from "../../src/keysModels.js"; -import { createRsaKey, stringToUint8Array, uint8ArrayToString } from "./utils/crypto.js"; -import { createPipelineRequest, createDefaultHttpClient } from "@azure/core-rest-pipeline"; -import { describe, it, assert, expect, beforeEach, afterEach } from "vitest"; - -import { toSupportTracing } from "@azure-tools/test-utils-vitest"; - -expect.extend({ - toSupportTracing, -}); - -describe("Keys client - create, read, update and delete operations for managed HSM", () => { - const keyPrefix = `CRUD${env.KEY_NAME || "KeyName"}`; - let keySuffix: string; - let hsmClient: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - - // These tests rely on the attestation URI inside the Release Policy, which is sanitized by the test recorder. - // Using a bodiless matcher to ignore the differences that this causes. - recorder.setMatcher("BodilessMatcher"); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - if (!authentication.hsmClient) { - // Managed HSM is not deployed for this run due to service resource restrictions so we skip these tests. - // This is only necessary while Managed HSM is in preview. - ctx.skip(); - } - - hsmClient = authentication.hsmClient; - keySuffix = authentication.keySuffix; - testClient = new TestClient(authentication.hsmClient); - }); - - afterEach(async function () { - await recorder.stop(); - }); - - it("can create an OCT key with options", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const options: CreateOctKeyOptions = { - hsm: true, - }; - const result = await hsmClient.createOctKey(keyName, options); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - assert.equal(result.keyType, "oct-HSM"); - await testClient.flushKey(keyName); - }); - - describe("getRandomBytes", () => { - it("can return the required number of bytes", async () => { - const result = await hsmClient.getRandomBytes(10); - assert.exists(result); - assert.equal(result.length, 10); - }); - - it("returns an error when bytes is out of range", async () => { - await expect(hsmClient.getRandomBytes(-1)).rejects.toThrow(); - await expect(hsmClient.getRandomBytes(0)).rejects.toThrow(); - await expect(hsmClient.getRandomBytes(129)).rejects.toThrow(); - }); - - it("supports tracing", async () => { - await expect((options: any) => hsmClient.getRandomBytes(1, options)).toSupportTracing([ - "KeyClient.getRandomBytes", - ]); - }); - }); - - describe("releaseKey", () => { - let attestation: string; - let encodedReleasePolicy: Uint8Array; - - beforeEach(async () => { - const attestationUri = env.AZURE_KEYVAULT_ATTESTATION_URI; - const releasePolicy = { - anyOf: [ - { - allOf: [ - { - claim: "sdk-test", - equals: "true", - }, - ], - authority: attestationUri, - }, - ], - version: "1.0", - }; - - encodedReleasePolicy = stringToUint8Array(JSON.stringify(releasePolicy)); - - if (!isPlaybackMode()) { - const client = createDefaultHttpClient(); - const response = await client.sendRequest( - createPipelineRequest({ url: `${attestationUri}/generate-test-token` }), - ); - attestation = JSON.parse(response.bodyAsText!).token; - recorder.variable("attestation", attestation); - } else { - attestation = recorder.variable("attestation", attestation); - } - }); - - it("can create an exportable key and release it", async () => { - const keyName = recorder.variable( - "exportkey", - `exportkey-${Math.floor(Math.random() * 100000)}`, - ); - const createdKey = await hsmClient.createKey(keyName, "RSA", { - exportable: true, - releasePolicy: { encodedPolicy: encodedReleasePolicy }, - keyOps: ["encrypt", "decrypt"], - }); - - assert.exists(createdKey.properties.releasePolicy?.encodedPolicy); - assert.isNotEmpty( - JSON.parse(uint8ArrayToString(createdKey.properties.releasePolicy!.encodedPolicy!)), - ); - assert.isTrue(createdKey.properties.exportable); - const releaseResult = await hsmClient.releaseKey(keyName, attestation); - - assert.exists(releaseResult.value); - }); - - it("can import an exportable key and release it", async () => { - const keyName = recorder.variable( - "importreleasekey", - `importreleasekey-${Math.floor(Math.random() * 100000)}`, - ); - - const importedKey = await hsmClient.importKey(keyName, createRsaKey(), { - exportable: true, - releasePolicy: { encodedPolicy: encodedReleasePolicy }, - }); - - assert.exists(importedKey.properties.releasePolicy?.encodedPolicy); - assert.isNotEmpty( - JSON.parse(uint8ArrayToString(importedKey.properties.releasePolicy!.encodedPolicy!)), - ); - const releaseResult = await hsmClient.releaseKey(keyName, attestation, { - version: importedKey.properties.version, - nonce: "nonce", - algorithm: KnownKeyExportEncryptionAlgorithm.RsaAesKeyWrap256, - }); - - assert.exists(releaseResult.value); - }); - - it("can update a key's release policy", async () => { - const keyName = recorder.variable( - "exportkey", - `exportkey-${Math.floor(Math.random() * 100000)}`, - ); - - const createdKey = await hsmClient.createKey(keyName, "RSA", { - exportable: true, - releasePolicy: { encodedPolicy: encodedReleasePolicy }, - keyOps: ["encrypt", "decrypt"], - }); - - const newReleasePolicy = { - anyOf: [ - { - anyOf: [ - { - claim: "sdk-test", - equals: "false", - }, - ], - authority: env.AZURE_KEYVAULT_ATTESTATION_URI, - }, - ], - version: "1.0", - }; - const updatedKey = await hsmClient.updateKeyProperties(createdKey.name, { - releasePolicy: { encodedPolicy: stringToUint8Array(JSON.stringify(newReleasePolicy)) }, - }); - - assert.exists(updatedKey.properties.releasePolicy?.encodedPolicy); - - // Release policy is sanitized by the test recorder, so we can't compare the exact value in playback mode - - if (!isPlaybackMode()) { - const decodedReleasePolicy = JSON.parse( - uint8ArrayToString(updatedKey.properties.releasePolicy!.encodedPolicy!), - ); - - assert.equal(decodedReleasePolicy.anyOf[0].anyOf[0].equals, "false"); - } - }); - - it("errors when key is exportable without a release policy", async () => { - const keyName = recorder.variable( - "exportablenopolicy", - `exportablenopolicy-${Math.floor(Math.random() * 100000)}`, - ); - await expect(hsmClient.createRsaKey(keyName, { exportable: true })).rejects.toThrow( - /exportable/i, - ); - }); - - it("errors when a key has a release policy but is not exportable", async () => { - const keyName = recorder.variable( - "policynonexportable", - `policynonexportable-${Math.floor(Math.random() * 100000)}`, - ); - await expect( - hsmClient.createRsaKey(keyName, { - releasePolicy: { encodedPolicy: encodedReleasePolicy }, - }), - ).rejects.toThrow(/exportable/i); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/keyClient.spec.ts b/sdk/keyvault/keyvault-keys/test/public/keyClient.spec.ts deleted file mode 100644 index 4c48cb71987e..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/keyClient.spec.ts +++ /dev/null @@ -1,591 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { Recorder, env, isPlaybackMode } from "@azure-tools/test-recorder"; -import { createDefaultHttpClient, createPipelineRequest } from "@azure/core-rest-pipeline"; - -import type { - CreateEcKeyOptions, - GetKeyOptions, - KeyClient, - UpdateKeyPropertiesOptions, -} from "../../src/index.js"; -import { testPollerProperties } from "./utils/recorderUtils.js"; -import { authenticate, envSetupForPlayback } from "./utils/testAuthentication.js"; -import type TestClient from "./utils/testClient.js"; -import { stringToUint8Array, uint8ArrayToString } from "./utils/crypto.js"; -import { describe, it, assert, expect, beforeEach, afterEach } from "vitest"; - -import { toSupportTracing } from "@azure-tools/test-utils-vitest"; - -expect.extend({ - toSupportTracing: toSupportTracing, -}); - -describe("Keys client - create, read, update and delete operations", () => { - const keyPrefix = `CRUD${env.KEY_NAME || "KeyName"}`; - let keySuffix: string; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - - beforeEach(async (ctx) => { - recorder = new Recorder(ctx); - - // These tests rely on the attestation URI inside the Release Policy, which is sanitized by the test recorder. - // Using a bodiless matcher to ignore the differences that this causes. - await recorder.start(envSetupForPlayback); - await recorder.setMatcher("BodilessMatcher"); - - const authentication = await authenticate(recorder); - keySuffix = authentication.keySuffix; - client = authentication.client; - testClient = authentication.testClient; - }); - - afterEach(async () => { - await recorder.stop(); - }); - - // The tests follow - - it("can create a key while giving a manual type", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const result = await client.createKey(keyName, "RSA"); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("cannot create a key with an empty name", async () => { - const keyName = ""; - try { - await client.createKey(keyName, "RSA"); - assert.fail("Expected an error"); - } catch (e) { - // Catch expected error - } - }); - - it("can create a RSA key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const result = await client.createRsaKey(keyName); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can create a RSA key with size", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const options = { - keySize: 2048, - }; - const result = await client.createRsaKey(keyName, options); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can create a RSA key with public exponent", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const options = { - publicExponent: 3, - }; - const result = await client.createRsaKey(keyName, options); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can create an EC key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const result = await client.createEcKey(keyName); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can create an EC key with curve", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const options: CreateEcKeyOptions = { - curve: "P-256", - }; - const result = await client.createEcKey(keyName, options); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can create a disabled key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const options = { - enabled: false, - }; - const result = await client.createRsaKey(keyName, options); - assert.equal(result.properties.enabled, false, "Unexpected enabled value from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can create a key with notBefore", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const date = new Date("2019-01-01"); - const notBefore = new Date(date.getTime() + 5000); // 5 seconds later - notBefore.setMilliseconds(0); - - const options = { notBefore }; - const result = await client.createRsaKey(keyName, options); - - assert.equal( - result!.properties.notBefore!.getTime(), - notBefore.getTime(), - "Unexpected notBefore value from createKey().", - ); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can create a key with expires", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const date = new Date("2019-01-01"); - const expiresOn = new Date(date.getTime() + 5000); // 5 seconds later - expiresOn.setMilliseconds(0); - - const options = { expiresOn }; - const result = await client.createRsaKey(keyName, options); - - assert.equal( - result!.properties.expiresOn!.getTime(), - expiresOn.getTime(), - "Unexpected expires value from createKey().", - ); - assert.equal(result.name, keyName, "Unexpected key name in result from createKey()."); - await testClient.flushKey(keyName); - }); - - it("can update key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const { version } = (await client.createRsaKey(keyName)).properties; - const options: UpdateKeyPropertiesOptions = { enabled: false }; - const result = await client.updateKeyProperties(keyName, version!, options); - assert.equal(result.properties.enabled, false, "Unexpected enabled value from updateKey()."); - }); - - it("can update a key's properties without specifying a version", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createRsaKey(keyName); - const options: UpdateKeyPropertiesOptions = { enabled: false }; - const result = await client.updateKeyProperties(keyName, options); - assert.equal(result.properties.enabled, false, "Unexpected enabled value from updateKey()."); - }); - - it("can update a key's properties for a specific version", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const { version: previousVersion } = (await client.createRsaKey(keyName)).properties; - const { version: newVersion } = (await client.createRsaKey(keyName)).properties; - assert.notEqual(previousVersion, newVersion); - - const options: UpdateKeyPropertiesOptions = { enabled: false }; - const result = await client.updateKeyProperties(keyName, previousVersion!, options); - assert.equal(result.properties.enabled, false, "Unexpected enabled value from updateKey()."); - }); - - it("can update a disabled key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const createOptions = { - enabled: false, - }; - const { version } = (await client.createRsaKey(keyName, createOptions)).properties; - const expiresOn = new Date("2019-01-01"); - expiresOn.setMilliseconds(0); - const updateOptions: UpdateKeyPropertiesOptions = { expiresOn }; - const result = await client.updateKeyProperties(keyName, version || "", updateOptions); - assert.equal( - result!.properties.expiresOn!.getTime(), - expiresOn.getTime(), - "Unexpected expires value after attempting to update a disabled key", - ); - await testClient.flushKey(keyName); - }); - - it("can delete a key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const poller = await client.beginDeleteKey(keyName, testPollerProperties); - await poller.pollUntilDone(); - - try { - await client.getKey(keyName); - throw Error("Expecting an error but not catching one."); - } catch (e: any) { - if (e.name === "RestError") { - assert.equal(e.code, "KeyNotFound"); - assert.equal(e.statusCode, 404); - } else { - throw e; - } - } - await testClient.purgeKey(keyName); - }); - - it("delete nonexisting key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - try { - await client.getKey(keyName); - throw Error("Expecting an error but not catching one."); - } catch (e: any) { - if (e.name === "RestError") { - assert.equal(e.code, "KeyNotFound"); - assert.equal(e.statusCode, 404); - } else { - throw e; - } - } - }); - - it("can get a key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const getResult = await client.getKey(keyName); - assert.equal(getResult.name, keyName, "Unexpected key name in result from getKey()."); - await testClient.flushKey(keyName); - }); - - it("can get a specific version of a key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const { version } = (await client.createKey(keyName, "RSA")).properties; - const options: GetKeyOptions = { version }; - const getResult = await client.getKey(keyName, options); - assert.equal( - getResult.properties.version, - version, - "Unexpected key name in result from getKey().", - ); - await testClient.flushKey(keyName); - }); - - it("can get a deleted key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const poller = await client.beginDeleteKey(keyName, testPollerProperties); - assert.equal( - poller.getResult()!.name, - keyName, - "Unexpected key name in result from beginDeleteKey().", - ); - await poller.pollUntilDone(); - let getResult = poller.getResult(); - assert.equal( - getResult!.name, - keyName, - "Unexpected key name in result from poller.getResult().", - ); - getResult = await client.getDeletedKey(keyName); - assert.equal(getResult!.name, keyName, "Unexpected key name in result from getDeletedKey()."); - await testClient.purgeKey(keyName); - }); - - it("can't get a deleted key that doesn't exist", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - let error; - try { - const poller = await client.beginDeleteKey(keyName, testPollerProperties); - await poller.pollUntilDone(); - throw Error("Expecting an error but not catching one."); - } catch (e: any) { - error = e; - } - assert.equal(error.code, "KeyNotFound"); - assert.equal(error.statusCode, 404); - }); - - it("can purge a deleted key", async (ctx) => { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const poller = await client.beginDeleteKey(keyName, testPollerProperties); - await poller.pollUntilDone(); - await client.purgeDeletedKey(keyName); - }); - - describe("key rotation", () => { - it("rotateKey supports rotating a key", async () => { - const keyName = recorder.variable( - "keyrotate", - `keyrotate-${Math.floor(Math.random() * 1000)}`, - ); - const key = await client.createKey(keyName, "RSA"); - const rotatedKey = await client.rotateKey(keyName); - - // A new version is created, and the key material is rotated (RSA key, check n and e). - assert.notEqual(rotatedKey.id, key.id); - assert.notEqual(rotatedKey.properties.version, key.properties.version); - assert.notEqual(rotatedKey.key?.n, key.key?.n); - }); - - it("updateKeyRotationPolicy supports creating a new rotation policy and fetching it", async () => { - const keyName = recorder.variable( - "keyrotationpolicy", - `keyrotationpolicy-${Math.floor(Math.random() * 1000)}`, - ); - const key = await client.createKey(keyName, "RSA"); - - const rotationPolicy = await client.updateKeyRotationPolicy(key.name, { - expiresIn: "P90D", - lifetimeActions: [ - { - action: "Rotate", - timeBeforeExpiry: "P30D", - }, - ], - }); - - const fetchedPolicy = await client.getKeyRotationPolicy(keyName); - - assert.deepEqual(fetchedPolicy, rotationPolicy); - }); - - it("updateKeyRotationPolicy supports updating an existing policy", async () => { - const keyName = recorder.variable( - "keyrotationpolicy", - `keyrotationpolicy-${Math.floor(Math.random() * 1000)}`, - ); - const key = await client.createKey(keyName, "RSA"); - - // Create a policy which we will override later. - await client.updateKeyRotationPolicy(key.name, { - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P2M", - }, - ], - }); - - const updatedPolicy = await client.updateKeyRotationPolicy(key.name, { - expiresIn: "P90D", - lifetimeActions: [ - { - action: "Notify", - timeBeforeExpiry: "P30D", - }, - ], - }); - - assert.deepEqual(updatedPolicy, { - id: updatedPolicy.id, - createdOn: updatedPolicy.createdOn, - updatedOn: updatedPolicy.updatedOn, - expiresIn: "P90D", - lifetimeActions: [ - { - timeAfterCreate: undefined, - action: "Notify", - timeBeforeExpiry: "P30D", - }, - ], - }); - }); - - it("throws when attempting to fetch a policy of a non-existent key", async () => { - const keyName = recorder.variable( - "nonexistentkey", - `nonexistentkey-${Math.floor(Math.random() * 1000)}`, - ); - await expect(client.getKeyRotationPolicy(keyName)).rejects.toThrow(); - }); - - it("supports tracing", async () => { - const keyName = recorder.variable( - "rotationpolicytracing", - `rotationpolicytracing-${Math.floor(Math.random() * 1000)}`, - ); - const key = await client.createKey(keyName, "RSA"); - - await expect(async (options: any) => { - await client.updateKeyRotationPolicy( - key.name, - { - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P2M", - }, - ], - }, - options, - ); - await client.getKeyRotationPolicy(key.name, options); - }).toSupportTracing(["KeyClient.updateKeyRotationPolicy", "KeyClient.getKeyRotationPolicy"]); - }); - }); - - describe("releaseKey", () => { - let attestation: string; - let encodedReleasePolicy: Uint8Array; - - beforeEach(async () => { - const attestationUri = env.AZURE_KEYVAULT_ATTESTATION_URI; - const releasePolicy = { - anyOf: [ - { - allOf: [ - { - claim: "sdk-test", - equals: "true", - }, - ], - authority: attestationUri, - }, - ], - version: "1.0.0", - }; - encodedReleasePolicy = stringToUint8Array(JSON.stringify(releasePolicy)); - - if (!isPlaybackMode()) { - const attestationTokenClient = createDefaultHttpClient(); - const response = await attestationTokenClient.sendRequest( - createPipelineRequest({ url: `${attestationUri}/generate-test-token` }), - ); - attestation = JSON.parse(response.bodyAsText!).token; - recorder.variable("attestation", attestation); - } else { - attestation = recorder.variable("attestation", attestation); - } - }); - - it("can create an exportable key and release it", async () => { - const keyName = recorder.variable( - "exportkey", - `exportkey-${Math.floor(Math.random() * 1000)}`, - ); - const createdKey = await client.createRsaKey(keyName, { - exportable: true, - hsm: true, - releasePolicy: { encodedPolicy: encodedReleasePolicy }, - keyOps: ["encrypt", "decrypt"], - }); - - assert.exists(createdKey.properties.releasePolicy?.encodedPolicy); - assert.isNotEmpty( - JSON.parse(uint8ArrayToString(createdKey.properties.releasePolicy!.encodedPolicy!)), - ); - assert.isTrue(createdKey.properties.exportable); - const releaseResult = await client.releaseKey(keyName, attestation); - - assert.exists(releaseResult.value); - }); - - it("errors when key is exportable without a release policy", async () => { - const keyName = recorder.variable( - "exportablenopolicy", - `exportablenopolicy-${Math.floor(Math.random() * 1000)}`, - ); - await expect(client.createRsaKey(keyName, { exportable: true, hsm: true })).rejects.toThrow( - /exportable/i, - ); - }); - - it("errors when a key has a release policy but is not exportable", async () => { - const keyName = recorder.variable( - "policynonexportable", - `policynonexportable-${Math.floor(Math.random() * 1000)}`, - ); - await expect( - client.createRsaKey(keyName, { - hsm: true, - releasePolicy: { encodedPolicy: encodedReleasePolicy }, - }), - ).rejects.toThrow(/exportable/i); - }); - - it("errors when updating an immutable release policy", async () => { - const keyName = recorder.variable( - "immutablerelease", - `immutablerelease-${Math.floor(Math.random() * 1000)}`, - ); - const createdKey = await client.createRsaKey(keyName, { - exportable: true, - hsm: true, - releasePolicy: { - encodedPolicy: encodedReleasePolicy, - immutable: true, - }, - keyOps: ["encrypt", "decrypt"], - }); - - const newReleasePolicy = { - anyOf: [ - { - anyOf: [ - { - claim: "sdk-test", - equals: "false", - }, - ], - authority: env.AZURE_KEYVAULT_ATTESTATION_URI, - }, - ], - version: "1.0", - }; - - await expect( - client.updateKeyProperties(createdKey.name, { - releasePolicy: { - encodedPolicy: stringToUint8Array(JSON.stringify(newReleasePolicy)), - immutable: true, - }, - }), - ).rejects.toThrow(/Immutable Key Release/); - }); - }); - - describe("tracing", () => { - it("traces through the basic operations", async () => { - const keyName = recorder.variable( - "keyclienttracing", - `keyclienttracing-${Math.floor(Math.random() * 1000)}`, - ); - - await expect(async (options: any) => { - await client.createKey(keyName, "RSA", options); - await client.getKey(keyName, options); - await client.backupKey(keyName, options); - // TODO: figure out tracing strategy for list operations - // await client.listDeletedKeys(options).next(); - // await client.listPropertiesOfKeys(options).next(); - // await client.listPropertiesOfKeyVersions(keyName, options).next(); - await client.updateKeyProperties(keyName, options); - }).toSupportTracing([ - "KeyClient.createKey", - "KeyClient.getKey", - "KeyClient.backupKey", - "KeyClient.updateKeyProperties", - ]); - }); - - it("traces through key rotation operations", async () => { - const keyName = recorder.variable( - "keyrotationtracing", - `keyrotationtracing-${Math.floor(Math.random() * 1000)}`, - ); - await client.createKey(keyName, "RSA"); - await expect(async (options: any) => { - await client.updateKeyRotationPolicy( - keyName, - { - lifetimeActions: [ - { - action: "Rotate", - timeAfterCreate: "P50D", - }, - ], - }, - options, - ); - await client.getKeyRotationPolicy(keyName, options); - }).toSupportTracing(["KeyClient.updateKeyRotationPolicy", "KeyClient.getKeyRotationPolicy"]); - }); - - it("traces through secure key release", async () => { - await expect(async (options: any) => { - try { - await client.releaseKey("foo", "anything", options); - } catch { - // ignore errors, as it's not worth setting up the secure key release policy for this test. - } - }).toSupportTracing(["KeyClient.releaseKey"]); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/list.spec.ts b/sdk/keyvault/keyvault-keys/test/public/list.spec.ts deleted file mode 100644 index 4a0277f3bf48..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/list.spec.ts +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { Recorder, env, isRecordMode } from "@azure-tools/test-recorder"; - -import type { KeyClient } from "../../src/index.js"; -import { testPollerProperties } from "./utils/recorderUtils.js"; -import { authenticate, envSetupForPlayback } from "./utils/testAuthentication.js"; -import type TestClient from "./utils/testClient.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("Keys client - list keys in various ways", () => { - const keyPrefix = `list${env.KEY_NAME || "KeyName"}`; - let keySuffix: string; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - keySuffix = authentication.keySuffix; - client = authentication.client; - testClient = authentication.testClient; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - // The tests follow - - // Use this while recording to make sure the target keyvault is clean. - // The next tests will produce a more consistent output. - // This test is only useful while developing locally. - it("can purge all keys", async function (ctx): Promise { - // WARNING: When TEST_MODE equals "record", all of the keys in the indicated KEYVAULT_URI will be deleted as part of this test. - if (!isRecordMode()) { - return ctx.skip(); - } - for await (const properties of client.listPropertiesOfKeys()) { - try { - await testClient.flushKey(properties.name); - } catch { - // Nothing to do here. - } - } - for await (const deletedKey of client.listDeletedKeys()) { - try { - await testClient.purgeKey(deletedKey.name); - } catch { - // Nothing to do here. - } - } - }); - - it("can get the versions of a key", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const expectedVersions = 2; - - for (let i = 0; i < expectedVersions; ++i) { - await client.createKey(keyName, "RSA"); - } - - let totalVersions = 0; - for await (const version of client.listPropertiesOfKeyVersions(keyName)) { - assert.equal( - version.name, - keyName, - "Unexpected key name in result from listPropertiesOfKeyVersions().", - ); - totalVersions += 1; - } - assert.equal(totalVersions, expectedVersions, `Unexpected total versions for key ${keyName}`); - await testClient.flushKey(keyName); - }); - - it("can get the versions of a key (paged)", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - - const expectedVersions = 2; - for (let i = 0; i < expectedVersions; ++i) { - await client.createKey(keyName, "RSA"); - } - - let totalVersions = 0; - for await (const page of client - .listPropertiesOfKeyVersions(keyName) - .byPage({ maxPageSize: 1 })) { - assert.isAtMost(page.length, 1); - for (const version of page) { - assert.equal( - version.name, - keyName, - "Unexpected key name in result from listPropertiesOfKeyVersions().", - ); - totalVersions += 1; - } - } - assert.equal(totalVersions, expectedVersions, `Unexpected total versions for key ${keyName}`); - await testClient.flushKey(keyName); - }); - - it("list 0 versions of a non-existing key", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - let totalVersions = 0; - for await (const version of client.listPropertiesOfKeyVersions(keyName)) { - assert.equal( - version.name, - keyName, - "Unexpected key name in result from listPropertiesOfKeyVersions().", - ); - totalVersions += 1; - } - assert.equal(totalVersions, 0, `Unexpected total versions for key ${keyName}`); - }); - - it("list 0 versions of a non-existing key (paged)", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - let totalVersions = 0; - for await (const page of client.listPropertiesOfKeyVersions(keyName).byPage()) { - for (const version of page) { - assert.equal( - version.name, - keyName, - "Unexpected key name in result from listPropertiesOfKeyVersions().", - ); - totalVersions += 1; - } - } - assert.equal(totalVersions, 0, `Unexpected total versions for key ${keyName}`); - }); - - it("can get several inserted keys", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyNames = [`${keyName}-0`, `${keyName}-1`]; - for (const name of keyNames) { - await client.createKey(name, "RSA"); - } - - let found = 0; - for await (const properties of client.listPropertiesOfKeys()) { - // The vault might contain more keys than the ones we inserted. - if (!keyNames.includes(properties.name)) continue; - found += 1; - } - - assert.equal(found, 2, "Unexpected number of keys found by getKeys."); - - for (const name of keyNames) { - await testClient.flushKey(name); - } - }); - - it("can get several inserted keys (paged)", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyNames = [`${keyName}-0`, `${keyName}-1`]; - for (const name of keyNames) { - await client.createKey(name, "RSA"); - } - - let found = 0; - - for await (const page of client.listPropertiesOfKeys().byPage({ maxPageSize: 1 })) { - assert.isAtMost(page.length, 1); - for (const properties of page) { - // The vault might contain more keys than the ones we inserted. - if (!keyNames.includes(properties.name)) continue; - found += 1; - } - } - - assert.equal(found, 2, "Unexpected number of keys found by getKeys."); - - for (const name of keyNames) { - await testClient.flushKey(name); - } - }); - - it("list deleted keys", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyNames = [`${keyName}-0`, `${keyName}-1`]; - for (const name of keyNames) { - await client.createKey(name, "RSA"); - } - for (const name of keyNames) { - const poller = await client.beginDeleteKey(name, testPollerProperties); - await poller.pollUntilDone(); - } - - let found = 0; - for await (const deletedKey of client.listDeletedKeys()) { - // The vault might contain more keys than the ones we inserted. - if (!keyNames.includes(deletedKey.name)) continue; - found += 1; - } - - assert.equal(found, 2, "Unexpected number of keys found by listDeletedKeys."); - - for (const name of keyNames) { - await testClient.purgeKey(name); - } - }); - - it("list deleted keys (paged)", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyNames = [`${keyName}-0`, `${keyName}-1`]; - for (const name of keyNames) { - await client.createKey(name, "RSA"); - } - for (const name of keyNames) { - const poller = await client.beginDeleteKey(name, testPollerProperties); - await poller.pollUntilDone(); - } - - let found = 0; - for await (const page of client.listDeletedKeys().byPage({ maxPageSize: 1 })) { - assert.isAtMost(page.length, 1); - for (const deletedKey of page) { - // The vault might contain more keys than the ones we inserted. - if (!keyNames.includes(deletedKey.name)) continue; - found += 1; - } - } - - assert.equal(found, 2, "Unexpected number of keys found by listDeletedKeys."); - - for (const name of keyNames) { - await testClient.purgeKey(name); - } - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/lro.delete.spec.ts b/sdk/keyvault/keyvault-keys/test/public/lro.delete.spec.ts deleted file mode 100644 index f121914cf35e..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/lro.delete.spec.ts +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { Recorder, env } from "@azure-tools/test-recorder"; - -import type { DeletedKey, KeyClient } from "../../src/index.js"; -import { testPollerProperties } from "./utils/recorderUtils.js"; -import { authenticate, envSetupForPlayback } from "./utils/testAuthentication.js"; -import type TestClient from "./utils/testClient.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("Keys client - Long Running Operations - delete", () => { - const keyPrefix = `lroDelete${env.CERTIFICATE_NAME || "KeyName"}`; - let keySuffix: string; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - keySuffix = authentication.keySuffix; - client = authentication.client; - testClient = authentication.testClient; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - // The tests follow - - it("can wait until a key is deleted", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const poller = await client.beginDeleteKey(keyName, testPollerProperties); - assert.ok(poller.getOperationState().isStarted); - - // The pending deleted can be obtained this way: - assert.equal(poller.getOperationState().result!.name, keyName); - - const deletedKey: DeletedKey = await poller.pollUntilDone(); - assert.equal(deletedKey.name, keyName); - assert.ok(poller.getOperationState().isCompleted); - - // The final key can also be obtained this way: - assert.equal(poller.getOperationState().result!.name, keyName); - - await testClient.purgeKey(keyName); - }); - - it("can resume from a stopped poller", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const poller = await client.beginDeleteKey(keyName, testPollerProperties); - assert.ok(poller.getOperationState().isStarted); - - poller.pollUntilDone().catch((e) => { - assert.ok(e.name === "PollerStoppedError"); - assert.equal(e.name, "PollerStoppedError"); - assert.equal(e.message, "This poller is already stopped"); - }); - - await poller.poll(); // Making sure it has some data - - poller.stopPolling(); - assert.ok(poller.isStopped()); - assert.ok(!poller.getOperationState().isCompleted); - - const serialized = poller.toString(); - - const resumePoller = await client.beginDeleteKey(keyName, { - resumeFrom: serialized, - ...testPollerProperties, - }); - - assert.ok(resumePoller.getOperationState().isStarted); - const deletedKey: DeletedKey = await resumePoller.pollUntilDone(); - assert.equal(deletedKey.name, keyName); - assert.ok(resumePoller.getOperationState().isCompleted); - - await testClient.purgeKey(keyName); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/lro.recoverDelete.spec.ts b/sdk/keyvault/keyvault-keys/test/public/lro.recoverDelete.spec.ts deleted file mode 100644 index ed2aecf06bfa..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/lro.recoverDelete.spec.ts +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { Recorder, env } from "@azure-tools/test-recorder"; - -import type { DeletedKey, KeyClient } from "../../src/index.js"; -import { testPollerProperties } from "./utils/recorderUtils.js"; -import { authenticate, envSetupForPlayback } from "./utils/testAuthentication.js"; -import type TestClient from "./utils/testClient.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("Keys client - Long Running Operations - recoverDelete", () => { - const keyPrefix = `lroRecoverDelete${env.CERTIFICATE_NAME || "KeyName"}`; - let keySuffix: string; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - keySuffix = authentication.keySuffix; - client = authentication.client; - testClient = authentication.testClient; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - // The tests follow - - it("can wait until a key is recovered", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - - const deletePoller = await client.beginDeleteKey(keyName, testPollerProperties); - await deletePoller.pollUntilDone(); - - const poller = await client.beginRecoverDeletedKey(keyName, testPollerProperties); - assert.ok(poller.getOperationState().isStarted); - - // The pending key can be obtained this way: - assert.equal(poller.getOperationState().result!.name, keyName); - - const deletedKey: DeletedKey = await poller.pollUntilDone(); - assert.equal(deletedKey.name, keyName); - assert.ok(poller.getOperationState().isCompleted); - - // The final key can also be obtained this way: - assert.equal(poller.getOperationState().result!.name, keyName); - - await testClient.flushKey(keyName); - }); - - it("can resume from a stopped poller", async function (ctx) { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - await client.createKey(keyName, "RSA"); - const deletePoller = await client.beginDeleteKey(keyName, testPollerProperties); - await deletePoller.pollUntilDone(); - - const poller = await client.beginRecoverDeletedKey(keyName, testPollerProperties); - assert.ok(poller.getOperationState().isStarted); - - poller.pollUntilDone().catch((e) => { - assert.ok(e.name === "PollerStoppedError"); - assert.equal(e.name, "PollerStoppedError"); - assert.equal(e.message, "This poller is already stopped"); - }); - - await poller.poll(); // Making sure it has some data - - poller.stopPolling(); - assert.ok(poller.isStopped()); - assert.ok(!poller.getOperationState().isCompleted); - - const serialized = poller.toString(); - - const resumePoller = await client.beginRecoverDeletedKey(keyName, { - resumeFrom: serialized, - ...testPollerProperties, - }); - - assert.ok(poller.getOperationState().isStarted); - const deletedKey: DeletedKey = await resumePoller.pollUntilDone(); - assert.equal(deletedKey.name, keyName); - assert.ok(resumePoller.getOperationState().isCompleted); - - await testClient.flushKey(keyName); - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/node/crypto.spec.ts b/sdk/keyvault/keyvault-keys/test/public/node/crypto.spec.ts deleted file mode 100644 index 281fe9b19b5d..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/node/crypto.spec.ts +++ /dev/null @@ -1,384 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createHash } from "node:crypto"; -import { Recorder, env, isLiveMode } from "@azure-tools/test-recorder"; -import type { ClientSecretCredential } from "@azure/identity"; - -import type { KeyClient, KeyVaultKey } from "../../../src/index.js"; -import { CryptographyClient } from "../../../src/index.js"; -import { authenticate, envSetupForPlayback } from "../utils/testAuthentication.js"; -import type TestClient from "../utils/testClient.js"; -import { stringToUint8Array, uint8ArrayToString } from "./../utils/crypto.js"; -import { RsaCryptographyProvider } from "../../../src/cryptography/rsaCryptographyProvider.js"; -import { describe, it, assert, expect, beforeEach, afterEach } from "vitest"; - -import { toSupportTracing } from "@azure-tools/test-utils-vitest"; - -expect.extend({ - toSupportTracing: toSupportTracing, -}); - -describe("CryptographyClient (all decrypts happen remotely)", () => { - const keyPrefix = `crypto${env.KEY_NAME || "KeyName"}`; - let client: KeyClient; - let testClient: TestClient; - let cryptoClient: CryptographyClient; - let recorder: Recorder; - let credential: ClientSecretCredential; - let keyName: string; - let keyVaultKey: KeyVaultKey; - let keySuffix: string; - - describe("RSA keys", () => { - beforeEach(async (ctx) => { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - client = authentication.client; - testClient = authentication.testClient; - credential = authentication.credential; - keySuffix = authentication.keySuffix; - keyName = recorder.variable("RSA", `RSA-${Math.floor(Math.random() * 100000)}`); - keyVaultKey = await client.createKey(keyName, "RSA"); - cryptoClient = new CryptographyClient( - keyVaultKey, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: !isLiveMode() }), - ); - }); - - afterEach(async function () { - await testClient.flushKey(keyName); - await recorder.stop(); - }); - - if (isLiveMode()) { - it("encrypt & decrypt with RSA1_5", async (ctx) => { - const text = ctx.task.name; - const encryptResult = await cryptoClient.encrypt({ - algorithm: "RSA1_5", - plaintext: stringToUint8Array(text), - }); - const decryptResult = await cryptoClient.decrypt({ - algorithm: "RSA1_5", - ciphertext: encryptResult.result, - }); - const decryptedText = uint8ArrayToString(decryptResult.result); - assert.equal(text, decryptedText); - }); - - it("manually encrypt locally and decrypt remotely, both with RSA1_5", async (ctx) => { - const text = ctx.task.name; - const localProvider = new RsaCryptographyProvider(keyVaultKey.key!); - const encryptResult = await localProvider.encrypt({ - algorithm: "RSA1_5", - plaintext: Buffer.from(text), - }); - const decryptResult = await cryptoClient.decrypt({ - algorithm: "RSA1_5", - ciphertext: encryptResult.result, - }); - const decryptedText = uint8ArrayToString(decryptResult.result); - assert.equal(text, decryptedText); - }); - - it("encrypt & decrypt with RSA-OAEP", async (ctx) => { - const text = ctx.task.name; - const encryptResult = await cryptoClient.encrypt( - { - algorithm: "RSA-OAEP", - plaintext: stringToUint8Array(text), - }, - {}, - ); - const decryptResult = await cryptoClient.decrypt({ - algorithm: "RSA-OAEP", - ciphertext: encryptResult.result, - }); - const decryptedText = uint8ArrayToString(decryptResult.result); - assert.equal(text, decryptedText); - }); - - it("manually encrypt locally and decrypt remotely, both with RSA-OAEP", async (ctx) => { - const text = ctx.task.name; - const localProvider = new RsaCryptographyProvider(keyVaultKey.key!); - const encryptResult = await localProvider.encrypt({ - algorithm: "RSA-OAEP", - plaintext: Buffer.from(text), - }); - const decryptResult = await cryptoClient.decrypt({ - algorithm: "RSA-OAEP", - ciphertext: encryptResult.result, - }); - const decryptedText = uint8ArrayToString(decryptResult.result); - assert.equal(text, decryptedText); - }); - - it("the CryptographyClient can be created from a full KeyVaultKey object", async (ctx) => { - const customKeyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const customKeyVaultKey = await client.createKey(customKeyName, "RSA"); - const cryptoClientFromKey = new CryptographyClient( - customKeyVaultKey, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: !isLiveMode() }), - ); - - const text = ctx.task.name; - const encryptResult = await cryptoClientFromKey.encrypt({ - algorithm: "RSA1_5", - plaintext: stringToUint8Array(text), - }); - const decryptResult = await cryptoClientFromKey.decrypt({ - algorithm: "RSA1_5", - ciphertext: encryptResult.result, - }); - const decryptedText = uint8ArrayToString(decryptResult.result); - assert.equal(text, decryptedText); - }); - - it("wrap and unwrap with rsa1_5", async (ctx) => { - if (!isLiveMode()) { - console.log( - "Wrapping and unwrapping don't cause a repeatable pattern, so these tests can only run in playback mode", - ); - ctx.skip(); - } - const text = "arepa"; - const wrapped = await cryptoClient.wrapKey("RSA1_5", stringToUint8Array(text)); - const unwrappedResult = await cryptoClient.unwrapKey("RSA1_5", wrapped.result); - const unwrappedText = uint8ArrayToString(unwrappedResult.result); - assert.equal(text, unwrappedText); - assert.equal("RSA1_5", unwrappedResult.algorithm); - }); - - it("wrap and unwrap with RSA-OAEP", async (ctx) => { - if (!isLiveMode()) { - console.log( - "Wrapping and unwrapping don't cause a repeatable pattern, so these tests can only run in playback mode", - ); - ctx.skip(); - } - const text = ctx.task.name; - const wrapped = await cryptoClient.wrapKey("RSA-OAEP", stringToUint8Array(text)); - const unwrappedResult = await cryptoClient.unwrapKey("RSA-OAEP", wrapped.result); - const unwrappedText = uint8ArrayToString(unwrappedResult.result); - assert.equal(text, unwrappedText); - assert.equal("RSA-OAEP", unwrappedResult.algorithm); - }); - } - - it("sign and verify with RS256", async function (): Promise { - const signatureValue = Buffer.from("32 byte signature in ascii chars"); - const hash = createHash("SHA256"); - hash.update(signatureValue); - - const signature = await cryptoClient.sign("RS256", signatureValue); - const verifyResult = await cryptoClient.verify("RS256", signatureValue, signature.result); - - assert.ok(verifyResult.result); - }); - - it("sign and verify data with RS256 (local verification)", async function () { - const signatureValue = Buffer.from("32 byte signature in ascii chars"); - const signature = await cryptoClient.signData("RS256", signatureValue); - const verifyResult = await cryptoClient.verifyData("RS256", signatureValue, signature.result); - assert.ok(verifyResult.result); - }); - - describe("tracing", () => { - it("traces through remote cryptography calls", async () => { - if (isLiveMode()) { - await expect(async (options: any) => { - const encryptResult = await cryptoClient.encrypt( - { algorithm: "RSA1_5", plaintext: stringToUint8Array("Hello, world") }, - options, - ); - await cryptoClient.decrypt( - { algorithm: "RSA1_5", ciphertext: encryptResult.result }, - options, - ); - - const signResult = await cryptoClient.signData( - "RS256", - stringToUint8Array("Message"), - options, - ); - await cryptoClient.verifyData( - "RS256", - stringToUint8Array("Message"), - signResult.result, - options, - ); - }).toSupportTracing([ - "CryptographyClient.encrypt", - "CryptographyClient.decrypt", - "CryptographyClient.signData", - "CryptographyClient.verifyData", - ]); - } - }); - }); - }); - - describe("RSA-HSM keys", () => { - beforeEach(async (ctx) => { - if (isLiveMode() && env.KEYVAULT_SKU !== "premium") { - // RSA-HSM keys are only available in the premium KeyVault SKU which is not - // available in all clouds. - ctx.skip(); - } - - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - client = authentication.client; - testClient = authentication.testClient; - credential = authentication.credential; - keySuffix = authentication.keySuffix; - - keyName = recorder.variable("RSA-HSM", `RSA-HSM-${Math.floor(Math.random() * 100000)}`); - keyVaultKey = await client.createKey(keyName, "RSA-HSM"); - cryptoClient = new CryptographyClient( - keyVaultKey.id!, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: !isLiveMode() }), - ); - }); - - afterEach(async function () { - await testClient.flushKey(keyName); - await recorder?.stop(); - }); - - it("encrypt & decrypt with an RSA-HSM key and the RSA-OAEP algorithm", async (ctx) => { - if (!isLiveMode()) { - console.log("Encryption with RSA is not repeatable"); - ctx.skip(); - } - const text = ctx.task.name; - const encryptResult = await cryptoClient.encrypt("RSA-OAEP", stringToUint8Array(text)); - const decryptResult = await cryptoClient.decrypt("RSA-OAEP", encryptResult.result); - const decryptedText = uint8ArrayToString(decryptResult.result); - assert.equal(text, decryptedText); - }); - - it("encrypt & decrypt with an RSA-HSM key and the RSA1_5 algorithm", async (ctx) => { - if (!isLiveMode()) { - console.log("Encryption with RSA is not repeatable"); - ctx.skip(); - } - const text = ctx.task.name; - const encryptResult = await cryptoClient.encrypt("RSA1_5", stringToUint8Array(text)); - const decryptResult = await cryptoClient.decrypt("RSA1_5", encryptResult.result); - const decryptedText = uint8ArrayToString(decryptResult.result); - assert.equal(text, decryptedText); - }); - - it("wrap and unwrap with RSA-OAEP on a RSA-HSM key", async (ctx) => { - if (!isLiveMode()) { - console.log( - "Wrapping and unwrapping don't cause a repeatable pattern, so this test can only run live", - ); - ctx.skip(); - } - const text = ctx.task.name; - const wrapped = await cryptoClient.wrapKey("RSA-OAEP", stringToUint8Array(text)); - const unwrappedResult = await cryptoClient.unwrapKey("RSA-OAEP", wrapped.result); - const unwrappedText = uint8ArrayToString(unwrappedResult.result); - assert.equal(text, unwrappedText); - }); - - it("wrap and unwrap with RSA1_5 on a RSA-HSM key", async (ctx) => { - if (!isLiveMode()) { - console.log( - "Wrapping and unwrapping don't cause a repeatable pattern, so this test can only run live", - ); - ctx.skip(); - } - const text = ctx.task.name; - const wrapped = await cryptoClient.wrapKey("RSA1_5", stringToUint8Array(text)); - const unwrappedResult = await cryptoClient.unwrapKey("RSA1_5", wrapped.result); - const unwrappedText = uint8ArrayToString(unwrappedResult.result); - assert.equal(text, unwrappedText); - }); - - it("sign and verify with RS256 through an RSA-HSM key", async function (): Promise { - const signatureValue = Buffer.from("My Message"); - const hash = createHash("sha256"); - hash.update(signatureValue); - const digest = hash.digest(); - const signature = await cryptoClient.sign("RS256", digest); - const verifyResult = await cryptoClient.verify("RS256", digest, signature.result); - assert.ok(verifyResult.result); - }); - - it("sign and verify data with RS256 through an RSA-HSM key (local verification)", async function (): Promise { - const signatureValue = Buffer.from("My Message"); - const signature = await cryptoClient.signData("RS256", signatureValue); - const verifyResult = await cryptoClient.verifyData("RS256", signatureValue, signature.result); - assert.ok(verifyResult.result); - }); - - it("sign and verify with RS384 through an RSA-HSM key", async function (): Promise { - const signatureValue = Buffer.from("My Message"); - const hash = createHash("sha384"); - hash.update(signatureValue); - const digest = hash.digest(); - const signature = await cryptoClient.sign("RS384", digest); - const verifyResult = await cryptoClient.verify("RS384", digest, signature.result); - assert.ok(verifyResult.result); - }); - }); - - describe("EC keys", () => { - beforeEach(async (ctx) => { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - client = authentication.client; - testClient = authentication.testClient; - credential = authentication.credential; - keySuffix = authentication.keySuffix; - - keyName = recorder.variable("EC", `EC-${Math.floor(Math.random() * 100000)}`); - }); - - for (const [keyCurve, signatureAlgorithm, shaAlgorithm] of [ - ["P-256", "ES256", "SHA256"], - ["P-256K", "ES256K", "SHA256"], - ["P-384", "ES384", "SHA384"], - ["P-521", "ES512", "SHA512"], - ] as const) { - it(`sign / signData and verify / verifyData using ${signatureAlgorithm}`, async function () { - keyVaultKey = await client.createEcKey(keyName, { curve: keyCurve }); - // Implicitly test the getCryptographyClient method here - cryptoClient = client.getCryptographyClient( - keyVaultKey.name, - recorder.configureClientOptions({ - keyVersion: keyVaultKey.properties.version, - }), - ); - const data = Buffer.from("my message"); - - // Sign and verify - const hash = createHash(shaAlgorithm); - hash.update(data); - const digest = hash.digest(); - - let signature = await cryptoClient.sign(signatureAlgorithm, digest); - let verification = await cryptoClient.verify(signatureAlgorithm, digest, signature.result); - assert.isTrue(verification.result); - - // SignData and VerifyData - signature = await cryptoClient.signData(signatureAlgorithm, data); - verification = await cryptoClient.verifyData(signatureAlgorithm, data, signature.result); - assert.isTrue(verification.result); - await testClient.flushKey(keyName); - await recorder.stop(); - }); - } - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/node/localCryptography.spec.ts b/sdk/keyvault/keyvault-keys/test/public/node/localCryptography.spec.ts deleted file mode 100644 index c9884f54fceb..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/node/localCryptography.spec.ts +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import type { KeyClient, KeyVaultKey, SignatureAlgorithm } from "../../../src/index.js"; -import { CryptographyClient } from "../../../src/index.js"; -import { createHash } from "node:crypto"; -import { authenticate, envSetupForPlayback } from "../utils/testAuthentication.js"; -import type TestClient from "../utils/testClient.js"; -import { Recorder, env, isLiveMode } from "@azure-tools/test-recorder"; -import type { ClientSecretCredential } from "@azure/identity"; -import { RsaCryptographyProvider } from "../../../src/cryptography/rsaCryptographyProvider.js"; -import { describe, it, assert, expect, beforeEach, afterEach } from "vitest"; - -describe("Local cryptography public tests", () => { - const keyPrefix = `localCrypto${env.KEY_NAME || "KeyName"}`; - let client: KeyClient; - let testClient: TestClient; - let recorder: Recorder; - let credential: ClientSecretCredential; - let keySuffix: string; - - beforeEach(async function (ctx) { - recorder = new Recorder(ctx); - await recorder.start(envSetupForPlayback); - - const authentication = await authenticate(recorder); - client = authentication.client; - testClient = authentication.testClient; - credential = authentication.credential; - keySuffix = authentication.keySuffix; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - describe("When using a local JsonWebToken", function () { - let customKeyName; - let customKeyVaultKey: KeyVaultKey; - let cryptoClientFromKey: CryptographyClient; - - beforeEach(async function () { - customKeyName = testClient.formatName(`${keyPrefix}-beforeeachhook-${keySuffix}`); - customKeyVaultKey = await client.createKey(customKeyName, "RSA"); - cryptoClientFromKey = new CryptographyClient(customKeyVaultKey.key!); - }); - - it("the CryptographyClient can be created from a local JsonWebKey object", async function () { - assert.isEmpty(cryptoClientFromKey.vaultUrl); - assert.equal(cryptoClientFromKey.keyID, customKeyVaultKey.id); - }); - - describe("when using an unsupported algorithm", function () { - it("throws on encrypt", async function () { - await expect(cryptoClientFromKey.encrypt("foo", Buffer.from("bar"))).rejects.toThrow( - /using a local JsonWebKey/, - ); - }); - - it("throws on wrapKey", async function () { - await expect(cryptoClientFromKey.wrapKey("A128KW", Buffer.from("bar"))).rejects.toThrow( - /using a local JsonWebKey/, - ); - }); - - it("throws on sign", async function () { - await expect(cryptoClientFromKey.sign("RSA1_5", Buffer.from("bar"))).rejects.toThrow( - /using a local JsonWebKey/, - ); - }); - - it("throws on signData", async function () { - await expect(cryptoClientFromKey.signData("PS360", Buffer.from("bar"))).rejects.toThrow( - /using a local JsonWebKey/, - ); - }); - - it("throws on verify", async function () { - await expect( - cryptoClientFromKey.verify("PS360", Buffer.from("bar"), Buffer.from("baz")), - ).rejects.toThrow(/using a local JsonWebKey/); - }); - - it("throws on verifyData", async function () { - await expect( - cryptoClientFromKey.verifyData("PS360", Buffer.from("bar"), Buffer.from("baz")), - ).rejects.toThrow(/using a local JsonWebKey/); - }); - }); - - describe("when using an unsupported operation", function () { - it("throws on decrypt", async function () { - await expect(cryptoClientFromKey.decrypt("RSA1_5", Buffer.from("bar"))).rejects.toThrow( - /using a local JsonWebKey/, - ); - }); - - it("throws on unwrapKey", async function () { - await expect(cryptoClientFromKey.unwrapKey("RSA1_5", Buffer.from("bar"))).rejects.toThrow( - /using a local JsonWebKey/, - ); - }); - }); - }); - - it("encrypt & decrypt RSA1_5", async function (ctx) { - if (!isLiveMode()) { - console.log("Skipping test, Local encryption can't be tested on playback"); - ctx.skip(); - } - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyVaultKey = await client.createKey(keyName, "RSA"); - const cryptoClient = new CryptographyClient(keyVaultKey.id!, credential, { - disableChallengeResourceVerification: !isLiveMode(), - }); - - const localCryptoClient = new CryptographyClient(keyVaultKey.key!); - const text = Buffer.from(ctx.task.name); - const encrypted = await localCryptoClient.encrypt("RSA1_5", text); - const unwrapped = await cryptoClient.decrypt("RSA1_5", encrypted.result); - assert.deepEqual(unwrapped.result, text); - await testClient.flushKey(keyName); - }); - - it("encrypt & decrypt RSA-OAEP", async function (ctx) { - if (!isLiveMode()) { - console.log("Skipping test, Local encryption can't be tested on playback"); - ctx.skip(); - } - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyVaultKey = await client.createKey(keyName, "RSA"); - const cryptoClient = new CryptographyClient(keyVaultKey.id!, credential, { - disableChallengeResourceVerification: !isLiveMode(), - }); - - const localCryptoClient = new CryptographyClient(keyVaultKey.key!); - const text = Buffer.from(ctx.task.name); - const encrypted = await localCryptoClient.encrypt("RSA-OAEP", text); - const unwrapped = await cryptoClient.decrypt("RSA-OAEP", encrypted.result); - assert.deepEqual(unwrapped.result, text); - await testClient.flushKey(keyName); - }); - - it("wrapKey & unwrapKey RSA1_5", async function (ctx) { - if (!isLiveMode()) { - console.log("Skipping test, Local encryption can't be tested on playback"); - ctx.skip(); - } - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyVaultKey = await client.createKey(keyName, "RSA"); - const cryptoClient = new CryptographyClient(keyVaultKey.id!, credential, { - disableChallengeResourceVerification: !isLiveMode(), - }); - - const localCryptoClient = new CryptographyClient(keyVaultKey.key!); - const data = Buffer.from("arepa"); - const wrapped = await localCryptoClient.wrapKey("RSA1_5", data); - - // Local Cryptography Client part - // unwrapKey is not implemented locally yet - const unwrapped = await cryptoClient.unwrapKey("RSA1_5", wrapped.result); - assert.deepEqual(unwrapped.result, data); - await testClient.flushKey(keyName); - }); - - it("wrapKey & unwrapKey RSA-OAEP", async function (ctx) { - if (!isLiveMode()) { - console.log("Skipping test, Local encryption can't be tested on playback"); - ctx.skip(); - } - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyVaultKey = await client.createKey(keyName, "RSA"); - const cryptoClient = new CryptographyClient(keyVaultKey.id!, credential, { - disableChallengeResourceVerification: !isLiveMode(), - }); - - const localCryptoClient = new CryptographyClient(keyVaultKey.key!); - const data = Buffer.from("arepa"); - const wrapped = await localCryptoClient.wrapKey("RSA-OAEP", data); - - // Local Cryptography Client part - // unwrapKey is not implemented locally yet - const unwrapped = await cryptoClient.unwrapKey("RSA-OAEP", wrapped.result); - assert.deepEqual(unwrapped.result, data); - await testClient.flushKey(keyName); - }); - - describe("verify", () => { - const rsaProvider = new RsaCryptographyProvider({}); - const localSupportedAlgorithmNames = Object.keys(rsaProvider.signatureAlgorithmToHashAlgorithm); - - for (const localAlgorithmName of localSupportedAlgorithmNames) { - it(localAlgorithmName, async function (ctx): Promise { - const keyName = testClient.formatName(`${keyPrefix}-${ctx.task.name}-${keySuffix}`); - const keyVaultKey = await client.createKey(keyName, "RSA"); - const cryptoClient = new CryptographyClient( - keyVaultKey.id!, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: !isLiveMode() }), - ); - - // Sign is not implemented yet. - // This boils down to the JWK to PEM conversion, which doesn't support private keys at the moment. - const signatureValue = ctx.task.name; - const hash = createHash(rsaProvider.signatureAlgorithmToHashAlgorithm[localAlgorithmName]); - hash.update(signatureValue); - const digest = hash.digest(); - const signature = await cryptoClient.sign(localAlgorithmName as SignatureAlgorithm, digest); - - // Local Cryptography Client part - const localCryptoClient = new CryptographyClient(keyVaultKey.key!); - const verifyResult = await localCryptoClient.verifyData( - localAlgorithmName, - digest, - signature.result, - ); - assert.ok(verifyResult); - - await testClient.flushKey(keyName); - }); - } - }); -}); diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/base64url.browser.ts b/sdk/keyvault/keyvault-keys/test/public/utils/base64url.browser.ts deleted file mode 100644 index 76ff758a2393..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/base64url.browser.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * Decodes a base64url string. - * Padding is not needed for the recorded tests and is not added. - * - * @internal - */ -export function fromBase64url(value: string): string { - const encoded = value.replace(/-/g, "+").replace(/_/g, "/"); - return atob(encoded); -} - -/** - * Encodes a string to base64url. - * - * @internal - */ -export function toBase64url(value: string): string { - return btoa(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/base64url.ts b/sdk/keyvault/keyvault-keys/test/public/utils/base64url.ts deleted file mode 100644 index 8d7c09d9d004..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/base64url.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * Decodes a base64url string. - * Padding is not needed for the recorded tests and is not added. - * - * @internal - */ -export function fromBase64url(value: string): string { - const encoded = value.replace(/-/g, "+").replace(/_/g, "/"); - return Buffer.from(encoded, "base64").toString(); -} - -/** - * Encodes a string to base64url. - * - * @internal - */ -export function toBase64url(value: string): string { - return Buffer.from(value) - .toString("base64") - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/, ""); -} diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/crypto.ts b/sdk/keyvault/keyvault-keys/test/public/utils/crypto.ts deleted file mode 100644 index 8847a05d92e8..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/crypto.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { JsonWebKey } from "../../../src/index.js"; - -export function stringToUint8Array(str: string): Uint8Array { - return new Uint8Array(Buffer.from(str)); -} - -export function uint8ArrayToString(ab: Uint8Array): string { - return Buffer.from(ab).toString("utf-8"); -} - -export function getKey(size: number): Uint8Array { - const result = new Uint8Array(size); - return result.map((_val, i) => i); -} - -function toBytes(hex: string): Uint8Array { - if (hex.length % 2) { - hex = `0${hex}`; - } - return Buffer.from(hex, "hex"); -} - -export function createRsaKey(): JsonWebKey { - return { - kty: "RSA", - keyOps: ["encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"], - n: toBytes( - "00a0914d00234ac683b21b4c15d5bed887bdc959c2e57af54ae734e8f00720d775d275e455207e3784ceeb60a50a4655dd72a7a94d271e8ee8f7959a669ca6e775bf0e23badae991b4529d978528b4bd90521d32dd2656796ba82b6bbfc7668c8f5eeb5053747fd199319d29a8440d08f4412d527ff9311eda71825920b47b1c46b11ab3e91d7316407e89c7f340f7b85a34042ce51743b27d4718403d34c7b438af6181be05e4d11eb985d38253d7fe9bf53fc2f1b002d22d2d793fa79a504b6ab42d0492804d7071d727a06cf3a8893aa542b1503f832b296371b6707d4dc6e372f8fe67d8ded1c908fde45ce03bc086a71487fa75e43aa0e0679aa0d20efe35", - ), - e: toBytes("10001"), - d: toBytes( - "627c7d24668148fe2252c7fa649ea8a5a9ed44d75c766cda42b29b660e99404f0e862d4561a6c95af6a83d213e0a2244b03cd28576473215073785fb067f015da19084ade9f475e08b040a9a2c7ba00253bb8125508c9df140b75161d266be347a5e0f6900fe1d8bbf78ccc25eeb37e0c9d188d6e1fc15169ba4fe12276193d77790d2326928bd60d0d01d6ead8d6ac4861abadceec95358fd6689c50a1671a4a936d2376440a41445501da4e74bfb98f823bd19c45b94eb01d98fc0d2f284507f018ebd929b8180dbe6381fdd434bffb7800aaabdd973d55f9eaf9bb88a6ea7b28c2a80231e72de1ad244826d665582c2362761019de2e9f10cb8bcc2625649", - ), - p: toBytes( - "00d1deac8d68ddd2c1fd52d5999655b2cf1565260de5269e43fd2a85f39280e1708ffff0682166cb6106ee5ea5e9ffd9f98d0becc9ff2cda2febc97259215ad84b9051e563e14a051dce438bc6541a24ac4f014cf9732d36ebfc1e61a00d82cbe412090f7793cfbd4b7605be133dfc3991f7e1bed5786f337de5036fc1e2df4cf3", - ), - q: toBytes( - "00c3dc66b641a9b73cd833bc439cd34fc6574465ab5b7e8a92d32595a224d56d911e74624225b48c15a670282a51c40d1dad4bc2e9a3c8dab0c76f10052dfb053bc6ed42c65288a8e8bace7a8881184323f94d7db17ea6dfba651218f931a93b8f738f3d8fd3f6ba218d35b96861a0f584b0ab88ddcf446b9815f4d287d83a3237", - ), - dp: toBytes( - "00c9a159be7265cbbabc9afcc4967eb74fe58a4c4945431902d1142da599b760e03838f8cbd26b64324fea6bdc9338503f459793636e59b5361d1e6951e08ddb089e1b507be952a81fbeaf7e76890ea4f536e25505c3f648b1e88377dfc19b4c304e738dfca07211b792286a392a704d0f444c0a802539110b7f1f121c00cff0a9", - ), - dq: toBytes( - "00a0bd4c0a3d9f64436a082374b5caf2488bac1568696153a6a5e4cd85d186db31e2f58f024c617d29f37b4e6b54c97a1e25efec59c4d1fd3061ac33509ce8cae5c11f4cd2e83f41a8264f785e78dc0996076ee23dfdfc43d67c463afaa0180c4a718357f9a6f270d542479a0f213870e661fb950abca4a14ca290570ba7983347", - ), - qi: toBytes( - "009fe7ae42e92bc04fcd5780464bd21d0c8ac0c599f9af020fde6ab0a7e7d1d39902f5d8fb6c614184c4c1b103fb46e94cd10a6c8a40f9991a1f28269f326435b6c50276fda6493353c650a833f724d80c7d522ba16c79f0eb61f672736b68fb8be3243d10943c4ab7028d09e76cfb5892222e38bc4d35585bf35a88cd68c73b07", - ), - }; -} diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/lro/restore/operation.ts b/sdk/keyvault/keyvault-keys/test/public/utils/lro/restore/operation.ts deleted file mode 100644 index c94c52386d53..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/lro/restore/operation.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { AbortSignalLike } from "@azure/abort-controller"; -import type { PollOperation, PollOperationState } from "@azure/core-lro"; -import type { OperationOptions } from "@azure-rest/core-client"; -import type { KeyPollerOptions, KeyVaultKey } from "../../../../../src/index.js"; - -/** - * Options sent to the beginRestoreKeyBackup method. - */ -export interface BeginRestoreKeyBackupOptions extends KeyPollerOptions {} - -/** - * @internal - * An interface representing the KeyClient. For internal use. - */ -export interface TestKeyClientInterface { - /** - * Restores a backed up key, and all its versions, to a vault. This operation requires the - * keys/restore permission. - */ - restoreKeyBackup( - backup: Uint8Array, - options?: BeginRestoreKeyBackupOptions, - ): Promise; -} - -/** - * An interface representing the state of the restore key's poll operation - */ -export interface RestoreKeyBackupPollOperationState extends PollOperationState { - /** - * The backup of the key. - */ - backup: Uint8Array; - /** - * Options for the core-client requests. - */ - requestOptions?: OperationOptions; - /** - * An interface representing a KeyClient. For internal use. - */ - client: TestKeyClientInterface; -} - -/** - * An interface representing a restore key's poll operation - */ -export interface RestoreKeyBackupPollOperation - extends PollOperation {} - -/** - * Reaches to the service and updates the restore key's poll operation. - * @param options - The optional parameters, which are an abortSignal from \@azure/abort-controller and a function that triggers the poller's onProgress function. - */ -async function update( - this: RestoreKeyBackupPollOperation, - options: { - abortSignal?: AbortSignalLike; - fireProgress?: (state: RestoreKeyBackupPollOperationState) => void; - } = {}, -): Promise { - const state = this.state; - const { backup, client, requestOptions = {} } = state; - - if (options.abortSignal) { - requestOptions.abortSignal = options.abortSignal; - } - - if (!state.isStarted) { - state.isStarted = true; - } - - try { - state.result = await client.restoreKeyBackup(backup, requestOptions); - state.isCompleted = true; - } catch { - // Nothing to do here. - } - - return makeRestoreKeyBackupPollOperation(state); -} - -/** - * @param options - The optional parameters, which is only an abortSignal from \@azure/abort-controller - */ -async function cancel(this: RestoreKeyBackupPollOperation): Promise { - throw new Error("Canceling the restoration of a key is not supported."); -} - -/** - * Serializes the create key's poll operation - */ -function toString(this: RestoreKeyBackupPollOperation): string { - return JSON.stringify({ - state: this.state, - }); -} - -/** - * Builds a create key's poll operation - * @param state - A poll operation's state, in case the new one is intended to follow up where the previous one was left. - */ -export function makeRestoreKeyBackupPollOperation( - state: RestoreKeyBackupPollOperationState, -): RestoreKeyBackupPollOperation { - return { - state: { - ...state, - }, - update, - cancel, - toString, - }; -} diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/lro/restore/poller.ts b/sdk/keyvault/keyvault-keys/test/public/utils/lro/restore/poller.ts deleted file mode 100644 index 95965816b21a..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/lro/restore/poller.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { OperationOptions } from "@azure-rest/core-client"; -import { delay } from "@azure/core-util"; -import { Poller } from "@azure/core-lro"; -import type { RestoreKeyBackupPollOperationState, TestKeyClientInterface } from "./operation.js"; -import { makeRestoreKeyBackupPollOperation } from "./operation.js"; -import type { KeyVaultKey } from "../../../../../src/index.js"; - -export interface RestoreKeyBackupPollerOptions { - client: TestKeyClientInterface; - backup: Uint8Array; - requestOptions?: OperationOptions; - intervalInMs?: number; - resumeFrom?: string; -} - -/** - * Class that creates a poller that waits until a key finishes being restored - */ -export class RestoreKeyBackupPoller extends Poller< - RestoreKeyBackupPollOperationState, - KeyVaultKey -> { - /** - * Defines how much time the poller is going to wait before making a new request to the service. - */ - public intervalInMs: number; - - constructor(options: RestoreKeyBackupPollerOptions) { - const { client, backup, requestOptions, intervalInMs = 2000, resumeFrom } = options; - - let state: RestoreKeyBackupPollOperationState | undefined; - - if (resumeFrom) { - state = JSON.parse(resumeFrom).state; - } - - const operation = makeRestoreKeyBackupPollOperation({ - ...state, - backup, - requestOptions, - client, - }); - - super(operation); - - this.intervalInMs = intervalInMs; - } - - /** - * The method used by the poller to wait before attempting to update its operation. - */ - async delay(): Promise { - return delay(this.intervalInMs); - } -} diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/recorderUtils.ts b/sdk/keyvault/keyvault-keys/test/public/utils/recorderUtils.ts deleted file mode 100644 index 73913d864f48..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/recorderUtils.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { isPlaybackMode } from "@azure-tools/test-recorder"; - -export function uniqueString(): string { - return isPlaybackMode() ? "" : Math.random().toString().slice(2); -} - -/** - * Properties that are used to configure our polling operations - * in tests. During playback mode we don't want any delays. During - * live mode we can safely increase the default polling interval (currently 2s) - * to 5s in order to reduce calls to the service. - */ -export const testPollerProperties = { - intervalInMs: isPlaybackMode() ? 0 : 5 * 1000, -}; diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/testAuthentication.ts b/sdk/keyvault/keyvault-keys/test/public/utils/testAuthentication.ts deleted file mode 100644 index 678f52f44ceb..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/testAuthentication.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { KeyClient } from "../../../src/index.js"; -import type { Recorder } from "@azure-tools/test-recorder"; -import { env, assertEnvironmentVariable, isLiveMode } from "@azure-tools/test-recorder"; -import { uniqueString } from "./recorderUtils.js"; -import TestClient from "./testClient.js"; -import { createTestCredential } from "@azure-tools/test-credential"; - -export const replaceableVariables = { - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "12345678-1234-1234-1234-123456789012", - KEYVAULT_NAME: "keyvault_name", - KEYVAULT_URI: "https://keyvault_name.vault.azure.net/", - AZURE_MANAGEDHSM_URI: "https://azure_managedhsm.managedhsm.azure.net/", - AZURE_KEYVAULT_ATTESTATION_URI: "https://skr_attestation.azure.net/", -}; - -export const envSetupForPlayback = { - envSetupForPlayback: { - ...replaceableVariables, - }, -}; - -export async function authenticate(recorder: Recorder): Promise { - const keySuffix = uniqueString(); - - const keyVaultUriName = assertEnvironmentVariable("KEYVAULT_URI").match("https://(.*.net)/")![1]; - const replacedKeyVaultUriName = replaceableVariables.KEYVAULT_URI.match("https://(.*.net)/")![1]; - - await recorder.addSanitizers({ - generalSanitizers: [ - { - target: keySuffix, - value: "", - }, - { - target: keyVaultUriName, - value: replacedKeyVaultUriName, - }, - ], - bodyKeySanitizers: [ - { - jsonPath: "$.release_policy.data", - value: "eyAic2FuaXRpemVkIjogInNhbml0aXplZCIgfQ==", // dummy base64-encoded JSON object - }, - ], - }); - - const credential = createTestCredential(); - - const keyVaultUrl = assertEnvironmentVariable("KEYVAULT_URI"); - if (!keyVaultUrl) { - throw new Error("Missing KEYVAULT_URI environment variable."); - } - - const client = new KeyClient( - keyVaultUrl, - credential, - recorder.configureClientOptions({ - disableChallengeResourceVerification: !isLiveMode(), - }), - ); - const testClient = new TestClient(client); - - let hsmClient: KeyClient | undefined = undefined; - if (env.AZURE_MANAGEDHSM_URI) { - hsmClient = new KeyClient( - env.AZURE_MANAGEDHSM_URI, - credential, - recorder.configureClientOptions({ - disableChallengeResourceVerification: !isLiveMode(), - }), - ); - } - - return { client, credential, testClient, hsmClient, keySuffix }; -} diff --git a/sdk/keyvault/keyvault-keys/test/public/utils/testClient.ts b/sdk/keyvault/keyvault-keys/test/public/utils/testClient.ts deleted file mode 100644 index 2cd3e51e95b1..000000000000 --- a/sdk/keyvault/keyvault-keys/test/public/utils/testClient.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { testPollerProperties } from "./recorderUtils.js"; -import type { KeyClient } from "../../../src/index.js"; - -export interface TestClientInterface { - client: KeyClient; - formatName: (name: string) => string; - purgeKey: (keyName: string) => Promise; - flushKey: (keyName: string) => Promise; -} -export default class TestClient implements TestClientInterface { - public readonly client: KeyClient; - constructor(client: KeyClient) { - this.client = client; - } - public formatName(name: string): string { - return name.replace(/[^0-9a-zA-Z-]/g, ""); - } - public async purgeKey(keyName: string): Promise { - await this.client.purgeDeletedKey(keyName); - } - public async flushKey(keyName: string): Promise { - const poller = await this.client.beginDeleteKey(keyName, testPollerProperties); - await poller.pollUntilDone(); - await this.purgeKey(keyName); - } -} diff --git a/sdk/keyvault/keyvault-keys/tests.yml b/sdk/keyvault/keyvault-keys/tests.yml deleted file mode 100644 index d69fb0e566d9..000000000000 --- a/sdk/keyvault/keyvault-keys/tests.yml +++ /dev/null @@ -1,25 +0,0 @@ -trigger: none - -extends: - template: /eng/pipelines/templates/stages/archetype-sdk-tests.yml - parameters: - PackageName: "@azure/keyvault-keys" - ServiceDirectory: keyvault - TimeoutInMinutes: 90 - CloudConfig: - Public: - Location: 'eastus2' - # KV HSM limitation prevents us from running live tests - # against multiple platforms in parallel (we're limited to a single - # instance per region per subscription) so we're only running - # live tests against a single instance. - AdditionalMatrixConfigs: - - Name: Keyvault_live_test_base - Path: sdk/keyvault/keyvault-keys/platform-matrix.json - Selection: sparse - GenerateVMJobs: true - - # Due to the high cost of Managed HSMs, we only want to test using them weekly. - ${{ if not(contains(variables['Build.DefinitionName'], 'tests-weekly')) }}: - MatrixFilters: - - ArmTemplateParameters=^(?!.*enableHsm.*true) diff --git a/sdk/keyvault/keyvault-keys/tsconfig.browser.config.json b/sdk/keyvault/keyvault-keys/tsconfig.browser.config.json deleted file mode 100644 index 75871518e3a0..000000000000 --- a/sdk/keyvault/keyvault-keys/tsconfig.browser.config.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["./tsconfig.test.json", "../../../tsconfig.browser.base.json"] -} diff --git a/sdk/keyvault/keyvault-keys/tsconfig.json b/sdk/keyvault/keyvault-keys/tsconfig.json deleted file mode 100644 index 273d9078a24a..000000000000 --- a/sdk/keyvault/keyvault-keys/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "references": [ - { "path": "./tsconfig.src.json" }, - { "path": "./tsconfig.samples.json" }, - { "path": "./tsconfig.test.json" } - ] -} diff --git a/sdk/keyvault/keyvault-keys/tsconfig.samples.json b/sdk/keyvault/keyvault-keys/tsconfig.samples.json deleted file mode 100644 index 29352310b73e..000000000000 --- a/sdk/keyvault/keyvault-keys/tsconfig.samples.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../../tsconfig.samples.base.json", - "compilerOptions": { - "paths": { - "@azure/keyvault-keys": ["./dist/esm"] - } - } -} diff --git a/sdk/keyvault/keyvault-keys/tsconfig.src.json b/sdk/keyvault/keyvault-keys/tsconfig.src.json deleted file mode 100644 index bae70752dd38..000000000000 --- a/sdk/keyvault/keyvault-keys/tsconfig.src.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../../../tsconfig.lib.json" -} diff --git a/sdk/keyvault/keyvault-keys/tsconfig.test.json b/sdk/keyvault/keyvault-keys/tsconfig.test.json deleted file mode 100644 index 290ca214aebc..000000000000 --- a/sdk/keyvault/keyvault-keys/tsconfig.test.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["./tsconfig.src.json", "../../../tsconfig.test.base.json"] -} diff --git a/sdk/keyvault/keyvault-keys/tsdoc.json b/sdk/keyvault/keyvault-keys/tsdoc.json deleted file mode 100644 index 81c5a8a2aa2f..000000000000 --- a/sdk/keyvault/keyvault-keys/tsdoc.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", - "extends": ["../../../tsdoc.json"] -} diff --git a/sdk/keyvault/keyvault-keys/tsp-location.yaml b/sdk/keyvault/keyvault-keys/tsp-location.yaml index 8a8ab1850c92..3a7514b024c6 100644 --- a/sdk/keyvault/keyvault-keys/tsp-location.yaml +++ b/sdk/keyvault/keyvault-keys/tsp-location.yaml @@ -1,5 +1,5 @@ -directory: specification/keyvault/Security.KeyVault.Keys/ -commit: de825aa1e9bc91476240630a2142d42a380de1c9 -repo: azure/azure-rest-api-specs -additionalDirectories: -- specification/keyvault/Security.KeyVault.Common/ +directory: specification/keyvault/Security.KeyVault.Keys +commit: 59583521f5e5a5b1e02bd8966bc30b567ecc696a +repo: ../azure-rest-api-specs +additionalDirectories: +- specification/keyvault/Security.KeyVault.Common diff --git a/sdk/keyvault/keyvault-keys/vitest.config.ts b/sdk/keyvault/keyvault-keys/vitest.config.ts deleted file mode 100644 index 0dfa15cc4498..000000000000 --- a/sdk/keyvault/keyvault-keys/vitest.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import viteConfig from "../../../vitest.shared.config.ts"; - -export default viteConfig; diff --git a/sdk/keyvault/keyvault-keys/vitest.esm.config.ts b/sdk/keyvault/keyvault-keys/vitest.esm.config.ts deleted file mode 100644 index 2f6e757a54f7..000000000000 --- a/sdk/keyvault/keyvault-keys/vitest.esm.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { mergeConfig } from "vitest/config"; -import vitestConfig from "./vitest.config.ts"; -import vitestEsmConfig from "../../../vitest.esm.shared.config.ts"; - -export default mergeConfig( - vitestConfig, - vitestEsmConfig -);