From e317f88c61bae64d8ca92a5db4fea5997124643b Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Fri, 22 Nov 2024 05:13:02 +0000 Subject: [PATCH] CodeGen from PR 30239 in Azure/azure-rest-api-specs Merge e157edee5c93247d305574e586f549914ed32efe into 01833dddcd59e369b08a8cad696f03297b18c045 --- sdk/keyvault/keyvault-admin/CHANGELOG.md | 193 ----- sdk/keyvault/keyvault-admin/LICENSE | 21 - sdk/keyvault/keyvault-admin/README.md | 160 ---- .../keyvault-admin/TROUBLESHOOTING.md | 3 - .../keyvault-admin/api-extractor.json | 31 - sdk/keyvault/keyvault-admin/assets.json | 6 - sdk/keyvault/keyvault-admin/eslint.config.mjs | 13 - sdk/keyvault/keyvault-admin/package.json | 147 ---- .../keyvault-admin/platform-matrix.json | 22 - .../review/keyvault-admin.api.md | 300 ------- sdk/keyvault/keyvault-admin/sample.env | 23 - .../samples-dev/accessControlHelloWorld.ts | 81 -- .../samples-dev/backupRestoreHelloWorld.ts | 65 -- .../samples-dev/backupSelectiveKeyRestore.ts | 76 -- .../samples-dev/snippets/_prerequisites.md | 3 - .../samples-dev/updateSettings.ts | 37 - .../samples/v4-beta/javascript/README.md | 73 -- .../javascript/accessControlHelloWorld.js | 81 -- .../javascript/backupRestoreHelloWorld.js | 66 -- .../javascript/backupSelectiveKeyRestore.js | 77 -- .../samples/v4-beta/javascript/package.json | 40 - .../samples/v4-beta/javascript/sample.env | 23 - .../v4-beta/javascript/updateSettings.js | 38 - .../samples/v4-beta/typescript/README.md | 86 -- .../samples/v4-beta/typescript/package.json | 50 -- .../samples/v4-beta/typescript/sample.env | 23 - .../typescript/src/accessControlHelloWorld.ts | 81 -- .../typescript/src/backupRestoreHelloWorld.ts | 65 -- .../src/backupSelectiveKeyRestore.ts | 76 -- .../v4-beta/typescript/src/updateSettings.ts | 37 - .../samples/v4-beta/typescript/tsconfig.json | 17 - .../samples/v4/javascript/README.md | 73 -- .../v4/javascript/accessControlHelloWorld.js | 81 -- .../v4/javascript/backupRestoreHelloWorld.js | 66 -- .../javascript/backupSelectiveKeyRestore.js | 77 -- .../samples/v4/javascript/package.json | 40 - .../samples/v4/javascript/sample.env | 23 - .../samples/v4/typescript/README.md | 86 -- .../samples/v4/typescript/package.json | 50 -- .../samples/v4/typescript/sample.env | 23 - .../typescript/src/accessControlHelloWorld.ts | 81 -- .../typescript/src/backupRestoreHelloWorld.ts | 65 -- .../src/backupSelectiveKeyRestore.ts | 76 -- .../samples/v4/typescript/tsconfig.json | 17 - .../keyvault-admin/src/accessControlClient.ts | 489 ----------- .../keyvault-admin/src/accessControlModels.ts | 215 ----- .../keyvault-admin/src/backupClient.ts | 407 --------- .../keyvault-admin/src/backupClientModels.ts | 104 --- sdk/keyvault/keyvault-admin/src/constants.ts | 17 - .../keyvault-admin/src/generated/index.ts | 12 - .../src/generated/keyVaultClient.ts | 332 -------- .../src/generated/keyVaultClientContext.ts | 54 -- .../src/generated/models/index.ts | 632 -------------- .../src/generated/models/mappers.ts | 784 ------------------ .../src/generated/models/parameters.ts | 187 ----- .../src/generated/operations/index.ts | 10 - .../generated/operations/roleAssignments.ts | 236 ------ .../generated/operations/roleDefinitions.ts | 237 ------ .../generated/operationsInterfaces/index.ts | 10 - .../operationsInterfaces/roleAssignments.ts | 89 -- .../operationsInterfaces/roleDefinitions.ts | 90 -- sdk/keyvault/keyvault-admin/src/index.ts | 13 - sdk/keyvault/keyvault-admin/src/log.ts | 9 - .../src/lro/backup/operation.ts | 151 ---- .../keyvault-admin/src/lro/backup/poller.ts | 57 -- .../src/lro/keyVaultAdminPoller.ts | 139 ---- .../src/lro/restore/operation.ts | 162 ---- .../keyvault-admin/src/lro/restore/poller.ts | 60 -- .../src/lro/selectiveKeyRestore/operation.ts | 159 ---- .../src/lro/selectiveKeyRestore/poller.ts | 63 -- sdk/keyvault/keyvault-admin/src/mappings.ts | 58 -- .../keyvault-admin/src/settingsClient.ts | 138 --- .../src/settingsClientModels.ts | 81 -- sdk/keyvault/keyvault-admin/src/tracing.ts | 11 - sdk/keyvault/keyvault-admin/swagger/README.md | 81 -- sdk/keyvault/keyvault-admin/test/README.md | 56 -- .../internal/serviceVersionParameter.spec.ts | 117 --- .../test/internal/userAgent.spec.ts | 32 - .../public/accessControlClient.aborts.spec.ts | 97 --- .../test/public/accessControlClient.spec.ts | 306 ------- .../test/public/backupClient.abort.spec.ts | 75 -- .../test/public/backupClient.spec.ts | 166 ---- .../test/public/settingsClient.spec.ts | 39 - .../test/public/utils/authentication.ts | 103 --- .../test/public/utils/common.ts | 41 - .../test/public/utils/recorder.ts | 14 - sdk/keyvault/keyvault-admin/tests.yml | 23 - sdk/keyvault/keyvault-admin/tsconfig.json | 20 - sdk/keyvault/keyvault-admin/tsdoc.json | 4 - sdk/keyvault/keyvault-admin/tsp-location.yaml | 4 + sdk/keyvault/keyvault-admin/vitest.config.ts | 15 - 91 files changed, 4 insertions(+), 8967 deletions(-) delete mode 100644 sdk/keyvault/keyvault-admin/CHANGELOG.md delete mode 100644 sdk/keyvault/keyvault-admin/LICENSE delete mode 100644 sdk/keyvault/keyvault-admin/README.md delete mode 100644 sdk/keyvault/keyvault-admin/TROUBLESHOOTING.md delete mode 100644 sdk/keyvault/keyvault-admin/api-extractor.json delete mode 100644 sdk/keyvault/keyvault-admin/assets.json delete mode 100644 sdk/keyvault/keyvault-admin/eslint.config.mjs delete mode 100644 sdk/keyvault/keyvault-admin/package.json delete mode 100644 sdk/keyvault/keyvault-admin/platform-matrix.json delete mode 100644 sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md delete mode 100644 sdk/keyvault/keyvault-admin/sample.env delete mode 100644 sdk/keyvault/keyvault-admin/samples-dev/accessControlHelloWorld.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples-dev/backupRestoreHelloWorld.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples-dev/backupSelectiveKeyRestore.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples-dev/snippets/_prerequisites.md delete mode 100644 sdk/keyvault/keyvault-admin/samples-dev/updateSettings.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/README.md delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/accessControlHelloWorld.js delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupRestoreHelloWorld.js delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupSelectiveKeyRestore.js delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/package.json delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/sample.env delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/updateSettings.js delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/README.md delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/package.json delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/sample.env delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/accessControlHelloWorld.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupRestoreHelloWorld.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupSelectiveKeyRestore.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/updateSettings.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/tsconfig.json delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/javascript/README.md delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/javascript/accessControlHelloWorld.js delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/javascript/backupRestoreHelloWorld.js delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/javascript/backupSelectiveKeyRestore.js delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/javascript/package.json delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/javascript/sample.env delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/typescript/README.md delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/typescript/package.json delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/typescript/sample.env delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/typescript/src/accessControlHelloWorld.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupRestoreHelloWorld.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupSelectiveKeyRestore.ts delete mode 100644 sdk/keyvault/keyvault-admin/samples/v4/typescript/tsconfig.json delete mode 100644 sdk/keyvault/keyvault-admin/src/accessControlClient.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/accessControlModels.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/backupClient.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/backupClientModels.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/constants.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/index.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/keyVaultClientContext.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/models/index.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/models/mappers.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/models/parameters.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/operations/index.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/operations/roleAssignments.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/operations/roleDefinitions.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/index.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleAssignments.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleDefinitions.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/index.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/log.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/lro/backup/operation.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/lro/backup/poller.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/lro/keyVaultAdminPoller.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/lro/restore/operation.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/lro/restore/poller.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/operation.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/poller.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/mappings.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/settingsClient.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/settingsClientModels.ts delete mode 100644 sdk/keyvault/keyvault-admin/src/tracing.ts delete mode 100644 sdk/keyvault/keyvault-admin/swagger/README.md delete mode 100644 sdk/keyvault/keyvault-admin/test/README.md delete mode 100644 sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/accessControlClient.aborts.spec.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/backupClient.abort.spec.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/settingsClient.spec.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/utils/authentication.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/utils/common.ts delete mode 100644 sdk/keyvault/keyvault-admin/test/public/utils/recorder.ts delete mode 100644 sdk/keyvault/keyvault-admin/tests.yml delete mode 100644 sdk/keyvault/keyvault-admin/tsconfig.json delete mode 100644 sdk/keyvault/keyvault-admin/tsdoc.json create mode 100644 sdk/keyvault/keyvault-admin/tsp-location.yaml delete mode 100644 sdk/keyvault/keyvault-admin/vitest.config.ts diff --git a/sdk/keyvault/keyvault-admin/CHANGELOG.md b/sdk/keyvault/keyvault-admin/CHANGELOG.md deleted file mode 100644 index 655820b191f2..000000000000 --- a/sdk/keyvault/keyvault-admin/CHANGELOG.md +++ /dev/null @@ -1,193 +0,0 @@ -# Release History - -## 4.6.1 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 4.6.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. [#30743](https://github.com/Azure/azure-sdk-for-js/pull/30743) - -## 4.5.0 (2024-02-14) - -### Features Added - -Since 4.4.0: - -- Managed Identity can now be used in place of a SAS token to access the blob storage resource when performing backup and restore operations. - -### Breaking Changes - -Since 4.5.0-beta.1: - -- Change signature of backup and restore operations to use an overload when using Managed Identity to access the blob storage resource. This means - `undefined` no longer has to be passed in the `sasToken` parameter in order to set additional request options when using Managed Identity. - This change is only breaking for customers using 4.5.0-beta.1 and does not impact customers using the previous GA version, 4.4.0. - -### Other Changes - -- The default service version is now `7.5`. - -## 4.5.0-beta.1 (2023-11-08) - -### Features Added - -- Managed Identity can now be used in place of a SAS token to access the blob storage resource when performing backup and restore operations. - -### Other Changes - -- The default service version is now `7.5-preview.1`. - -## 4.4.0 (2023-03-09) - -### Features Added - -- Added `KeyVaultSettingsClient` to get and update Managed HSM settings. - -### Other Changes - -- `KeyVaultAccessControlClient`, `KeyVaultBackupClient`, and `KeyVaultSettingsClient` now support service version 7.4 by default. - -## 4.4.0-beta.1 (2022-11-10) - -### Features Added - -- Added `KeyVaultSettingsClient` to get and update Managed HSM settings. -- Added support for service version `7.4-preview.1`. - -## 4.3.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.2.2 (2022-08-09) - -### Other Changes - -- Improvements to documentation. - -## 4.2.1 (2022-07-05) - -### Bugs Fixed - -- The scope of the token used for authentication now reflects the scope required by the service in the WWW-Authenticate header. - -## 4.2.0 (2022-03-24) - -### Other Changes - -- This release updates `BackupClient` and `AccessControlClient` to support service version 7.3 by default. - -## 4.2.0-beta.2 (2021-11-09) - -### Features Added - -- Support multi-tenant authentication against Key Vault and Managed HSM when using @azure/identity 2.0.0 or newer. - -### Other Changes - -- Updated the latest service version to 7.3. - -## 4.2.0-beta.1 (2021-08-10) - -- Move generated client to use @azure/core-rest-pipeline. For more information about Core V2, please refer to [the documentation](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core#core-v1-and-core-v2). - - - With this change, 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. - - ```typescript - let rawResponse: FullOperationResponse | undefined; - await client.getRoleDefinition(globalScope, "roleDefinitionName", { - onResponse: (response) => (rawResponse = response), - }); - ``` - -## 4.1.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.1.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. - -## 4.0.1 (2021-06-15) - -### Bug Fixes - -- Fixed an issue where bundling could fail when importing this library due to an incorrectly set import. - -## 4.0.0 (2021-06-15) - -This release marks the general availability of the `@azure/keyvault-admin` package. - -### New Features - -- The `KeyVaultAccessControlClient` provides support for managing role-based access control (RBAC) operations. - - Both role assignments and custom role definitions are supported with the ability to create, read, update, and delete custom role definitions and assignments. -- The `KeyVaultBackupClient` provides support for back up and restore operations for the entire Key Vault Managed HSM instance. - - Full Managed HSM backup and restore operations are supported. - - Selective Key Restore from a previous backup is also supported. - -### Changes since 4.0.0-beta.3: - -- Added the "KeyVault" prefix to all of the Key Vault Admin client operations. -- Made the AesGcmDecryptParameters authenticationTag required. -- Collapsed `KeyVaultRoleAssignmentPropertiesWithScope` to `KeyVaultRoleAssignmentProperties`. -- Renamed `KeyVaultKeyId` to `KeyVaultKeyIdentifier`. -- Renamed `beginRestore`'s `blobStorageUri` to `folderUri`. -- Removed `folderName` from `beginRestore`. Now the folder name will be inferred from the `folderUri`. -- Renamed `beginSelectiveRestore`'s `blobStorageUri` to `folderUri`. -- Removed `folderName` from `beginSelectiveRestore`. Now the folder name will be inferred from the `folderUri`. -- Reordered the parameters of `beginSelectiveRestore` to `keyName`, `folderUrl`, `sasToken`, `[options]`. -- Renamed `KeyVaultBackupResult`'s `backupFolderUri` to `folderUri`. -- Renamed `beginSelectiveRestore` to `beginSelectiveKeyRestore`. -- Renamed `KeyVaultBeginSelectiveRestoreOptions` to `KeyVaultBeginSelectiveKeyRestoreOptions`. -- Renamed `KeyVaultSelectiveRestoreOperationState` to `KeyVaultSelectiveKeyRestoreOperationState`. -- Renamed `KeyVaultSelectiveRestoreResult` to `KeyVaultSelectiveKeyRestoreResult`. -- `deleteRoleAssignment` and `deleteRoleDefinition` will no longer throw an exception when the resource no longer exist and return no result. - -## 4.0.0-beta.3 (2021-04-06) - -- Updated the Latest service version to 7.2. -- Long Running Operations will now use the `status` field to determine whether the operation failed. -- 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. - -## 4.0.0-beta.2 (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 Admin 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. -- [Breaking] Return `BackupResult` and `RestoreResult` from backup/restore long running operations which will contain additional information about the operation as well any relevant data. -- Backup / Restore polling will now correctly propagate any errors to the awaited call. -- Add support for custom role definitions - creating, updating, and deleting role definitions are now supported. - -## 4.0.0-beta.1 (2020-09-11) - -The @azure/keyvault-admin package provides two clients, `KeyVaultAccessControlClient` and `KeyVaultBackupClient`. - -- The `KeyVaultAccessControlClient` allows working with role-based access control (RBAC) operations, meaning assigning, deleting and retrieving role assignments, and retrieving role definitions. -- The `KeyVaultBackupClient` allows generating full backups and restores of Key Vault instances, and selective restores of keys. diff --git a/sdk/keyvault/keyvault-admin/LICENSE b/sdk/keyvault/keyvault-admin/LICENSE deleted file mode 100644 index ea8fb1516028..000000000000 --- a/sdk/keyvault/keyvault-admin/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-admin/README.md b/sdk/keyvault/keyvault-admin/README.md deleted file mode 100644 index 70d49e6c2d78..000000000000 --- a/sdk/keyvault/keyvault-admin/README.md +++ /dev/null @@ -1,160 +0,0 @@ -# Azure Key Vault Administration client library for JavaScript - -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 package `@azure/keyvault-admin` provides support for administrative Key Vault tasks such as full backup / restore and key-level role-based access control (RBAC). - -> Note: The Administration library only works with [Azure Key Vault Managed HSM][managedhsm] - functions targeting a Key Vault will fail. -> -> Note: This package cannot be used in the browser due to Azure Key Vault service limitations, please refer to [this document](https://github.com/Azure/azure-sdk-for-js/blob/main/samples/cors/ts/README.md) for guidance. - -Key links: - -- [Source code][package-gh] -- [Package (npm)][package-npm] -- [API Reference Documentation][docs] -- [Product documentation][docs-service] -- [Samples][samples] - -## Getting started - -### Install the package - -Install the Azure Key Vault administration client library for JavaScript and TypeScript with [NPM][npm]: - -```PowerShell -npm install @azure/keyvault-admin -``` - -### 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][compiler-options] for more information. - -### 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 [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]. - -## Authenticate the client - -In order to interact with the Azure Key Vault service, you will need to create an instance of either the [`KeyVaultAccessControlClient`](#create-keyvaultaccesscontrolclient) class or the [`KeyVaultBackupClient`](#create-keyvaultbackupclient) class, as well as a **vault url** (which you may see as "DNS Name" in the Azure Portal) 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]. - -### Create KeyVaultAccessControlClient - -Once you've authenticated with [the authentication method that suits you best][default_azure_credential], you can create a `KeyVaultAccessControlClient` as follows, substituting in your Managed HSM URL in the constructor: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyVaultAccessControlClient } = require("@azure/keyvault-admin"); - -const credentials = new DefaultAzureCredential(); - -const client = new KeyVaultAccessControlClient(``, credentials); -``` - -### Create KeyVaultBackupClient - -Once you've authenticated with [the authentication method that suits you best][default_azure_credential], you can create a `KeyVaultBackupClient` as follows, substituting in your Managed HSM URL in the constructor: - -```javascript -const { DefaultAzureCredential } = require("@azure/identity"); -const { KeyVaultBackupClient } = require("@azure/keyvault-admin"); - -const credentials = new DefaultAzureCredential(); - -const client = new KeyVaultBackupClient(``, credentials); -``` - -## Key concepts - -### KeyVaultRoleDefinition - -A Role Definition is a collection of permissions. A role definition defines the operations that can be performed, such as read, write, and delete. It can also define the operations that are excluded from allowed operations. - -Role definitions can be listed and specified as part of a `KeyVaultRoleAssignment`. - -### KeyVaultRoleAssignment - -A Role Assignment is the association of a Role Definition to a service principal. They can be created, listed, fetched individually, and deleted. - -### KeyVaultAccessControlClient - -A `KeyVaultAccessControlClient` provides operations allowing for management of Role Definitions (instances of `KeyVaultRoleDefinition`) and Role Assignments (instances of `KeyVaultRoleAssignment`). - -### KeyVaultBackupClient - -A `KeyVaultBackupClient` provides operations for performing full key backups, full key restores, and selective key restores. - -### Long running operations - -The operations done by the `KeyVaultBackupClient` may take as much time as needed by the Azure resources, requiring a client layer to keep track, serialize, and resume the operations through the lifecycle of the programs that wait for them to finish. This is done via a common abstraction through the package [@azure/core-lro][core-lro]. - -The `KeyVaultBackupClient` offers three methods that execute long running operations: - -- `beginBackup`, starts generating a backup of an Azure Key Vault Managed HSM on the specified Storage Blob account. -- `beginRestore`, starts restoring all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. -- `beginSelectiveRestore`, starts restoring all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder. - -The methods that begin long running operations return a poller that allows you to wait indefinitely until the operation is complete. More information is available in the examples below. - -## Examples - -We have samples both in JavaScript and TypeScript that show the access control and backup/restore features in this package. Please follow the corresponding readmes for detailed steps to run the samples. - -- [Readme for JavaScript samples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/javascript/README.md) -- [Readme for TypeScript samples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/typescript/README.md) - -## Troubleshooting - -See our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/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 Administration Samples (JavaScript)](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/samples/v4/javascript) -- [Key Vault Administration Samples (TypeScript)](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/samples/v4/typescript) -- [Key Vault Administration Test Cases](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/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. - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fkeyvault%2Fkeyvault-admin%2FREADME.png) - - - -[compiler-options]: https://www.typescriptlang.org/docs/handbook/compiler-options.html -[core-lro]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/core-lro -[docs-service]: https://azure.microsoft.com/services/key-vault/ -[docs]: https://docs.microsoft.com/javascript/api/@azure/keyvault-admin -[managedhsm]: https://docs.microsoft.com/azure/key-vault/managed-hsm/overview -[npm]: https://www.npmjs.com/ -[package-gh]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin -[package-npm]: https://www.npmjs.com/package/@azure/keyvault-admin -[samples]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/samples -[azure_keyvault_mhsm]: https://docs.microsoft.com/azure/key-vault/managed-hsm/overview -[azure_keyvault_mhsm_cli]: https://docs.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://docs.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 diff --git a/sdk/keyvault/keyvault-admin/TROUBLESHOOTING.md b/sdk/keyvault/keyvault-admin/TROUBLESHOOTING.md deleted file mode 100644 index 3264bfff8bd0..000000000000 --- a/sdk/keyvault/keyvault-admin/TROUBLESHOOTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# Troubleshooting Azure Key Vault Administration 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-admin/api-extractor.json b/sdk/keyvault/keyvault-admin/api-extractor.json deleted file mode 100644 index 6af4b01fadc7..000000000000 --- a/sdk/keyvault/keyvault-admin/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-admin.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-admin/assets.json b/sdk/keyvault/keyvault-admin/assets.json deleted file mode 100644 index 662129f1027f..000000000000 --- a/sdk/keyvault/keyvault-admin/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "js", - "TagPrefix": "js/keyvault/keyvault-admin", - "Tag": "js/keyvault/keyvault-admin_4b469d86ad" -} diff --git a/sdk/keyvault/keyvault-admin/eslint.config.mjs b/sdk/keyvault/keyvault-admin/eslint.config.mjs deleted file mode 100644 index 9d853f7251be..000000000000 --- a/sdk/keyvault/keyvault-admin/eslint.config.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import azsdkEslint from "@azure/eslint-plugin-azure-sdk"; - -export default [ - { ignores: ["src/generated"] }, - ...azsdkEslint.configs.recommended, - { - rules: { - "@azure/azure-sdk/ts-package-json-module": "warn", - "@typescript-eslint/no-this-alias": "off", - "no-use-before-define": "warn", - }, - }, -]; diff --git a/sdk/keyvault/keyvault-admin/package.json b/sdk/keyvault/keyvault-admin/package.json deleted file mode 100644 index 90c9e5e2387a..000000000000 --- a/sdk/keyvault/keyvault-admin/package.json +++ /dev/null @@ -1,147 +0,0 @@ -{ - "name": "@azure/keyvault-admin", - "sdk-type": "client", - "author": "Microsoft Corporation", - "version": "4.6.1", - "license": "MIT", - "description": "Isomorphic client library for Azure KeyVault's administrative functions.", - "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/README.md", - "repository": "github:Azure/azure-sdk-for-js", - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault", - "backup", - "restore", - "access", - "role" - ], - "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" - ], - "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 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 vendored cross-env TEST_MODE=live dev-tool run test:vitest --no-test-proxy", - "lint": "eslint package.json api-extractor.json src", - "lint:fix": "eslint package.json src --fix --fix-type [problem,suggestion]", - "pack": "npm pack 2>&1", - "test": "npm run build:test && npm run unit-test", - "test:browser": "echo Skipped", - "test:node": "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" - }, - "//metadata": { - "constantPaths": [ - { - "path": "src/generated/keyVaultClientContext.ts", - "prefix": "packageDetails" - }, - { - "path": "src/constants.ts", - "prefix": "SDK_VERSION" - }, - { - "path": "swagger/README.md", - "prefix": "package-version" - } - ] - }, - "//sampleConfiguration": { - "productName": "Azure Key Vault Administration", - "productSlugs": [ - "azure", - "azure-key-vault" - ], - "requiredResources": { - "Azure Key Vault": "https://docs.microsoft.com/azure/key-vault/quick-create-portal" - }, - "customSnippets": { - "prerequisites": "samples-dev/snippets/_prerequisites.md" - }, - "skipFolder": true - }, - "sideEffects": false, - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.3.0", - "@azure/core-client": "^1.0.0", - "@azure/core-lro": "^2.2.0", - "@azure/core-paging": "^1.1.1", - "@azure/core-rest-pipeline": "^1.1.0", - "@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.0.1", - "@azure/keyvault-keys": "^4.2.1", - "@types/node": "^18.0.0", - "@vitest/browser": "^2.0.5", - "@vitest/coverage-istanbul": "^2.0.5", - "dotenv": "^16.0.0", - "eslint": "^9.9.0", - "playwright": "^1.46.0", - "typescript": "~5.6.2", - "vitest": "^2.0.5" - }, - "type": "module", - "tshy": { - "exports": { - "./package.json": "./package.json", - ".": "./src/index.ts" - }, - "dialects": [ - "esm", - "commonjs" - ], - "selfLink": false - }, - "exports": { - "./package.json": "./package.json", - ".": { - "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-admin/platform-matrix.json b/sdk/keyvault/keyvault-admin/platform-matrix.json deleted file mode 100644 index 995568db56c4..000000000000 --- a/sdk/keyvault/keyvault-admin/platform-matrix.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": [ - { - "Agent": { - "ubuntu-20.04_ManagedHSM": { - "OSVmImage": "env:LINUXVMIMAGE", - "Pool": "env:LINUXPOOL", - "ArmTemplateParameters": "@{ enableHsm = $true }" - } - }, - "Versions": { - "18.x": { - "NodeTestVersion": "18.x" - }, - "20.x": { - "NodeTestVersion": "20.x" - } - }, - "TestType": "node" - } - ] -} diff --git a/sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md b/sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md deleted file mode 100644 index 7c94bc9858b2..000000000000 --- a/sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md +++ /dev/null @@ -1,300 +0,0 @@ -## API Report File for "@azure/keyvault-admin" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts - -import type { CommonClientOptions } from '@azure/core-client'; -import type { OperationOptions } from '@azure/core-client'; -import type { PagedAsyncIterableIterator } from '@azure/core-paging'; -import type { PollerLike } from '@azure/core-lro'; -import type { PollOperationState } from '@azure/core-lro'; -import type { TokenCredential } from '@azure/core-auth'; - -// @public -export interface AccessControlClientOptions extends CommonClientOptions { - disableChallengeResourceVerification?: boolean; - serviceVersion?: SUPPORTED_API_VERSIONS; -} - -// @public -export interface BooleanKeyVaultSetting extends KeyVaultSetting { - kind: "boolean"; - value: boolean; -} - -// @public -export interface CreateRoleAssignmentOptions extends OperationOptions { -} - -// @public -export interface DeleteRoleAssignmentOptions extends OperationOptions { -} - -// @public -export interface DeleteRoleDefinitionOptions extends OperationOptions { -} - -// @public -export interface GetRoleAssignmentOptions extends OperationOptions { -} - -// @public -export interface GetRoleDefinitionOptions extends OperationOptions { -} - -// @public -export interface GetSettingOptions extends OperationOptions { -} - -// @public -export function isBooleanSetting(setting: KeyVaultSetting): setting is BooleanKeyVaultSetting; - -// @public -export class KeyVaultAccessControlClient { - constructor(vaultUrl: string, credential: TokenCredential, options?: AccessControlClientOptions); - createRoleAssignment(roleScope: KeyVaultRoleScope, name: string, roleDefinitionId: string, principalId: string, options?: CreateRoleAssignmentOptions): Promise; - deleteRoleAssignment(roleScope: KeyVaultRoleScope, name: string, options?: DeleteRoleAssignmentOptions): Promise; - deleteRoleDefinition(roleScope: KeyVaultRoleScope, name: string, options?: DeleteRoleDefinitionOptions): Promise; - getRoleAssignment(roleScope: KeyVaultRoleScope, name: string, options?: GetRoleAssignmentOptions): Promise; - getRoleDefinition(roleScope: KeyVaultRoleScope, name: string, options?: GetRoleDefinitionOptions): Promise; - listRoleAssignments(roleScope: KeyVaultRoleScope, options?: ListRoleAssignmentsOptions): PagedAsyncIterableIterator; - listRoleDefinitions(roleScope: KeyVaultRoleScope, options?: ListRoleDefinitionsOptions): PagedAsyncIterableIterator; - setRoleDefinition(roleScope: KeyVaultRoleScope, options?: SetRoleDefinitionOptions): Promise; - readonly vaultUrl: string; -} - -// @public -export interface KeyVaultAdminPollOperationState extends PollOperationState { - endTime?: Date; - jobId?: string; - startTime?: Date; - status?: string; - statusDetails?: string; -} - -// @public -export class KeyVaultBackupClient { - constructor(vaultUrl: string, credential: TokenCredential, options?: KeyVaultBackupClientOptions); - beginBackup(blobStorageUri: string, sasToken: string, options?: KeyVaultBeginBackupOptions): Promise>; - beginBackup(blobStorageUri: string, options?: KeyVaultBeginBackupOptions): Promise>; - beginRestore(folderUri: string, sasToken: string, options?: KeyVaultBeginRestoreOptions): Promise>; - beginRestore(folderUri: string, options?: KeyVaultBeginRestoreOptions): Promise>; - beginSelectiveKeyRestore(keyName: string, folderUri: string, sasToken: string, options?: KeyVaultBeginSelectiveKeyRestoreOptions): Promise>; - beginSelectiveKeyRestore(keyName: string, folderUri: string, options?: KeyVaultBeginSelectiveKeyRestoreOptions): Promise>; - readonly vaultUrl: string; -} - -// @public -export interface KeyVaultBackupClientOptions extends CommonClientOptions { - disableChallengeResourceVerification?: boolean; - serviceVersion?: SUPPORTED_API_VERSIONS; -} - -// @public -export type KeyVaultBackupOperationState = KeyVaultAdminPollOperationState; - -// @public -export interface KeyVaultBackupPollerOptions extends OperationOptions { - intervalInMs?: number; - resumeFrom?: string; -} - -// @public -export interface KeyVaultBackupResult { - endTime?: Date; - folderUri?: string; - startTime: Date; -} - -// @public -export interface KeyVaultBeginBackupOptions extends KeyVaultBackupPollerOptions { -} - -// @public -export interface KeyVaultBeginRestoreOptions extends KeyVaultBackupPollerOptions { -} - -// @public -export interface KeyVaultBeginSelectiveKeyRestoreOptions extends KeyVaultBackupPollerOptions { -} - -// @public -export type KeyVaultDataAction = string; - -// @public -export interface KeyVaultPermission { - actions?: string[]; - dataActions?: KeyVaultDataAction[]; - notActions?: string[]; - notDataActions?: KeyVaultDataAction[]; -} - -// @public -export interface KeyVaultRestoreOperationState extends KeyVaultAdminPollOperationState { -} - -// @public -export interface KeyVaultRestoreResult { - endTime?: Date; - startTime: Date; -} - -// @public -export interface KeyVaultRoleAssignment { - readonly id: string; - readonly kind: string; - readonly name: string; - properties: KeyVaultRoleAssignmentProperties; -} - -// @public -export interface KeyVaultRoleAssignmentProperties { - principalId: string; - roleDefinitionId: string; - scope?: KeyVaultRoleScope; -} - -// @public -export interface KeyVaultRoleDefinition { - assignableScopes: string[]; - description: string; - readonly id: string; - readonly kind: string; - readonly name: string; - permissions: KeyVaultPermission[]; - roleName: string; - roleType: string; -} - -// @public -export type KeyVaultRoleScope = string; - -// @public -export interface KeyVaultSelectiveKeyRestoreOperationState extends KeyVaultAdminPollOperationState { -} - -// @public -export interface KeyVaultSelectiveKeyRestoreResult { - endTime?: Date; - startTime: Date; -} - -// @public -export interface KeyVaultSetting { - kind?: string; - name: string; - value: unknown; -} - -// @public -export class KeyVaultSettingsClient { - constructor(vaultUrl: string, credential: TokenCredential, options?: SettingsClientOptions); - getSetting(settingName: string, options?: GetSettingOptions): Promise; - getSettings(options?: ListSettingsOptions): Promise; - updateSetting(setting: KeyVaultSetting, options?: UpdateSettingOptions): Promise; - readonly vaultUrl: string; -} - -// @public -export enum KnownKeyVaultDataAction { - BackupHsmKeys = "Microsoft.KeyVault/managedHsm/keys/backup/action", - CreateHsmKey = "Microsoft.KeyVault/managedHsm/keys/create", - DecryptHsmKey = "Microsoft.KeyVault/managedHsm/keys/decrypt/action", - DeleteHsmKey = "Microsoft.KeyVault/managedHsm/keys/delete", - DeleteRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/delete/action", - DeleteRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/delete/action", - DownloadHsmSecurityDomain = "Microsoft.KeyVault/managedHsm/securitydomain/download/action", - DownloadHsmSecurityDomainStatus = "Microsoft.KeyVault/managedHsm/securitydomain/download/read", - EncryptHsmKey = "Microsoft.KeyVault/managedHsm/keys/encrypt/action", - ExportHsmKey = "Microsoft.KeyVault/managedHsm/keys/export/action", - GetRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/read/action", - ImportHsmKey = "Microsoft.KeyVault/managedHsm/keys/import/action", - PurgeDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/delete", - RandomNumbersGenerate = "Microsoft.KeyVault/managedHsm/rng/action", - ReadDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/read/action", - ReadHsmBackupStatus = "Microsoft.KeyVault/managedHsm/backup/status/action", - ReadHsmKey = "Microsoft.KeyVault/managedHsm/keys/read/action", - ReadHsmRestoreStatus = "Microsoft.KeyVault/managedHsm/restore/status/action", - ReadHsmSecurityDomainStatus = "Microsoft.KeyVault/managedHsm/securitydomain/upload/read", - ReadHsmSecurityDomainTransferKey = "Microsoft.KeyVault/managedHsm/securitydomain/transferkey/read", - ReadRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/read/action", - RecoverDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/recover/action", - ReleaseKey = "Microsoft.KeyVault/managedHsm/keys/release/action", - RestoreHsmKeys = "Microsoft.KeyVault/managedHsm/keys/restore/action", - SignHsmKey = "Microsoft.KeyVault/managedHsm/keys/sign/action", - StartHsmBackup = "Microsoft.KeyVault/managedHsm/backup/start/action", - StartHsmRestore = "Microsoft.KeyVault/managedHsm/restore/start/action", - UnwrapHsmKey = "Microsoft.KeyVault/managedHsm/keys/unwrap/action", - UploadHsmSecurityDomain = "Microsoft.KeyVault/managedHsm/securitydomain/upload/action", - VerifyHsmKey = "Microsoft.KeyVault/managedHsm/keys/verify/action", - WrapHsmKey = "Microsoft.KeyVault/managedHsm/keys/wrap/action", - WriteHsmKey = "Microsoft.KeyVault/managedHsm/keys/write/action", - WriteRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/write/action", - WriteRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/write/action" -} - -// @public -export enum KnownKeyVaultRoleScope { - Global = "/", - Keys = "/keys" -} - -// @public -export const LATEST_API_VERSION = "7.5"; - -// @public -export interface ListRoleAssignmentsOptions extends OperationOptions { -} - -// @public -export interface ListRoleAssignmentsPageSettings { - continuationToken?: string; -} - -// @public -export interface ListRoleDefinitionsOptions extends OperationOptions { -} - -// @public -export interface ListRoleDefinitionsPageSettings { - continuationToken?: string; -} - -// @public -export interface ListSettingsOptions extends OperationOptions { -} - -// @public -export interface ListSettingsResponse { - settings: KeyVaultSetting[]; -} - -// @public -export const SDK_VERSION: string; - -// @public -export interface SetRoleDefinitionOptions extends OperationOptions { - assignableScopes?: KeyVaultRoleScope[]; - description?: string; - permissions?: KeyVaultPermission[]; - roleDefinitionName?: string; - roleName?: string; -} - -// @public -export interface SettingsClientOptions extends CommonClientOptions { - disableChallengeResourceVerification?: boolean; - serviceVersion?: SUPPORTED_API_VERSIONS; -} - -// @public -export type SUPPORTED_API_VERSIONS = "7.2" | "7.3" | "7.4" | "7.5"; - -// @public -export interface UpdateSettingOptions extends OperationOptions { -} - -// (No @packageDocumentation comment for this package) - -``` diff --git a/sdk/keyvault/keyvault-admin/sample.env b/sdk/keyvault/keyvault-admin/sample.env deleted file mode 100644 index 38ebf9042796..000000000000 --- a/sdk/keyvault/keyvault-admin/sample.env +++ /dev/null @@ -1,23 +0,0 @@ -# The name of the Managed HSM Key Vault to use in the samples. -# At the moment only Azure Managed HSM supports administration operations. -AZURE_MANAGEDHSM_URI= - -# URI of the Blob Storage instance, with the name of the container where the Key Vault backups will be generated. -BLOB_STORAGE_URI= - -# The SAS token to use for authentication to Azure Blob Storage. -BLOB_STORAGE_SAS_TOKEN= - -# The name of the Azure Storage Blob container where backups will be stored. -BLOB_CONTAINER_NAME= - -# Object ID of the application, tenant or principal to whom the role will be assigned to. -CLIENT_OBJECT_ID= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= diff --git a/sdk/keyvault/keyvault-admin/samples-dev/accessControlHelloWorld.ts b/sdk/keyvault/keyvault-admin/samples-dev/accessControlHelloWorld.ts deleted file mode 100644 index 3c32a948747e..000000000000 --- a/sdk/keyvault/keyvault-admin/samples-dev/accessControlHelloWorld.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an AccessControlClient to list, create, and assign roles to users. - */ - -import { - KeyVaultAccessControlClient, - KeyVaultPermission, - KnownKeyVaultDataAction, - KnownKeyVaultRoleScope, -} from "@azure/keyvault-admin"; -import { DefaultAzureCredential } from "@azure/identity"; -import { randomUUID } from "@azure/core-util"; - -// 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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultAccessControlClient(url, credential); - - for await (const roleAssignment of client.listRoleAssignments("/")) { - console.log(roleAssignment); - } - - const globalScope = KnownKeyVaultRoleScope.Global; - const roleDefinitionName = randomUUID(); - const permissions: KeyVaultPermission[] = [ - { - dataActions: [ - KnownKeyVaultDataAction.StartHsmBackup, - KnownKeyVaultDataAction.StartHsmRestore, - ], - }, - ]; - let roleDefinition = await client.setRoleDefinition(globalScope, { - roleDefinitionName, - roleName: "Backup Manager", - permissions, - description: "Allow backup actions", - }); - console.log(roleDefinition); - - // This sample uses a custom role but you may assign one of the many built-in roles. - // Please refer to https://docs.microsoft.com/azure/key-vault/managed-hsm/built-in-roles for more information. - const roleAssignmentName = randomUUID(); - const clientObjectId = process.env["CLIENT_OBJECT_ID"]; - if (!clientObjectId) { - throw new Error("Missing environment variable CLIENT_OBJECT_ID."); - } - let assignment = await client.createRoleAssignment( - globalScope, - roleAssignmentName, - roleDefinition.id, - clientObjectId, - ); - console.log(assignment); - - assignment = await client.getRoleAssignment(globalScope, roleAssignmentName); - console.log(assignment); - - await client.deleteRoleAssignment(globalScope, roleAssignmentName); - - await client.deleteRoleDefinition(globalScope, roleDefinition.name); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples-dev/backupRestoreHelloWorld.ts b/sdk/keyvault/keyvault-admin/samples-dev/backupRestoreHelloWorld.ts deleted file mode 100644 index 703496fc3e0a..000000000000 --- a/sdk/keyvault/keyvault-admin/samples-dev/backupRestoreHelloWorld.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and fully restore an Azure Key Vault Managed HSM using Azure Storage Blob. - */ - -import { KeyVaultBackupClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const restorePoller = await client.beginRestore(backupResult.folderUri!, sasToken); - await restorePoller.pollUntilDone(); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples-dev/backupSelectiveKeyRestore.ts b/sdk/keyvault/keyvault-admin/samples-dev/backupSelectiveKeyRestore.ts deleted file mode 100644 index 75112c52f244..000000000000 --- a/sdk/keyvault/keyvault-admin/samples-dev/backupSelectiveKeyRestore.ts +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and restore a specific key in an Azure Key Vault Managed HSM using Azure Storage Blob. - */ - -import { KeyVaultBackupClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const keyClient = new KeyClient(url, credential); - const keyName = "key-name"; - const key = await keyClient.createRsaKey(keyName); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - console.log("backupResult", backupResult); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const selectiveKeyRestorePoller = await client.beginSelectiveKeyRestore( - key.name, - backupResult.folderUri!, - sasToken, - ); - const restoreResult = await selectiveKeyRestorePoller.pollUntilDone(); - console.log("restoreResult", restoreResult); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples-dev/snippets/_prerequisites.md b/sdk/keyvault/keyvault-admin/samples-dev/snippets/_prerequisites.md deleted file mode 100644 index a0d2e3e74555..000000000000 --- a/sdk/keyvault/keyvault-admin/samples-dev/snippets/_prerequisites.md +++ /dev/null @@ -1,3 +0,0 @@ -To quickly create the needed Key Vault Managed HSM 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) \ No newline at end of file diff --git a/sdk/keyvault/keyvault-admin/samples-dev/updateSettings.ts b/sdk/keyvault/keyvault-admin/samples-dev/updateSettings.ts deleted file mode 100644 index 77798ae06eb2..000000000000 --- a/sdk/keyvault/keyvault-admin/samples-dev/updateSettings.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Demonstrates how to retrieve and update account settings for Managed HSM. - */ - -import { KeyVaultSettingsClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultSettingsClient(url, credential); - - const setting = await client.getSetting("AllowKeyManagementOperationsThroughARM"); - - // You can update the setting's value and then pass it back to updateSetting: - setting.value = true; - await client.updateSetting(setting); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/README.md b/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/README.md deleted file mode 100644 index 9e34ff4e032c..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/README.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -page_type: sample -languages: - - javascript -products: - - azure - - azure-key-vault -urlFragment: keyvault-admin-javascript-beta ---- - -# Azure Key Vault Administration client library samples for JavaScript (Beta) - -These sample programs show how to use the JavaScript client libraries for Azure Key Vault Administration in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| [accessControlHelloWorld.js][accesscontrolhelloworld] | Uses an AccessControlClient to list, create, and assign roles to users. | -| [backupRestoreHelloWorld.js][backuprestorehelloworld] | Uses a BackupClient to backup and fully restore an Azure Key Vault Managed HSM using Azure Storage Blob. | -| [backupSelectiveKeyRestore.js][backupselectivekeyrestore] | Uses a BackupClient to backup and restore a specific key in an Azure Key Vault Managed HSM using Azure Storage Blob. | -| [updateSettings.js][updatesettings] | Demonstrates how to retrieve and update account settings for Managed HSM. | - -## 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 Managed HSM 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) - -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 accessControlHelloWorld.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 AZURE_MANAGEDHSM_URI="" CLIENT_OBJECT_ID="" node accessControlHelloWorld.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[accesscontrolhelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/accessControlHelloWorld.js -[backuprestorehelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupRestoreHelloWorld.js -[backupselectivekeyrestore]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupSelectiveKeyRestore.js -[updatesettings]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/updateSettings.js -[apiref]: https://docs.microsoft.com/javascript/api/@azure/keyvault-admin -[freesub]: https://azure.microsoft.com/free/ -[createinstance_azurekeyvault]: https://docs.microsoft.com/azure/key-vault/quick-create-portal -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/README.md diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/accessControlHelloWorld.js b/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/accessControlHelloWorld.js deleted file mode 100644 index 068c2feb009a..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/accessControlHelloWorld.js +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an AccessControlClient to list, create, and assign roles to users. - */ - -const { - KeyVaultAccessControlClient, - KnownKeyVaultDataAction, - KnownKeyVaultRoleScope, -} = require("@azure/keyvault-admin"); -const { DefaultAzureCredential } = require("@azure/identity"); -const uuid = require("uuid"); - -// 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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultAccessControlClient(url, credential); - - for await (const roleAssignment of client.listRoleAssignments("/")) { - console.log(roleAssignment); - } - - const globalScope = KnownKeyVaultRoleScope.Global; - const roleDefinitionName = uuid.v4(); - const permissions = [ - { - dataActions: [ - KnownKeyVaultDataAction.StartHsmBackup, - KnownKeyVaultDataAction.StartHsmRestore, - ], - }, - ]; - let roleDefinition = await client.setRoleDefinition(globalScope, { - roleDefinitionName, - roleName: "Backup Manager", - permissions, - description: "Allow backup actions", - }); - console.log(roleDefinition); - - // This sample uses a custom role but you may assign one of the many built-in roles. - // Please refer to https://docs.microsoft.com/azure/key-vault/managed-hsm/built-in-roles for more information. - const roleAssignmentName = uuid.v4(); - const clientObjectId = process.env["CLIENT_OBJECT_ID"]; - if (!clientObjectId) { - throw new Error("Missing environment variable CLIENT_OBJECT_ID."); - } - let assignment = await client.createRoleAssignment( - globalScope, - roleAssignmentName, - roleDefinition.id, - clientObjectId - ); - console.log(assignment); - - assignment = await client.getRoleAssignment(globalScope, roleAssignmentName); - console.log(assignment); - - await client.deleteRoleAssignment(globalScope, roleAssignmentName); - - await client.deleteRoleDefinition(globalScope, roleDefinition.name); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupRestoreHelloWorld.js b/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupRestoreHelloWorld.js deleted file mode 100644 index 3bb9bfd64c15..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupRestoreHelloWorld.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and fully restore an Azure Key Vault Managed HSM using Azure Storage Blob. - */ - -const { KeyVaultBackupClient } = require("@azure/keyvault-admin"); -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const restorePoller = await client.beginRestore(backupResult.folderUri, sasToken); - await restorePoller.pollUntilDone(); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupSelectiveKeyRestore.js b/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupSelectiveKeyRestore.js deleted file mode 100644 index 9f48796c5c1e..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/backupSelectiveKeyRestore.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and restore a specific key in an Azure Key Vault Managed HSM using Azure Storage Blob. - */ - -const { KeyVaultBackupClient } = require("@azure/keyvault-admin"); -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const keyClient = new KeyClient(url, credential); - const keyName = "key-name"; - const key = await keyClient.createRsaKey(keyName); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - console.log("backupResult", backupResult); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const selectiveKeyRestorePoller = await client.beginSelectiveKeyRestore( - key.name, - backupResult.folderUri, - sasToken - ); - const restoreResult = await selectiveKeyRestorePoller.pollUntilDone(); - console.log("restoreResult", restoreResult); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/package.json b/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/package.json deleted file mode 100644 index 4c2624e5ff93..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@azure-samples/keyvault-admin-js-beta", - "private": true, - "version": "1.0.0", - "description": "Azure Key Vault Administration client library samples for JavaScript (Beta)", - "engines": { - "node": ">=18.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/keyvault/keyvault-admin" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault", - "backup", - "restore", - "access", - "role" - ], - "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-admin", - "dependencies": { - "@azure/keyvault-admin": "next", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "uuid": "^8.3.0", - "@azure/keyvault-keys": "^4.2.1" - } -} diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/sample.env b/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/sample.env deleted file mode 100644 index 38ebf9042796..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/sample.env +++ /dev/null @@ -1,23 +0,0 @@ -# The name of the Managed HSM Key Vault to use in the samples. -# At the moment only Azure Managed HSM supports administration operations. -AZURE_MANAGEDHSM_URI= - -# URI of the Blob Storage instance, with the name of the container where the Key Vault backups will be generated. -BLOB_STORAGE_URI= - -# The SAS token to use for authentication to Azure Blob Storage. -BLOB_STORAGE_SAS_TOKEN= - -# The name of the Azure Storage Blob container where backups will be stored. -BLOB_CONTAINER_NAME= - -# Object ID of the application, tenant or principal to whom the role will be assigned to. -CLIENT_OBJECT_ID= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/updateSettings.js b/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/updateSettings.js deleted file mode 100644 index 8435ae398de6..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/javascript/updateSettings.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Demonstrates how to retrieve and update account settings for Managed HSM. - */ - -const { KeyVaultSettingsClient } = require("@azure/keyvault-admin"); -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultSettingsClient(url, credential); - - const setting = await client.getSetting("AllowKeyManagementOperationsThroughARM"); - - // You can update the setting's value and then pass it back to updateSetting: - setting.value = true; - await client.updateSetting(setting); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/README.md b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/README.md deleted file mode 100644 index 4b7e98677d08..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/README.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -page_type: sample -languages: - - typescript -products: - - azure - - azure-key-vault -urlFragment: keyvault-admin-typescript-beta ---- - -# Azure Key Vault Administration client library samples for TypeScript (Beta) - -These sample programs show how to use the TypeScript client libraries for Azure Key Vault Administration in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| [accessControlHelloWorld.ts][accesscontrolhelloworld] | Uses an AccessControlClient to list, create, and assign roles to users. | -| [backupRestoreHelloWorld.ts][backuprestorehelloworld] | Uses a BackupClient to backup and fully restore an Azure Key Vault Managed HSM using Azure Storage Blob. | -| [backupSelectiveKeyRestore.ts][backupselectivekeyrestore] | Uses a BackupClient to backup and restore a specific key in an Azure Key Vault Managed HSM using Azure Storage Blob. | -| [updateSettings.ts][updatesettings] | Demonstrates how to retrieve and update account settings for Managed HSM. | - -## 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 Managed HSM 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) - -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/accessControlHelloWorld.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 AZURE_MANAGEDHSM_URI="" CLIENT_OBJECT_ID="" node dist/accessControlHelloWorld.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[accesscontrolhelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/accessControlHelloWorld.ts -[backuprestorehelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupRestoreHelloWorld.ts -[backupselectivekeyrestore]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupSelectiveKeyRestore.ts -[updatesettings]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/updateSettings.ts -[apiref]: https://docs.microsoft.com/javascript/api/@azure/keyvault-admin -[freesub]: https://azure.microsoft.com/free/ -[createinstance_azurekeyvault]: https://docs.microsoft.com/azure/key-vault/quick-create-portal -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/package.json b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/package.json deleted file mode 100644 index 11579144dc2f..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "@azure-samples/keyvault-admin-ts-beta", - "private": true, - "version": "1.0.0", - "description": "Azure Key Vault Administration client library samples for TypeScript (Beta)", - "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-admin" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault", - "backup", - "restore", - "access", - "role" - ], - "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-admin", - "dependencies": { - "@azure/keyvault-admin": "next", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "uuid": "^8.3.0", - "@azure/keyvault-keys": "^4.2.1" - }, - "devDependencies": { - "@types/uuid": "^8.0.0", - "@types/node": "^18.0.0", - "typescript": "~5.6.2", - "rimraf": "latest" - } -} diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/sample.env b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/sample.env deleted file mode 100644 index 38ebf9042796..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/sample.env +++ /dev/null @@ -1,23 +0,0 @@ -# The name of the Managed HSM Key Vault to use in the samples. -# At the moment only Azure Managed HSM supports administration operations. -AZURE_MANAGEDHSM_URI= - -# URI of the Blob Storage instance, with the name of the container where the Key Vault backups will be generated. -BLOB_STORAGE_URI= - -# The SAS token to use for authentication to Azure Blob Storage. -BLOB_STORAGE_SAS_TOKEN= - -# The name of the Azure Storage Blob container where backups will be stored. -BLOB_CONTAINER_NAME= - -# Object ID of the application, tenant or principal to whom the role will be assigned to. -CLIENT_OBJECT_ID= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/accessControlHelloWorld.ts b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/accessControlHelloWorld.ts deleted file mode 100644 index 1f272982399d..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/accessControlHelloWorld.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an AccessControlClient to list, create, and assign roles to users. - */ - -import { - KeyVaultAccessControlClient, - KeyVaultPermission, - KnownKeyVaultDataAction, - KnownKeyVaultRoleScope, -} from "@azure/keyvault-admin"; -import { DefaultAzureCredential } from "@azure/identity"; -import * as uuid from "uuid"; - -// 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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultAccessControlClient(url, credential); - - for await (const roleAssignment of client.listRoleAssignments("/")) { - console.log(roleAssignment); - } - - const globalScope = KnownKeyVaultRoleScope.Global; - const roleDefinitionName = uuid.v4(); - const permissions: KeyVaultPermission[] = [ - { - dataActions: [ - KnownKeyVaultDataAction.StartHsmBackup, - KnownKeyVaultDataAction.StartHsmRestore, - ], - }, - ]; - let roleDefinition = await client.setRoleDefinition(globalScope, { - roleDefinitionName, - roleName: "Backup Manager", - permissions, - description: "Allow backup actions", - }); - console.log(roleDefinition); - - // This sample uses a custom role but you may assign one of the many built-in roles. - // Please refer to https://docs.microsoft.com/azure/key-vault/managed-hsm/built-in-roles for more information. - const roleAssignmentName = uuid.v4(); - const clientObjectId = process.env["CLIENT_OBJECT_ID"]; - if (!clientObjectId) { - throw new Error("Missing environment variable CLIENT_OBJECT_ID."); - } - let assignment = await client.createRoleAssignment( - globalScope, - roleAssignmentName, - roleDefinition.id, - clientObjectId - ); - console.log(assignment); - - assignment = await client.getRoleAssignment(globalScope, roleAssignmentName); - console.log(assignment); - - await client.deleteRoleAssignment(globalScope, roleAssignmentName); - - await client.deleteRoleDefinition(globalScope, roleDefinition.name); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupRestoreHelloWorld.ts b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupRestoreHelloWorld.ts deleted file mode 100644 index 703496fc3e0a..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupRestoreHelloWorld.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and fully restore an Azure Key Vault Managed HSM using Azure Storage Blob. - */ - -import { KeyVaultBackupClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const restorePoller = await client.beginRestore(backupResult.folderUri!, sasToken); - await restorePoller.pollUntilDone(); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupSelectiveKeyRestore.ts b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupSelectiveKeyRestore.ts deleted file mode 100644 index 045574152431..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/backupSelectiveKeyRestore.ts +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and restore a specific key in an Azure Key Vault Managed HSM using Azure Storage Blob. - */ - -import { KeyVaultBackupClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const keyClient = new KeyClient(url, credential); - const keyName = "key-name"; - const key = await keyClient.createRsaKey(keyName); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - console.log("backupResult", backupResult); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const selectiveKeyRestorePoller = await client.beginSelectiveKeyRestore( - key.name, - backupResult.folderUri!, - sasToken - ); - const restoreResult = await selectiveKeyRestorePoller.pollUntilDone(); - console.log("restoreResult", restoreResult); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/updateSettings.ts b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/updateSettings.ts deleted file mode 100644 index 77798ae06eb2..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/src/updateSettings.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Demonstrates how to retrieve and update account settings for Managed HSM. - */ - -import { KeyVaultSettingsClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultSettingsClient(url, credential); - - const setting = await client.getSetting("AllowKeyManagementOperationsThroughARM"); - - // You can update the setting's value and then pass it back to updateSetting: - setting.value = true; - await client.updateSetting(setting); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/tsconfig.json b/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/tsconfig.json deleted file mode 100644 index 984eed535aa8..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4-beta/typescript/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "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-admin/samples/v4/javascript/README.md b/sdk/keyvault/keyvault-admin/samples/v4/javascript/README.md deleted file mode 100644 index 298507827d32..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/javascript/README.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -page_type: sample -languages: - - javascript -products: - - azure - - azure-key-vault -urlFragment: keyvault-admin-javascript ---- - -# Azure Key Vault Administration client library samples for JavaScript - -These sample programs show how to use the JavaScript client libraries for Azure Key Vault Administration in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -| [accessControlHelloWorld.js][accesscontrolhelloworld] | Uses an AccessControlClient to list, create, and assign roles to users. | -| [backupRestoreHelloWorld.js][backuprestorehelloworld] | Uses a BackupClient to backup and fully restore an Azure Key Vault using Azure Storage Blob. | -| [backupSelectiveKeyRestore.js][backupselectivekeyrestore] | Uses a BackupClient to backup and restore a specific key in Azure Key Vault using Azure Storage Blob. | - -## 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://docs.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 accessControlHelloWorld.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 AZURE_MANAGEDHSM_URI="" CLIENT_OBJECT_ID="" node accessControlHelloWorld.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[accesscontrolhelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/javascript/accessControlHelloWorld.js -[backuprestorehelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupRestoreHelloWorld.js -[backupselectivekeyrestore]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupSelectiveKeyRestore.js -[apiref]: https://docs.microsoft.com/javascript/api/@azure/keyvault-admin -[freesub]: https://azure.microsoft.com/free/ -[createinstance_azurekeyvault]: https://docs.microsoft.com/azure/key-vault/quick-create-portal -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/README.md diff --git a/sdk/keyvault/keyvault-admin/samples/v4/javascript/accessControlHelloWorld.js b/sdk/keyvault/keyvault-admin/samples/v4/javascript/accessControlHelloWorld.js deleted file mode 100644 index 068c2feb009a..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/javascript/accessControlHelloWorld.js +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an AccessControlClient to list, create, and assign roles to users. - */ - -const { - KeyVaultAccessControlClient, - KnownKeyVaultDataAction, - KnownKeyVaultRoleScope, -} = require("@azure/keyvault-admin"); -const { DefaultAzureCredential } = require("@azure/identity"); -const uuid = require("uuid"); - -// 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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultAccessControlClient(url, credential); - - for await (const roleAssignment of client.listRoleAssignments("/")) { - console.log(roleAssignment); - } - - const globalScope = KnownKeyVaultRoleScope.Global; - const roleDefinitionName = uuid.v4(); - const permissions = [ - { - dataActions: [ - KnownKeyVaultDataAction.StartHsmBackup, - KnownKeyVaultDataAction.StartHsmRestore, - ], - }, - ]; - let roleDefinition = await client.setRoleDefinition(globalScope, { - roleDefinitionName, - roleName: "Backup Manager", - permissions, - description: "Allow backup actions", - }); - console.log(roleDefinition); - - // This sample uses a custom role but you may assign one of the many built-in roles. - // Please refer to https://docs.microsoft.com/azure/key-vault/managed-hsm/built-in-roles for more information. - const roleAssignmentName = uuid.v4(); - const clientObjectId = process.env["CLIENT_OBJECT_ID"]; - if (!clientObjectId) { - throw new Error("Missing environment variable CLIENT_OBJECT_ID."); - } - let assignment = await client.createRoleAssignment( - globalScope, - roleAssignmentName, - roleDefinition.id, - clientObjectId - ); - console.log(assignment); - - assignment = await client.getRoleAssignment(globalScope, roleAssignmentName); - console.log(assignment); - - await client.deleteRoleAssignment(globalScope, roleAssignmentName); - - await client.deleteRoleDefinition(globalScope, roleDefinition.name); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupRestoreHelloWorld.js b/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupRestoreHelloWorld.js deleted file mode 100644 index f5d34baed22e..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupRestoreHelloWorld.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and fully restore an Azure Key Vault using Azure Storage Blob. - */ - -const { KeyVaultBackupClient } = require("@azure/keyvault-admin"); -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const restorePoller = await client.beginRestore(backupResult.folderUri, sasToken); - await restorePoller.pollUntilDone(); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupSelectiveKeyRestore.js b/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupSelectiveKeyRestore.js deleted file mode 100644 index 52c064fa2e96..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/javascript/backupSelectiveKeyRestore.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and restore a specific key in Azure Key Vault using Azure Storage Blob. - */ - -const { KeyVaultBackupClient } = require("@azure/keyvault-admin"); -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const keyClient = new KeyClient(url, credential); - const keyName = "key-name"; - const key = await keyClient.createRsaKey(keyName); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - console.log("backupResult", backupResult); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const selectiveKeyRestorePoller = await client.beginSelectiveKeyRestore( - key.name, - backupResult.folderUri, - sasToken - ); - const restoreResult = await selectiveKeyRestorePoller.pollUntilDone(); - console.log("restoreResult", restoreResult); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); - -module.exports = { main }; diff --git a/sdk/keyvault/keyvault-admin/samples/v4/javascript/package.json b/sdk/keyvault/keyvault-admin/samples/v4/javascript/package.json deleted file mode 100644 index e0439ad75169..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/javascript/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@azure-samples/keyvault-admin-js", - "private": true, - "version": "1.0.0", - "description": "Azure Key Vault Administration 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-admin" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault", - "backup", - "restore", - "access", - "role" - ], - "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-admin", - "dependencies": { - "@azure/keyvault-admin": "latest", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "uuid": "^8.3.0", - "@azure/keyvault-keys": "^4.2.1" - } -} diff --git a/sdk/keyvault/keyvault-admin/samples/v4/javascript/sample.env b/sdk/keyvault/keyvault-admin/samples/v4/javascript/sample.env deleted file mode 100644 index 38ebf9042796..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/javascript/sample.env +++ /dev/null @@ -1,23 +0,0 @@ -# The name of the Managed HSM Key Vault to use in the samples. -# At the moment only Azure Managed HSM supports administration operations. -AZURE_MANAGEDHSM_URI= - -# URI of the Blob Storage instance, with the name of the container where the Key Vault backups will be generated. -BLOB_STORAGE_URI= - -# The SAS token to use for authentication to Azure Blob Storage. -BLOB_STORAGE_SAS_TOKEN= - -# The name of the Azure Storage Blob container where backups will be stored. -BLOB_CONTAINER_NAME= - -# Object ID of the application, tenant or principal to whom the role will be assigned to. -CLIENT_OBJECT_ID= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= diff --git a/sdk/keyvault/keyvault-admin/samples/v4/typescript/README.md b/sdk/keyvault/keyvault-admin/samples/v4/typescript/README.md deleted file mode 100644 index abefb5238f79..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/typescript/README.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -page_type: sample -languages: - - typescript -products: - - azure - - azure-key-vault -urlFragment: keyvault-admin-typescript ---- - -# Azure Key Vault Administration client library samples for TypeScript - -These sample programs show how to use the TypeScript client libraries for Azure Key Vault Administration in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -| [accessControlHelloWorld.ts][accesscontrolhelloworld] | Uses an AccessControlClient to list, create, and assign roles to users. | -| [backupRestoreHelloWorld.ts][backuprestorehelloworld] | Uses a BackupClient to backup and fully restore an Azure Key Vault using Azure Storage Blob. | -| [backupSelectiveKeyRestore.ts][backupselectivekeyrestore] | Uses a BackupClient to backup and restore a specific key in Azure Key Vault using Azure Storage Blob. | - -## 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://docs.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/accessControlHelloWorld.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 AZURE_MANAGEDHSM_URI="" CLIENT_OBJECT_ID="" node dist/accessControlHelloWorld.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[accesscontrolhelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/accessControlHelloWorld.ts -[backuprestorehelloworld]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupRestoreHelloWorld.ts -[backupselectivekeyrestore]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupSelectiveKeyRestore.ts -[apiref]: https://docs.microsoft.com/javascript/api/@azure/keyvault-admin -[freesub]: https://azure.microsoft.com/free/ -[createinstance_azurekeyvault]: https://docs.microsoft.com/azure/key-vault/quick-create-portal -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/keyvault/keyvault-admin/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/keyvault/keyvault-admin/samples/v4/typescript/package.json b/sdk/keyvault/keyvault-admin/samples/v4/typescript/package.json deleted file mode 100644 index b81569f8dfc9..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/typescript/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "@azure-samples/keyvault-admin-ts", - "private": true, - "version": "1.0.0", - "description": "Azure Key Vault Administration 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-admin" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic", - "keyvault", - "backup", - "restore", - "access", - "role" - ], - "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-admin", - "dependencies": { - "@azure/keyvault-admin": "latest", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "uuid": "^8.3.0", - "@azure/keyvault-keys": "^4.2.1" - }, - "devDependencies": { - "@types/uuid": "^8.0.0", - "@types/node": "^18.0.0", - "typescript": "~5.6.2", - "rimraf": "latest" - } -} diff --git a/sdk/keyvault/keyvault-admin/samples/v4/typescript/sample.env b/sdk/keyvault/keyvault-admin/samples/v4/typescript/sample.env deleted file mode 100644 index 38ebf9042796..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/typescript/sample.env +++ /dev/null @@ -1,23 +0,0 @@ -# The name of the Managed HSM Key Vault to use in the samples. -# At the moment only Azure Managed HSM supports administration operations. -AZURE_MANAGEDHSM_URI= - -# URI of the Blob Storage instance, with the name of the container where the Key Vault backups will be generated. -BLOB_STORAGE_URI= - -# The SAS token to use for authentication to Azure Blob Storage. -BLOB_STORAGE_SAS_TOKEN= - -# The name of the Azure Storage Blob container where backups will be stored. -BLOB_CONTAINER_NAME= - -# Object ID of the application, tenant or principal to whom the role will be assigned to. -CLIENT_OBJECT_ID= - -# Used to authenticate using Azure AD as a service principal for role-based authentication. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= diff --git a/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/accessControlHelloWorld.ts b/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/accessControlHelloWorld.ts deleted file mode 100644 index 1f272982399d..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/accessControlHelloWorld.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses an AccessControlClient to list, create, and assign roles to users. - */ - -import { - KeyVaultAccessControlClient, - KeyVaultPermission, - KnownKeyVaultDataAction, - KnownKeyVaultRoleScope, -} from "@azure/keyvault-admin"; -import { DefaultAzureCredential } from "@azure/identity"; -import * as uuid from "uuid"; - -// 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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultAccessControlClient(url, credential); - - for await (const roleAssignment of client.listRoleAssignments("/")) { - console.log(roleAssignment); - } - - const globalScope = KnownKeyVaultRoleScope.Global; - const roleDefinitionName = uuid.v4(); - const permissions: KeyVaultPermission[] = [ - { - dataActions: [ - KnownKeyVaultDataAction.StartHsmBackup, - KnownKeyVaultDataAction.StartHsmRestore, - ], - }, - ]; - let roleDefinition = await client.setRoleDefinition(globalScope, { - roleDefinitionName, - roleName: "Backup Manager", - permissions, - description: "Allow backup actions", - }); - console.log(roleDefinition); - - // This sample uses a custom role but you may assign one of the many built-in roles. - // Please refer to https://docs.microsoft.com/azure/key-vault/managed-hsm/built-in-roles for more information. - const roleAssignmentName = uuid.v4(); - const clientObjectId = process.env["CLIENT_OBJECT_ID"]; - if (!clientObjectId) { - throw new Error("Missing environment variable CLIENT_OBJECT_ID."); - } - let assignment = await client.createRoleAssignment( - globalScope, - roleAssignmentName, - roleDefinition.id, - clientObjectId - ); - console.log(assignment); - - assignment = await client.getRoleAssignment(globalScope, roleAssignmentName); - console.log(assignment); - - await client.deleteRoleAssignment(globalScope, roleAssignmentName); - - await client.deleteRoleDefinition(globalScope, roleDefinition.name); -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupRestoreHelloWorld.ts b/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupRestoreHelloWorld.ts deleted file mode 100644 index f382399c4c96..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupRestoreHelloWorld.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and fully restore an Azure Key Vault using Azure Storage Blob. - */ - -import { KeyVaultBackupClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const restorePoller = await client.beginRestore(backupResult.folderUri!, sasToken); - await restorePoller.pollUntilDone(); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupSelectiveKeyRestore.ts b/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupSelectiveKeyRestore.ts deleted file mode 100644 index e83e8e4eef40..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/typescript/src/backupSelectiveKeyRestore.ts +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Uses a BackupClient to backup and restore a specific key in Azure Key Vault using Azure Storage Blob. - */ - -import { KeyVaultBackupClient } from "@azure/keyvault-admin"; -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://docs.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["AZURE_MANAGEDHSM_URI"]; - if (!url) { - throw new Error("Missing environment variable AZURE_MANAGEDHSM_URI."); - } - const client = new KeyVaultBackupClient(url, credential); - - const keyClient = new KeyClient(url, credential); - const keyName = "key-name"; - const key = await keyClient.createRsaKey(keyName); - - const sasToken = process.env["BLOB_STORAGE_SAS_TOKEN"]; - if (!sasToken) { - throw new Error("Missing environment variable BLOB_STORAGE_SAS_TOKEN."); - } - - // Create a Uri with the storage container path. - const blobContainerUri = buildBlobContainerUri(); - - // Start the backup and wait for its completion. - const backupPoller = await client.beginBackup(blobContainerUri, sasToken); - const backupResult = await backupPoller.pollUntilDone(); - console.log("backupResult", backupResult); - - // Finally, start and wait for the restore operation using the folderUri returned from a previous backup operation. - const selectiveKeyRestorePoller = await client.beginSelectiveKeyRestore( - key.name, - backupResult.folderUri!, - sasToken - ); - const restoreResult = await selectiveKeyRestorePoller.pollUntilDone(); - console.log("restoreResult", restoreResult); -} - -/** - * Helper function to construct a valid blob container URI from its parts. - */ -function buildBlobContainerUri() { - const blobStorageUri = process.env["BLOB_STORAGE_URI"]; - if (!blobStorageUri) { - throw new Error("Missing environment variable BLOB_STORAGE_URI."); - } - - const blobContainerName = process.env["BLOB_CONTAINER_NAME"]; - if (!blobContainerName) { - throw new Error("Missing environment variable BLOB_CONTAINER_NAME."); - } - - // If there are trailing slashes, remove them before building the URI. - return `${blobStorageUri.replace(/\/$/, "")}/${blobContainerName}`; -} - -main().catch((err) => { - console.log("error code: ", err.code); - console.log("error message: ", err.message); - console.log("error stack: ", err.stack); -}); diff --git a/sdk/keyvault/keyvault-admin/samples/v4/typescript/tsconfig.json b/sdk/keyvault/keyvault-admin/samples/v4/typescript/tsconfig.json deleted file mode 100644 index 984eed535aa8..000000000000 --- a/sdk/keyvault/keyvault-admin/samples/v4/typescript/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "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-admin/src/accessControlClient.ts b/sdk/keyvault/keyvault-admin/src/accessControlClient.ts deleted file mode 100644 index 1ffe3971b472..000000000000 --- a/sdk/keyvault/keyvault-admin/src/accessControlClient.ts +++ /dev/null @@ -1,489 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/// - -import type { - AccessControlClientOptions, - CreateRoleAssignmentOptions, - DeleteRoleAssignmentOptions, - DeleteRoleDefinitionOptions, - GetRoleAssignmentOptions, - GetRoleDefinitionOptions, - KeyVaultRoleAssignment, - KeyVaultRoleDefinition, - KeyVaultRoleScope, - ListRoleAssignmentsOptions, - ListRoleAssignmentsPageSettings, - ListRoleDefinitionsOptions, - ListRoleDefinitionsPageSettings, - SetRoleDefinitionOptions, -} from "./accessControlModels.js"; -import { KeyVaultClient } from "./generated/keyVaultClient.js"; -import { LATEST_API_VERSION } from "./constants.js"; -import type { PagedAsyncIterableIterator } from "@azure/core-paging"; -import type { RoleAssignmentsListForScopeOptionalParams } from "./generated/models/index.js"; -import type { TokenCredential } from "@azure/core-auth"; -import { keyVaultAuthenticationPolicy } from "@azure/keyvault-common"; -import { logger } from "./log.js"; -import { mappings } from "./mappings.js"; -import { tracingClient } from "./tracing.js"; -import { randomUUID } from "@azure/core-util"; - -/** - * The KeyVaultAccessControlClient provides methods to manage - * access control and role assignments in any given Azure Key Vault instance. - * The client supports creating, retrieving and deleting roles. - */ -export class KeyVaultAccessControlClient { - /** - * The base URL to the vault - */ - public readonly vaultUrl: string; - - /** - * A reference to the auto-generated Key Vault HTTP client. - */ - private readonly client: KeyVaultClient; - - /** - * Creates an instance of the KeyVaultAccessControlClient. - * - * Example usage: - * ```ts - * import { KeyVaultAccessControlClient } from "@azure/keyvault-admin"; - * import { DefaultAzureCredential } from "@azure/identity"; - * - * let vaultUrl = `https://.vault.azure.net`; - * let credentials = new DefaultAzureCredential(); - * - * let client = new KeyVaultAccessControlClient(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 options - Options used to configure Key Vault API requests. Omit this parameter to use the default configuration. - */ - constructor( - vaultUrl: string, - credential: TokenCredential, - // eslint-disable-next-line @azure/azure-sdk/ts-naming-options - options: AccessControlClientOptions = {}, - ) { - this.vaultUrl = vaultUrl; - - const serviceVersion = options.serviceVersion || LATEST_API_VERSION; - - const clientOptions = { - ...options, - loggingOptions: { - logger: logger.info, - additionalAllowedHeaderNames: [ - "x-ms-keyvault-region", - "x-ms-keyvault-network-info", - "x-ms-keyvault-service-version", - ], - }, - }; - - this.client = new KeyVaultClient(serviceVersion, clientOptions); - - // The authentication policy must come after the deserialization policy since the deserialization policy - // converts 401 responses to an Error, and we don't want to deal with that. - this.client.pipeline.addPolicy(keyVaultAuthenticationPolicy(credential, clientOptions), { - afterPolicies: ["deserializationPolicy"], - }); - } - - /** - * Creates a role assignment in an Azure Key Vault. - * - * Example usage: - * ```ts - * const client = new KeyVaultAccessControlClient(url, credentials); - * const roleDefinition = await client.listRoleDefinitions("/").next(); - * const principalId = "4871f6a6-374f-4b6b-8b0c-f5d84db823f6"; - * const result = await client.createRoleAssignment("/", "295c179b-9ad3-4117-99cd-b1aa66cf4517", roleDefinition, principalId); - * ``` - * Creates a new role assignment. - * @param roleScope - The scope of the role assignment. - * @param name - The name of the role assignment. Must be a UUID. - * @param roleDefinitionId - The role definition ID used in the role assignment. - * @param principalId - The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. - * @param options - The optional parameters. - */ - public createRoleAssignment( - roleScope: KeyVaultRoleScope, - name: string, - roleDefinitionId: string, - principalId: string, - options: CreateRoleAssignmentOptions = {}, - ): Promise { - return tracingClient.withSpan( - "KeyVaultAccessControlClient.createRoleAssignment", - options, - async (updatedOptions) => { - const response = await this.client.roleAssignments.create( - this.vaultUrl, - roleScope, - name, - { - properties: { - roleDefinitionId, - principalId, - }, - }, - updatedOptions, - ); - return mappings.roleAssignment.generatedToPublic(response); - }, - ); - } - - /** - * Deletes role assignments previously created in an Azure Key Vault. - * - * Example usage: - * ```ts - * const client = new KeyVaultAccessControlClient(url, credentials); - * const roleAssignment = await client.createRoleAssignment("/", "295c179b-9ad3-4117-99cd-b1aa66cf4517"); - * await client.deleteRoleAssignment(roleAssignment.properties.roleScope, roleAssignment.name); - * ``` - * Deletes an existing role assignment. - * @param roleScope - The scope of the role assignment. - * @param name - The name of the role assignment. - * @param options - The optional parameters. - */ - public deleteRoleAssignment( - roleScope: KeyVaultRoleScope, - name: string, - options: DeleteRoleAssignmentOptions = {}, - ): Promise { - return tracingClient.withSpan( - "KeyVaultAccessControlClient.deleteRoleAssignment", - options, - async (updatedOptions) => { - await this.client.roleAssignments.delete(this.vaultUrl, roleScope, name, updatedOptions); - }, - ); - } - - /** - * Gets a role assignments previously created in an Azure Key Vault. - * - * Example usage: - * ```ts - * const client = new KeyVaultAccessControlClient(url, credentials); - * let roleAssignment = await client.createRoleAssignment("/", "295c179b-9ad3-4117-99cd-b1aa66cf4517"); - * roleAssignment = const await client.getRoleAssignment(roleAssignment.properties.roleScope, roleAssignment.name); - * console.log(roleAssignment); - * ``` - * Gets an existing role assignment. - * @param roleScope - The scope of the role assignment. - * @param name - The name of the role assignment. - * @param options - The optional parameters. - */ - public getRoleAssignment( - roleScope: KeyVaultRoleScope, - name: string, - options: GetRoleAssignmentOptions = {}, - ): Promise { - return tracingClient.withSpan( - "KeyVaultAccessControlClient.getRoleAssignment", - options, - async (updatedOptions) => { - const response = await this.client.roleAssignments.get( - this.vaultUrl, - roleScope, - name, - updatedOptions, - ); - return mappings.roleAssignment.generatedToPublic(response); - }, - ); - } - - /** - * Deals with the pagination of {@link listRoleAssignments}. - * @param roleScope - The scope of the role assignments. - * @param continuationState - An object that indicates the position of the paginated request. - * @param options - Common options for the iterative endpoints. - */ - private async *listRoleAssignmentsPage( - roleScope: KeyVaultRoleScope, - continuationState: ListRoleAssignmentsPageSettings, - options?: ListRoleAssignmentsOptions, - ): AsyncIterableIterator { - if (!continuationState.continuationToken) { - const optionsComplete: RoleAssignmentsListForScopeOptionalParams = options || {}; - const currentSetResponse = await tracingClient.withSpan( - "KeyVaultAccessControlClient.listRoleAssignmentsPage", - optionsComplete, - async (updatedOptions) => { - return this.client.roleAssignments.listForScope(this.vaultUrl, roleScope, updatedOptions); - }, - ); - continuationState.continuationToken = currentSetResponse.nextLink; - if (currentSetResponse.value) { - yield currentSetResponse.value.map(mappings.roleAssignment.generatedToPublic, this); - } - } - while (continuationState.continuationToken) { - const currentSetResponse = await tracingClient.withSpan( - "KeyVaultAccessControlClient.listRoleAssignmentsPage", - options || {}, - async (updatedOptions) => { - return this.client.roleAssignments.listForScopeNext( - this.vaultUrl, - roleScope, - continuationState.continuationToken!, - updatedOptions, - ); - }, - ); - continuationState.continuationToken = currentSetResponse.nextLink; - if (currentSetResponse.value) { - yield currentSetResponse.value.map(mappings.roleAssignment.generatedToPublic, this); - } else { - break; - } - } - } - - /** - * Deals with the iteration of all the available results of {@link listRoleAssignments}. - * @param roleScope - The scope of the role assignments. - * @param options - Common options for the iterative endpoints. - */ - private async *listRoleAssignmentsAll( - roleScope: KeyVaultRoleScope, - options?: ListRoleAssignmentsOptions, - ): AsyncIterableIterator { - for await (const page of this.listRoleAssignmentsPage(roleScope, {}, options)) { - yield* page; - } - } - - /** - * Iterates over all of the available role assignments in an Azure Key Vault. - * - * Example usage: - * ```ts - * let client = new KeyVaultAccessControlClient(url, credentials); - * for await (const roleAssignment of client.listRoleAssignments("/")) { - * console.log("Role assignment: ", roleAssignment); - * } - * ``` - * Lists all of the role assignments in a given scope. - * @param roleScope - The scope of the role assignments. - * @param options - The optional parameters. - */ - public listRoleAssignments( - roleScope: KeyVaultRoleScope, - options: ListRoleAssignmentsOptions = {}, - ): PagedAsyncIterableIterator { - const iter = this.listRoleAssignmentsAll(roleScope, options); - - return { - next() { - return iter.next(); - }, - [Symbol.asyncIterator]() { - return this; - }, - byPage: (settings: ListRoleAssignmentsPageSettings = {}) => - this.listRoleAssignmentsPage(roleScope, settings, options), - }; - } - - /** - * Deals with the pagination of {@link listRoleDefinitions}. - * @param roleScope - The scope of the role definition. - * @param continuationState - An object that indicates the position of the paginated request. - * @param options - Common options for the iterative endpoints. - */ - private async *listRoleDefinitionsPage( - roleScope: KeyVaultRoleScope, - continuationState: ListRoleDefinitionsPageSettings, - options: ListRoleDefinitionsOptions = {}, - ): AsyncIterableIterator { - if (!continuationState.continuationToken) { - const optionsComplete: RoleAssignmentsListForScopeOptionalParams = options || {}; - const currentSetResponse = await tracingClient.withSpan( - "KeyVaultAccessControlClient.listRoleDefinitionsPage", - optionsComplete, - (updatedOptions) => - this.client.roleDefinitions.list(this.vaultUrl, roleScope, updatedOptions), - ); - continuationState.continuationToken = currentSetResponse.nextLink; - if (currentSetResponse.value) { - yield currentSetResponse.value.map(mappings.roleDefinition.generatedToPublic, this); - } - } - while (continuationState.continuationToken) { - const currentSetResponse = await tracingClient.withSpan( - "KeyVaultAccessControlClient.listRoleDefinitionsPage", - options, - (updatedOptions) => - this.client.roleDefinitions.listNext( - this.vaultUrl, - roleScope, - continuationState.continuationToken!, - updatedOptions, - ), - ); - continuationState.continuationToken = currentSetResponse.nextLink; - if (currentSetResponse.value) { - yield currentSetResponse.value.map(mappings.roleDefinition.generatedToPublic, this); - } else { - break; - } - } - } - - /** - * Deals with the iteration of all the available results of {@link listRoleDefinitions}. - * @param roleScope - The scope of the role definition. - * @param options - Common options for the iterative endpoints. - */ - private async *listRoleDefinitionsAll( - roleScope: KeyVaultRoleScope, - options?: ListRoleDefinitionsOptions, - ): AsyncIterableIterator { - for await (const page of this.listRoleDefinitionsPage(roleScope, {}, options)) { - yield* page; - } - } - - /** - * Iterates over all of the available role definitions in an Azure Key Vault. - * - * Example usage: - * ```ts - * let client = new KeyVaultAccessControlClient(url, credentials); - * for await (const roleDefinitions of client.listRoleDefinitions("/")) { - * console.log("Role definition: ", roleDefinitions); - * } - * ``` - * Lists all of the role definition in a given scope. - * @param roleScope - The scope of the role definition. - * @param options - The optional parameters. - */ - public listRoleDefinitions( - roleScope: KeyVaultRoleScope, - options: ListRoleDefinitionsOptions = {}, - ): PagedAsyncIterableIterator { - const iter = this.listRoleDefinitionsAll(roleScope, options); - - return { - next() { - return iter.next(); - }, - [Symbol.asyncIterator]() { - return this; - }, - byPage: (settings: ListRoleDefinitionsPageSettings = {}) => - this.listRoleDefinitionsPage(roleScope, settings, options), - }; - } - - /** - * Gets a role definition from Azure Key Vault. - * - * Example usage: - * ``` - * const client = new KeyVaultAccessControlClient(url, credentials); - * const roleDefinition = await client.getRoleDefinition("/", "b86a8fe4-44ce-4948-aee5-eccb2c155cd7"); - * console.log(roleDefinition); - * ``` - * @param roleScope - The scope of the role definition. - * @param name - The name of the role definition. - * @param options - The optional parameters. - */ - public getRoleDefinition( - roleScope: KeyVaultRoleScope, - name: string, - options: GetRoleDefinitionOptions = {}, - ): Promise { - return tracingClient.withSpan( - "KeyVaultAccessControlClient.getRoleDefinition", - options, - async (updatedOptions) => { - const response = await this.client.roleDefinitions.get( - this.vaultUrl, - roleScope, - name, - updatedOptions, - ); - return mappings.roleDefinition.generatedToPublic(response); - }, - ); - } - - /** - * Creates or updates a role definition in an Azure Key Vault. - * - * Example usage: - * ```ts - * const client = new KeyVaultAccessControlClient(url, credentials); - * const permissions = [{ dataActions: [KnownKeyVaultDataAction.BackupHsmKeys] }]; - * const roleDefinitionName = "23b8bb1a-39c0-4c89-a85b-dd3c99273a8a"; - * const roleDefinition = await client.setRoleDefinition(KnownKeyVaultRoleScope.Global, { permissions, roleDefinitionName }); - * console.log(roleDefinition); - * ``` - * @param roleScope - The scope of the role definition. - * @param options - The optional parameters. - */ - public setRoleDefinition( - roleScope: KeyVaultRoleScope, - options: SetRoleDefinitionOptions = {}, - ): Promise { - return tracingClient.withSpan( - "KeyVaultAccessControlClient.setRoleDefinition", - options, - async (updatedOptions) => { - const response = await this.client.roleDefinitions.createOrUpdate( - this.vaultUrl, - roleScope, - options.roleDefinitionName || randomUUID(), - { - properties: { - description: options.description, - permissions: options.permissions, - assignableScopes: [roleScope], - roleName: options.roleName, - roleType: "CustomRole", - }, - }, - updatedOptions, - ); - return mappings.roleDefinition.generatedToPublic(response); - }, - ); - } - - /** - * Deletes a custom role definition previously created in an Azure Key Vault. - * - * Example usage: - * ```ts - * const client = new KeyVaultAccessControlClient(url, credentials); - * const roleDefinition = await client.setRoleDefinition("/", "23b8bb1a-39c0-4c89-a85b-dd3c99273a8a", []); - * await client.deleteRoleDefinition("/", roleDefinition.name); - * ``` - * @param roleScope - The scope of the role definition. - * @param name - The name of the role definition to delete. - * @param options - The optional parameters. - */ - public deleteRoleDefinition( - roleScope: KeyVaultRoleScope, - name: string, - options: DeleteRoleDefinitionOptions = {}, - ): Promise { - return tracingClient.withSpan( - "KeyVaultAccessControlClient.deleteRoleDefinition", - options, - async (updatedOptions) => { - await this.client.roleDefinitions.delete(this.vaultUrl, roleScope, name, updatedOptions); - }, - ); - } -} diff --git a/sdk/keyvault/keyvault-admin/src/accessControlModels.ts b/sdk/keyvault/keyvault-admin/src/accessControlModels.ts deleted file mode 100644 index 777ee31bccba..000000000000 --- a/sdk/keyvault/keyvault-admin/src/accessControlModels.ts +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { CommonClientOptions, OperationOptions } from "@azure/core-client"; -import { - DataAction as KeyVaultDataAction, - RoleScope as KeyVaultRoleScope, - KnownDataAction as KnownKeyVaultDataAction, - KnownRoleScope as KnownKeyVaultRoleScope, -} from "./generated/index.js"; -import type { SUPPORTED_API_VERSIONS } from "./constants.js"; - -export { KeyVaultDataAction, KeyVaultRoleScope, KnownKeyVaultDataAction, KnownKeyVaultRoleScope }; - -/** - * The optional parameters accepted by the Key Vault's AccessControlClient - */ -export interface AccessControlClientOptions extends CommonClientOptions { - /** - * The accepted versions of the Key Vault's service API. - */ - serviceVersion?: SUPPORTED_API_VERSIONS; - - /** - * Whether to disable verification that the authentication challenge resource matches the Key Vault or Managed HSM domain. - * Defaults to false. - */ - disableChallengeResourceVerification?: boolean; -} - -/** - * A Key Vault role assignment. - */ -export interface KeyVaultRoleAssignment { - /** - * The role assignment ID. - */ - readonly id: string; - /** - * The role assignment name. - */ - readonly name: string; - /** - * The role assignment type. - */ - readonly kind: string; - /** - * Role assignment properties. - */ - properties: KeyVaultRoleAssignmentProperties; -} - -/** - * A list of Key Vault permissions. - */ -export interface KeyVaultPermission { - /** - * Allowed actions. - */ - actions?: string[]; - /** - * Actions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. - */ - notActions?: string[]; - /** - * Allowed Data actions. - */ - dataActions?: KeyVaultDataAction[]; - /** - * Data actions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. - */ - notDataActions?: KeyVaultDataAction[]; -} - -/** - * A Key Vault role definition. - */ -export interface KeyVaultRoleDefinition { - /** - * The role definition ID. - */ - readonly id: string; - /** - * The role definition name. - */ - readonly name: string; - /** - * The role definition type. - */ - readonly kind: string; - /** - * The role name. - */ - roleName: string; - /** - * The role definition description. - */ - description: string; - /** - * The role type. - */ - roleType: string; - /** - * A list of Key Vault permissions. - */ - permissions: KeyVaultPermission[]; - /** - * Role definition assignable scopes. - */ - assignableScopes: string[]; -} - -/** - * Role assignment properties. - */ -export interface KeyVaultRoleAssignmentProperties { - /** - * The role definition ID. - */ - roleDefinitionId: string; - /** - * The principal ID. - */ - principalId: string; - /** - * The role assignment scope. - */ - scope?: KeyVaultRoleScope; -} - -/** - * An interface representing the optional parameters that can be - * passed to {@link createRoleAssignment} - */ -export interface CreateRoleAssignmentOptions extends OperationOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link deleteRoleAssignment} - */ -export interface DeleteRoleAssignmentOptions extends OperationOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link getRoleAssignment} - */ -export interface GetRoleAssignmentOptions extends OperationOptions {} - -/** - * An interface representing optional parameters passed to {@link listRoleAssignments}. - */ -export interface ListRoleAssignmentsOptions extends OperationOptions {} - -/** - * An interface representing optional parameters passed to {@link listRoleDefinitions}. - */ -export interface ListRoleDefinitionsOptions extends OperationOptions {} - -/** - * An interface representing optional parameters passed to {@link getRoleDefinition}. - */ -export interface GetRoleDefinitionOptions extends OperationOptions {} - -/** - * An interface representing optional parameters passed to {@link setRoleDefinition}. - */ -export interface SetRoleDefinitionOptions extends OperationOptions { - /** - * UUID used as the name of the role definition to create. If it's not provided, a new UUID will be generated. - */ - roleDefinitionName?: string; - /** - * Friendly display name for the role definition. - */ - roleName?: string; - /** - * Long-form description of the role definition. - */ - description?: string; - /** - * List of Key Vault permissions - */ - permissions?: KeyVaultPermission[]; - /** - * List of assignable Key Vault role scopes - */ - assignableScopes?: KeyVaultRoleScope[]; -} - -/** - * An interface representing optional parameters passed to {@link deleteRoleDefinition}. - */ -export interface DeleteRoleDefinitionOptions extends OperationOptions {} - -/** - * Arguments for retrieving the next page of search results. - */ -export interface ListRoleDefinitionsPageSettings { - /** - * A token used for retrieving the next page of results when the server - * enforces pagination. - */ - continuationToken?: string; -} - -/** - * Arguments for retrieving the next page of search results. - */ -export interface ListRoleAssignmentsPageSettings { - /** - * A token used for retrieving the next page of results when the server - * enforces pagination. - */ - continuationToken?: string; -} diff --git a/sdk/keyvault/keyvault-admin/src/backupClient.ts b/sdk/keyvault/keyvault-admin/src/backupClient.ts deleted file mode 100644 index 3df315bac0a0..000000000000 --- a/sdk/keyvault/keyvault-admin/src/backupClient.ts +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - KeyVaultBackupClientOptions, - KeyVaultBackupResult, - KeyVaultBeginBackupOptions, - KeyVaultBeginRestoreOptions, - KeyVaultBeginSelectiveKeyRestoreOptions, - KeyVaultRestoreResult, - KeyVaultSelectiveKeyRestoreResult, -} from "./backupClientModels.js"; -import { KeyVaultAdminPollOperationState } from "./lro/keyVaultAdminPoller.js"; -import { KeyVaultBackupOperationState } from "./lro/backup/operation.js"; -import { KeyVaultBackupPoller } from "./lro/backup/poller.js"; -import { KeyVaultClient } from "./generated/keyVaultClient.js"; -import { KeyVaultRestoreOperationState } from "./lro/restore/operation.js"; -import { KeyVaultRestorePoller } from "./lro/restore/poller.js"; -import { KeyVaultSelectiveKeyRestoreOperationState } from "./lro/selectiveKeyRestore/operation.js"; -import { KeyVaultSelectiveKeyRestorePoller } from "./lro/selectiveKeyRestore/poller.js"; -import { LATEST_API_VERSION } from "./constants.js"; -import type { PollerLike } from "@azure/core-lro"; -import type { TokenCredential } from "@azure/core-auth"; -import { keyVaultAuthenticationPolicy } from "@azure/keyvault-common"; -import { logger } from "./log.js"; -import { mappings } from "./mappings.js"; - -export { - KeyVaultBackupOperationState, - KeyVaultRestoreOperationState, - KeyVaultSelectiveKeyRestoreOperationState, - KeyVaultAdminPollOperationState, -}; - -/** - * The KeyVaultBackupClient provides methods to generate backups - * and restore backups of any given Azure Key Vault instance. - * This client supports generating full backups, selective restores of specific keys - * and full restores of Key Vault instances. - */ -export class KeyVaultBackupClient { - /** - * The base URL to the vault - */ - public readonly vaultUrl: string; - - /** - * A reference to the auto-generated Key Vault HTTP client. - */ - private readonly client: KeyVaultClient; - - /** - * Creates an instance of the KeyVaultBackupClient. - * - * Example usage: - * ```ts - * import { KeyVaultBackupClient } from "@azure/keyvault-admin"; - * import { DefaultAzureCredential } from "@azure/identity"; - * - * let vaultUrl = `https://.vault.azure.net`; - * let credentials = new DefaultAzureCredential(); - * - * let client = new KeyVaultBackupClient(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 options - options used to configure Key Vault API requests. - */ - constructor( - vaultUrl: string, - credential: TokenCredential, - options: KeyVaultBackupClientOptions = {}, - ) { - this.vaultUrl = vaultUrl; - - const apiVersion = options.serviceVersion || LATEST_API_VERSION; - - const clientOptions = { - ...options, - loggingOptions: { - logger: logger.info, - additionalAllowedHeaderNames: [ - "x-ms-keyvault-region", - "x-ms-keyvault-network-info", - "x-ms-keyvault-service-version", - ], - }, - }; - - this.client = new KeyVaultClient(apiVersion, clientOptions); - // The authentication policy must come after the deserialization policy since the deserialization policy - // converts 401 responses to an Error, and we don't want to deal with that. - this.client.pipeline.addPolicy(keyVaultAuthenticationPolicy(credential, clientOptions), { - afterPolicies: ["deserializationPolicy"], - }); - } - - /** - * Starts generating a backup of an Azure Key Vault on the specified Storage Blob account. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault backup is generated. - * - * Example usage: - * ```ts - * const client = new KeyVaultBackupClient(url, credentials); - * - * const blobStorageUri = ""; // / - * const sasToken = ""; - * const poller = await client.beginBackup(blobStorageUri, sasToken); - * - * // Serializing the poller - * // - * // const serialized = poller.toString(); - * // - * // A new poller can be created with: - * // - * // await client.beginBackup(blobStorageUri, sasToken, { resumeFrom: serialized }); - * // - * - * // Waiting until it's done - * const backupUri = await poller.pollUntilDone(); - * console.log(backupUri); - * ``` - * Starts a full backup operation. - * @param blobStorageUri - The URL of the blob storage resource, including the path to the container where the backup will end up being stored. - * @param sasToken - The SAS token used to access the blob storage resource. - * @param options - The optional parameters. - */ - public async beginBackup( - blobStorageUri: string, - sasToken: string, - options?: KeyVaultBeginBackupOptions, - ): Promise>; - - /** - * Starts generating a backup of an Azure Key Vault on the specified Storage Blob account, using a user-assigned Managed Identity - * to access the Storage account. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault backup is generated. - * - * Example usage: - * ```ts - * const client = new KeyVaultBackupClient(url, credentials); - * - * const blobStorageUri = ""; // / - * const sasToken = ""; - * const poller = await client.beginBackup(blobStorageUri); - * - * // Serializing the poller - * // - * // const serialized = poller.toString(); - * // - * // A new poller can be created with: - * // - * // await client.beginBackup(blobStorageUri, { resumeFrom: serialized }); - * // - * - * // Waiting until it's done - * const backupUri = await poller.pollUntilDone(); - * console.log(backupUri); - * ``` - * Starts a full backup operation. - * @param blobStorageUri - The URL of the blob storage resource, including the path to the container where the backup will end up being stored. - * @param options - The optional parameters. - */ - public async beginBackup( - blobStorageUri: string, - options?: KeyVaultBeginBackupOptions, - ): Promise>; - - public async beginBackup( - blobStorageUri: string, - sasTokenOrOptions: string | KeyVaultBeginBackupOptions = {}, - optionsWhenSasTokenSpecified: KeyVaultBeginBackupOptions = {}, - ): Promise> { - const sasToken = typeof sasTokenOrOptions === "string" ? sasTokenOrOptions : undefined; - const options = - typeof sasTokenOrOptions === "string" ? optionsWhenSasTokenSpecified : sasTokenOrOptions; - - const poller = new KeyVaultBackupPoller({ - blobStorageUri, - sasToken, - client: this.client, - vaultUrl: this.vaultUrl, - intervalInMs: options.intervalInMs, - resumeFrom: options.resumeFrom, - requestOptions: options, - }); - - // This will initialize the poller's operation (the generation of the backup). - await poller.poll(); - - return poller; - } - - /** - * Starts restoring all key materials using the SAS token pointing to a previously stored Azure Blob storage - * backup folder. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault restore operation is complete. - * - * Example usage: - * ```ts - * const client = new KeyVaultBackupClient(url, credentials); - * - * const blobStorageUri = ""; // / - * const sasToken = ""; - * const poller = await client.beginRestore(blobStorageUri, sasToken); - * - * // The poller can be serialized with: - * // - * // const serialized = poller.toString(); - * // - * // A new poller can be created with: - * // - * // await client.beginRestore(blobStorageUri, sasToken, { resumeFrom: serialized }); - * // - * - * // Waiting until it's done - * const backupUri = await poller.pollUntilDone(); - * console.log(backupUri); - * ``` - * Starts a full restore operation. - * @param folderUri - The URL of the blob storage resource where the previous successful full backup was stored. - * @param sasToken - The SAS token. If no SAS token is provided, user-assigned Managed Identity will be used to access the blob storage resource. - * @param options - The optional parameters. - */ - public async beginRestore( - folderUri: string, - sasToken: string, - options?: KeyVaultBeginRestoreOptions, - ): Promise>; - - /** - * Starts restoring all key materials using the SAS token pointing to a previously stored Azure Blob storage - * backup folder, using a user-assigned Managed Identity to access the storage account. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault restore operation is complete. - * - * Example usage: - * ```ts - * const client = new KeyVaultBackupClient(url, credentials); - * - * const blobStorageUri = ""; // / - * const sasToken = ""; - * const poller = await client.beginRestore(blobStorageUri); - * - * // The poller can be serialized with: - * // - * // const serialized = poller.toString(); - * // - * // A new poller can be created with: - * // - * // await client.beginRestore(blobStorageUri, { resumeFrom: serialized }); - * // - * - * // Waiting until it's done - * const backupUri = await poller.pollUntilDone(); - * console.log(backupUri); - * ``` - * Starts a full restore operation. - * @param folderUri - The URL of the blob storage resource where the previous successful full backup was stored. - * @param sasToken - The SAS token. If no SAS token is provided, user-assigned Managed Identity will be used to access the blob storage resource. - * @param options - The optional parameters. - */ - public async beginRestore( - folderUri: string, - options?: KeyVaultBeginRestoreOptions, - ): Promise>; - - public async beginRestore( - folderUri: string, - sasTokenOrOptions: string | KeyVaultBeginRestoreOptions = {}, - optionsWhenSasTokenSpecified: KeyVaultBeginRestoreOptions = {}, - ): Promise> { - const sasToken = typeof sasTokenOrOptions === "string" ? sasTokenOrOptions : undefined; - const options = - typeof sasTokenOrOptions === "string" ? optionsWhenSasTokenSpecified : sasTokenOrOptions; - - const poller = new KeyVaultRestorePoller({ - ...mappings.folderUriParts(folderUri), - sasToken, - client: this.client, - vaultUrl: this.vaultUrl, - intervalInMs: options.intervalInMs, - resumeFrom: options.resumeFrom, - requestOptions: options, - }); - - // This will initialize the poller's operation (the generation of the backup). - await poller.poll(); - - return poller; - } - - /** - * Starts restoring all key versions of a given key using user supplied SAS token pointing to a previously - * stored Azure Blob storage backup folder. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault selective restore is complete. - * - * Example usage: - * ```ts - * const client = new KeyVaultBackupClient(url, credentials); - * - * const blobStorageUri = ""; - * const sasToken = ""; - * const keyName = ""; - * const poller = await client.beginSelectiveKeyRestore(keyName, blobStorageUri, sasToken); - * - * // Serializing the poller - * // - * // const serialized = poller.toString(); - * // - * // A new poller can be created with: - * // - * // await client.beginSelectiveKeyRestore(keyName, blobStorageUri, sasToken, { resumeFrom: serialized }); - * // - * - * // Waiting until it's done - * await poller.pollUntilDone(); - * ``` - * Creates a new role assignment. - * @param keyName - The name of the key that wants to be restored. - * @param folderUri - The URL of the blob storage resource, with the folder name of the blob where the previous successful full backup was stored. - * @param sasToken - The SAS token. If no SAS token is provided, user-assigned Managed Identity will be used to access the blob storage resource. - * @param options - The optional parameters. - */ - public async beginSelectiveKeyRestore( - keyName: string, - folderUri: string, - sasToken: string, - options?: KeyVaultBeginSelectiveKeyRestoreOptions, - ): Promise< - PollerLike - >; - - /** - * Starts restoring all key versions of a given key using to a previously - * stored Azure Blob storage backup folder. The Blob storage backup folder will be accessed using user-assigned Managed Identity. - * - * This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault selective restore is complete. - * - * Example usage: - * ```ts - * const client = new KeyVaultBackupClient(url, credentials); - * - * const blobStorageUri = ""; - * const sasToken = ""; - * const keyName = ""; - * const poller = await client.beginSelectiveKeyRestore(keyName, blobStorageUri, sasToken); - * - * // Serializing the poller - * // - * // const serialized = poller.toString(); - * // - * // A new poller can be created with: - * // - * // await client.beginSelectiveKeyRestore(keyName, blobStorageUri, sasToken, { resumeFrom: serialized }); - * // - * - * // Waiting until it's done - * await poller.pollUntilDone(); - * ``` - * Creates a new role assignment. - * @param keyName - The name of the key that wants to be restored. - * @param folderUri - The URL of the blob storage resource, with the folder name of the blob where the previous successful full backup was stored. - * @param sasToken - The SAS token. If no SAS token is provided, user-assigned Managed Identity will be used to access the blob storage resource. - * @param options - The optional parameters. - */ - public async beginSelectiveKeyRestore( - keyName: string, - folderUri: string, - options?: KeyVaultBeginSelectiveKeyRestoreOptions, - ): Promise< - PollerLike - >; - - public async beginSelectiveKeyRestore( - keyName: string, - folderUri: string, - sasTokenOrOptions: string | KeyVaultBeginSelectiveKeyRestoreOptions = {}, - optionsWhenSasTokenSpecified: KeyVaultBeginSelectiveKeyRestoreOptions = {}, - ): Promise< - PollerLike - > { - const sasToken = typeof sasTokenOrOptions === "string" ? sasTokenOrOptions : undefined; - const options = - typeof sasTokenOrOptions === "string" ? optionsWhenSasTokenSpecified : sasTokenOrOptions; - - const poller = new KeyVaultSelectiveKeyRestorePoller({ - ...mappings.folderUriParts(folderUri), - keyName, - sasToken, - client: this.client, - vaultUrl: this.vaultUrl, - intervalInMs: options.intervalInMs, - resumeFrom: options.resumeFrom, - requestOptions: options, - }); - - // This will initialize the poller's operation (the generation of the backup). - await poller.poll(); - - return poller; - } -} diff --git a/sdk/keyvault/keyvault-admin/src/backupClientModels.ts b/sdk/keyvault/keyvault-admin/src/backupClientModels.ts deleted file mode 100644 index fd75b39042cf..000000000000 --- a/sdk/keyvault/keyvault-admin/src/backupClientModels.ts +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { CommonClientOptions, OperationOptions } from "@azure/core-client"; -import type { SUPPORTED_API_VERSIONS } from "./constants.js"; - -/** - * The optional parameters accepted by the KeyVaultBackupClient - */ -export interface KeyVaultBackupClientOptions extends CommonClientOptions { - /** - * The accepted versions of the Key Vault's service API. - */ - serviceVersion?: SUPPORTED_API_VERSIONS; - - /** - * Whether to disable verification that the authentication challenge resource matches the Key Vault or Managed HSM domain. - * Defaults to false. - */ - disableChallengeResourceVerification?: boolean; -} - -/** - * An interface representing the optional parameters that can be - * passed to {@link beginBackup} - */ -export interface KeyVaultBackupPollerOptions extends 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 beginBackup} - */ -export interface KeyVaultBeginBackupOptions extends KeyVaultBackupPollerOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link beginRestore} - */ -export interface KeyVaultBeginRestoreOptions extends KeyVaultBackupPollerOptions {} - -/** - * An interface representing the optional parameters that can be - * passed to {@link beginSelectiveKeyRestore} - */ -export interface KeyVaultBeginSelectiveKeyRestoreOptions extends KeyVaultBackupPollerOptions {} - -/** - * An interface representing the result of a backup operation. - */ -export interface KeyVaultBackupResult { - /** - * The location of the full backup. - */ - folderUri?: string; - - /** - * The start time of the backup operation. - */ - startTime: Date; - - /** - * The end time of the backup operation. - */ - endTime?: Date; -} - -/** - * An interface representing the result of a restore operation. - */ -export interface KeyVaultRestoreResult { - /** - * The start time of the restore operation. - */ - startTime: Date; - - /** - * The end time of the restore operation. - */ - endTime?: Date; -} - -/** - * An interface representing the result of a selective key restore operation. - */ -export interface KeyVaultSelectiveKeyRestoreResult { - /** - * The start time of the selective key restore operation. - */ - startTime: Date; - - /** - * The end time of the selective key restore operation. - */ - endTime?: Date; -} diff --git a/sdk/keyvault/keyvault-admin/src/constants.ts b/sdk/keyvault/keyvault-admin/src/constants.ts deleted file mode 100644 index a82d89c36e53..000000000000 --- a/sdk/keyvault/keyvault-admin/src/constants.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * Current version of the Key Vault Admin SDK. - */ -export const SDK_VERSION: string = "4.6.1"; - -/** - * The latest supported Key Vault service API version. - */ -export const LATEST_API_VERSION = "7.5"; - -/** - * Supported API versions - */ -export type SUPPORTED_API_VERSIONS = "7.2" | "7.3" | "7.4" | "7.5"; diff --git a/sdk/keyvault/keyvault-admin/src/generated/index.ts b/sdk/keyvault/keyvault-admin/src/generated/index.ts deleted file mode 100644 index 00de1c72d4c7..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -export * from "./models/index.js"; -export { KeyVaultClient } from "./keyVaultClient.js"; -export { KeyVaultClientContext } from "./keyVaultClientContext.js"; -export * from "./operationsInterfaces/index.js"; diff --git a/sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts b/sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts deleted file mode 100644 index 231f5afe0cef..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { RoleDefinitionsImpl, RoleAssignmentsImpl } from "./operations/index.js"; -import { RoleDefinitions, RoleAssignments } from "./operationsInterfaces/index.js"; -import * as Parameters from "./models/parameters.js"; -import * as Mappers from "./models/mappers.js"; -import { KeyVaultClientContext } from "./keyVaultClientContext.js"; -import { - KeyVaultClientOptionalParams, - ApiVersion75, - FullBackupOptionalParams, - FullBackupResponse, - FullBackupStatusOptionalParams, - FullBackupStatusResponse, - FullRestoreOperationOptionalParams, - FullRestoreOperationResponse, - RestoreStatusOptionalParams, - RestoreStatusResponse, - SelectiveKeyRestoreOperationOptionalParams, - SelectiveKeyRestoreOperationResponse, - UpdateSettingOptionalParams, - UpdateSettingResponse, - GetSettingOptionalParams, - GetSettingResponse, - GetSettingsOptionalParams, - GetSettingsResponse -} from "./models/index.js"; - -export class KeyVaultClient extends KeyVaultClientContext { - /** - * Initializes a new instance of the KeyVaultClient class. - * @param apiVersion Api Version - * @param options The parameter options - */ - constructor( - apiVersion: ApiVersion75, - options?: KeyVaultClientOptionalParams - ) { - super(apiVersion, options); - this.roleDefinitions = new RoleDefinitionsImpl(this); - this.roleAssignments = new RoleAssignmentsImpl(this); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param options The options parameters. - */ - fullBackup( - vaultBaseUrl: string, - options?: FullBackupOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, options }, - fullBackupOperationSpec - ); - } - - /** - * Returns the status of full backup operation - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The id returned as part of the backup request - * @param options The options parameters. - */ - fullBackupStatus( - vaultBaseUrl: string, - jobId: string, - options?: FullBackupStatusOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, jobId, options }, - fullBackupStatusOperationSpec - ); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage - * backup folder - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param options The options parameters. - */ - fullRestoreOperation( - vaultBaseUrl: string, - options?: FullRestoreOperationOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, options }, - fullRestoreOperationOperationSpec - ); - } - - /** - * Returns the status of restore operation - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The Job Id returned part of the restore operation - * @param options The options parameters. - */ - restoreStatus( - vaultBaseUrl: string, - jobId: string, - options?: RestoreStatusOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, jobId, options }, - restoreStatusOperationSpec - ); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously - * stored Azure Blob storage backup folder - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup - * @param options The options parameters. - */ - selectiveKeyRestoreOperation( - vaultBaseUrl: string, - keyName: string, - options?: SelectiveKeyRestoreOperationOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, keyName, options }, - selectiveKeyRestoreOperationOperationSpec - ); - } - - /** - * Description of the pool setting to be updated - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param value The value of the pool setting. - * @param options The options parameters. - */ - updateSetting( - vaultBaseUrl: string, - settingName: string, - value: string, - options?: UpdateSettingOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, settingName, value, options }, - updateSettingOperationSpec - ); - } - - /** - * Retrieves the setting object of a specified setting name. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param options The options parameters. - */ - getSetting( - vaultBaseUrl: string, - settingName: string, - options?: GetSettingOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, settingName, options }, - getSettingOperationSpec - ); - } - - /** - * Retrieves a list of all the available account settings that can be configured. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param options The options parameters. - */ - getSettings( - vaultBaseUrl: string, - options?: GetSettingsOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, options }, - getSettingsOperationSpec - ); - } - - roleDefinitions: RoleDefinitions; - roleAssignments: RoleAssignments; -} -// Operation Specifications -const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); - -const fullBackupOperationSpec: coreClient.OperationSpec = { - path: "/backup", - httpMethod: "POST", - responses: { - 202: { - bodyMapper: Mappers.FullBackupOperation, - headersMapper: Mappers.KeyVaultClientFullBackupHeaders - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - requestBody: Parameters.azureStorageBlobContainerUri, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl], - headerParameters: [Parameters.accept, Parameters.contentType], - mediaType: "json", - serializer -}; -const fullBackupStatusOperationSpec: coreClient.OperationSpec = { - path: "/backup/{jobId}/pending", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.FullBackupOperation - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl, Parameters.jobId], - headerParameters: [Parameters.accept], - serializer -}; -const fullRestoreOperationOperationSpec: coreClient.OperationSpec = { - path: "/restore", - httpMethod: "PUT", - responses: { - 202: { - bodyMapper: Mappers.RestoreOperation, - headersMapper: Mappers.KeyVaultClientFullRestoreOperationHeaders - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - requestBody: Parameters.restoreBlobDetails, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl], - headerParameters: [Parameters.accept, Parameters.contentType], - mediaType: "json", - serializer -}; -const restoreStatusOperationSpec: coreClient.OperationSpec = { - path: "/restore/{jobId}/pending", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.RestoreOperation - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl, Parameters.jobId], - headerParameters: [Parameters.accept], - serializer -}; -const selectiveKeyRestoreOperationOperationSpec: coreClient.OperationSpec = { - path: "/keys/{keyName}/restore", - httpMethod: "PUT", - responses: { - 202: { - bodyMapper: Mappers.SelectiveKeyRestoreOperation, - headersMapper: Mappers.KeyVaultClientSelectiveKeyRestoreOperationHeaders - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - requestBody: Parameters.restoreBlobDetails1, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl, Parameters.keyName], - headerParameters: [Parameters.accept, Parameters.contentType], - mediaType: "json", - serializer -}; -const updateSettingOperationSpec: coreClient.OperationSpec = { - path: "/settings/{setting-name}", - httpMethod: "PATCH", - responses: { - 200: { - bodyMapper: Mappers.Setting - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - requestBody: { - parameterPath: { value: ["value"] }, - mapper: { ...Mappers.UpdateSettingRequest, required: true } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl, Parameters.settingName], - headerParameters: [Parameters.accept, Parameters.contentType], - mediaType: "json", - serializer -}; -const getSettingOperationSpec: coreClient.OperationSpec = { - path: "/settings/{setting-name}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.Setting - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl, Parameters.settingName], - headerParameters: [Parameters.accept], - serializer -}; -const getSettingsOperationSpec: coreClient.OperationSpec = { - path: "/settings", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.SettingsListResult - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [Parameters.vaultBaseUrl], - headerParameters: [Parameters.accept], - serializer -}; diff --git a/sdk/keyvault/keyvault-admin/src/generated/keyVaultClientContext.ts b/sdk/keyvault/keyvault-admin/src/generated/keyVaultClientContext.ts deleted file mode 100644 index 3e81311ae00f..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/keyVaultClientContext.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { ApiVersion75, KeyVaultClientOptionalParams } from "./models/index.js"; - -export class KeyVaultClientContext extends coreClient.ServiceClient { - apiVersion: ApiVersion75; - - /** - * Initializes a new instance of the KeyVaultClientContext class. - * @param apiVersion Api Version - * @param options The parameter options - */ - constructor( - apiVersion: ApiVersion75, - options?: KeyVaultClientOptionalParams - ) { - if (apiVersion === undefined) { - throw new Error("'apiVersion' cannot be null"); - } - - // Initializing default values for options - if (!options) { - options = {}; - } - const defaults: KeyVaultClientOptionalParams = { - requestContentType: "application/json; charset=utf-8" - }; - - const packageDetails = `azsdk-js-keyvault-admin/4.6.1`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - - const optionsWithDefaults = { - ...defaults, - ...options, - userAgentOptions: { - userAgentPrefix - }, - baseUri: options.endpoint || "{vaultBaseUrl}" - }; - super(optionsWithDefaults); - // Parameter assignments - this.apiVersion = apiVersion; - } -} diff --git a/sdk/keyvault/keyvault-admin/src/generated/models/index.ts b/sdk/keyvault/keyvault-admin/src/generated/models/index.ts deleted file mode 100644 index 6ca193d29c71..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/models/index.ts +++ /dev/null @@ -1,632 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; - -/** The key vault error exception. */ -export interface KeyVaultError { - /** - * The key vault server error. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly error?: ErrorModel; -} - -/** The key vault server error. */ -export interface ErrorModel { - /** - * The error code. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly code?: string; - /** - * The error message. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly message?: string; - /** - * The key vault server error. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly innerError?: ErrorModel; -} - -/** Role definition create parameters. */ -export interface RoleDefinitionCreateParameters { - /** Role definition properties. */ - properties: RoleDefinitionProperties; -} - -/** Role definition properties. */ -export interface RoleDefinitionProperties { - /** The role name. */ - roleName?: string; - /** The role definition description. */ - description?: string; - /** The role type. */ - roleType?: RoleType; - /** Role definition permissions. */ - permissions?: Permission[]; - /** Role definition assignable scopes. */ - assignableScopes?: RoleScope[]; -} - -/** Role definition permissions. */ -export interface Permission { - /** Action permissions that are granted. */ - actions?: string[]; - /** Action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. */ - notActions?: string[]; - /** Data action permissions that are granted. */ - dataActions?: DataAction[]; - /** Data action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. */ - notDataActions?: DataAction[]; -} - -/** Role definition. */ -export interface RoleDefinition { - /** - * The role definition ID. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly id?: string; - /** - * The role definition name. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly name?: string; - /** - * The role definition type. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly type?: RoleDefinitionType; - /** The role name. */ - roleName?: string; - /** The role definition description. */ - description?: string; - /** The role type. */ - roleType?: RoleType; - /** Role definition permissions. */ - permissions?: Permission[]; - /** Role definition assignable scopes. */ - assignableScopes?: RoleScope[]; -} - -/** Role definition list operation result. */ -export interface RoleDefinitionListResult { - /** Role definition list. */ - value?: RoleDefinition[]; - /** The URL to use for getting the next set of results. */ - nextLink?: string; -} - -/** Role assignment create parameters. */ -export interface RoleAssignmentCreateParameters { - /** Role assignment properties. */ - properties: RoleAssignmentProperties; -} - -/** Role assignment properties. */ -export interface RoleAssignmentProperties { - /** The role definition ID used in the role assignment. */ - roleDefinitionId: string; - /** The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. */ - principalId: string; -} - -/** Role Assignments */ -export interface RoleAssignment { - /** - * The role assignment ID. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly id?: string; - /** - * The role assignment name. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly name?: string; - /** - * The role assignment type. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly type?: string; - /** Role assignment properties. */ - properties?: RoleAssignmentPropertiesWithScope; -} - -/** Role assignment properties with scope. */ -export interface RoleAssignmentPropertiesWithScope { - /** The role scope. */ - scope?: RoleScope; - /** The role definition ID. */ - roleDefinitionId?: string; - /** The principal ID. */ - principalId?: string; -} - -/** Role assignment list operation result. */ -export interface RoleAssignmentListResult { - /** Role assignment list. */ - value?: RoleAssignment[]; - /** The URL to use for getting the next set of results. */ - nextLink?: string; -} - -export interface SASTokenParameter { - /** Azure Blob storage container Uri */ - storageResourceUri: string; - /** The SAS token pointing to an Azure Blob storage container */ - token?: string; - /** Indicates which authentication method should be used. If set to true, Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. */ - useManagedIdentity?: boolean; -} - -/** Full backup operation */ -export interface FullBackupOperation { - /** Status of the backup operation. */ - status?: string; - /** The status details of backup operation. */ - statusDetails?: string; - /** Error encountered, if any, during the full backup operation. */ - error?: ErrorModel; - /** The start time of the backup operation in UTC */ - startTime?: Date; - /** The end time of the backup operation in UTC */ - endTime?: Date; - /** Identifier for the full backup operation. */ - jobId?: string; - /** The Azure blob storage container Uri which contains the full backup */ - azureStorageBlobContainerUri?: string; -} - -export interface RestoreOperationParameters { - sasTokenParameters: SASTokenParameter; - /** The Folder name of the blob where the previous successful full backup was stored */ - folderToRestore: string; -} - -/** Restore operation */ -export interface RestoreOperation { - /** Status of the restore operation. */ - status?: string; - /** The status details of restore operation. */ - statusDetails?: string; - /** Error encountered, if any, during the restore operation. */ - error?: ErrorModel; - /** Identifier for the restore operation. */ - jobId?: string; - /** The start time of the restore operation */ - startTime?: Date; - /** The end time of the restore operation */ - endTime?: Date; -} - -export interface SelectiveKeyRestoreOperationParameters { - sasTokenParameters: SASTokenParameter; - /** The Folder name of the blob where the previous successful full backup was stored */ - folder: string; -} - -/** Selective Key Restore operation */ -export interface SelectiveKeyRestoreOperation { - /** Status of the restore operation. */ - status?: string; - /** The status details of restore operation. */ - statusDetails?: string; - /** Error encountered, if any, during the selective key restore operation. */ - error?: ErrorModel; - /** Identifier for the selective key restore operation. */ - jobId?: string; - /** The start time of the restore operation */ - startTime?: Date; - /** The end time of the restore operation */ - endTime?: Date; -} - -/** The update settings request object. */ -export interface UpdateSettingRequest { - /** The value of the pool setting. */ - value: string; -} - -export interface Setting { - /** The account setting to be updated */ - name: string; - /** The value of the pool setting. */ - value: string; - /** The type specifier of the value. */ - type?: SettingTypeEnum; -} - -/** The settings list result. */ -export interface SettingsListResult { - /** - * A response message containing a list of account settings with their associated value. - * NOTE: This property will not be serialized. It can only be populated by the server. - */ - readonly settings?: Setting[]; -} - -/** Role Assignments filter */ -export interface RoleAssignmentFilter { - /** Returns role assignment of the specific principal. */ - principalId?: string; -} - -/** Role Definitions filter */ -export interface RoleDefinitionFilter { - /** Returns role definition with the specific name. */ - roleName?: string; -} - -/** Defines headers for KeyVaultClient_fullBackup operation. */ -export interface KeyVaultClientFullBackupHeaders { - /** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */ - retryAfter?: number; - /** The URI to poll for completion status. */ - azureAsyncOperation?: string; -} - -/** Defines headers for KeyVaultClient_fullRestoreOperation operation. */ -export interface KeyVaultClientFullRestoreOperationHeaders { - /** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */ - retryAfter?: number; - /** The URI to poll for completion status. */ - azureAsyncOperation?: string; -} - -/** Defines headers for KeyVaultClient_selectiveKeyRestoreOperation operation. */ -export interface KeyVaultClientSelectiveKeyRestoreOperationHeaders { - /** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */ - retryAfter?: number; - /** The URI to poll for completion status. */ - azureAsyncOperation?: string; -} - -/** Known values of {@link ApiVersion75} that the service accepts. */ -export enum KnownApiVersion75 { - /** Api Version '7.5' */ - Seven5 = "7.5" -} - -/** - * Defines values for ApiVersion75. \ - * {@link KnownApiVersion75} can be used interchangeably with ApiVersion75, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **7.5**: Api Version '7.5' - */ -export type ApiVersion75 = string; - -/** Known values of {@link RoleType} that the service accepts. */ -export enum KnownRoleType { - /** Built in role. */ - BuiltInRole = "AKVBuiltInRole", - /** Custom role. */ - CustomRole = "CustomRole" -} - -/** - * Defines values for RoleType. \ - * {@link KnownRoleType} can be used interchangeably with RoleType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKVBuiltInRole**: Built in role. \ - * **CustomRole**: Custom role. - */ -export type RoleType = string; - -/** Known values of {@link DataAction} that the service accepts. */ -export enum KnownDataAction { - /** Read HSM key metadata. */ - ReadHsmKey = "Microsoft.KeyVault/managedHsm/keys/read/action", - /** Update an HSM key. */ - WriteHsmKey = "Microsoft.KeyVault/managedHsm/keys/write/action", - /** Read deleted HSM key. */ - ReadDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/read/action", - /** Recover deleted HSM key. */ - RecoverDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/recover/action", - /** Backup HSM keys. */ - BackupHsmKeys = "Microsoft.KeyVault/managedHsm/keys/backup/action", - /** Restore HSM keys. */ - RestoreHsmKeys = "Microsoft.KeyVault/managedHsm/keys/restore/action", - /** Delete role assignment. */ - DeleteRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/delete/action", - /** Get role assignment. */ - GetRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/read/action", - /** Create or update role assignment. */ - WriteRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/write/action", - /** Get role definition. */ - ReadRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/read/action", - /** Create or update role definition. */ - WriteRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/write/action", - /** Delete role definition. */ - DeleteRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/delete/action", - /** Encrypt using an HSM key. */ - EncryptHsmKey = "Microsoft.KeyVault/managedHsm/keys/encrypt/action", - /** Decrypt using an HSM key. */ - DecryptHsmKey = "Microsoft.KeyVault/managedHsm/keys/decrypt/action", - /** Wrap using an HSM key. */ - WrapHsmKey = "Microsoft.KeyVault/managedHsm/keys/wrap/action", - /** Unwrap using an HSM key. */ - UnwrapHsmKey = "Microsoft.KeyVault/managedHsm/keys/unwrap/action", - /** Sign using an HSM key. */ - SignHsmKey = "Microsoft.KeyVault/managedHsm/keys/sign/action", - /** Verify using an HSM key. */ - VerifyHsmKey = "Microsoft.KeyVault/managedHsm/keys/verify/action", - /** Create an HSM key. */ - CreateHsmKey = "Microsoft.KeyVault/managedHsm/keys/create", - /** Delete an HSM key. */ - DeleteHsmKey = "Microsoft.KeyVault/managedHsm/keys/delete", - /** Export an HSM key. */ - ExportHsmKey = "Microsoft.KeyVault/managedHsm/keys/export/action", - /** Release an HSM key using Secure Key Release. */ - ReleaseKey = "Microsoft.KeyVault/managedHsm/keys/release/action", - /** Import an HSM key. */ - ImportHsmKey = "Microsoft.KeyVault/managedHsm/keys/import/action", - /** Purge a deleted HSM key. */ - PurgeDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/delete", - /** Download an HSM security domain. */ - DownloadHsmSecurityDomain = "Microsoft.KeyVault/managedHsm/securitydomain/download/action", - /** Check status of HSM security domain download. */ - DownloadHsmSecurityDomainStatus = "Microsoft.KeyVault/managedHsm/securitydomain/download/read", - /** Upload an HSM security domain. */ - UploadHsmSecurityDomain = "Microsoft.KeyVault/managedHsm/securitydomain/upload/action", - /** Check the status of the HSM security domain exchange file. */ - ReadHsmSecurityDomainStatus = "Microsoft.KeyVault/managedHsm/securitydomain/upload/read", - /** Download an HSM security domain transfer key. */ - ReadHsmSecurityDomainTransferKey = "Microsoft.KeyVault/managedHsm/securitydomain/transferkey/read", - /** Start an HSM backup. */ - StartHsmBackup = "Microsoft.KeyVault/managedHsm/backup/start/action", - /** Start an HSM restore. */ - StartHsmRestore = "Microsoft.KeyVault/managedHsm/restore/start/action", - /** Read an HSM backup status. */ - ReadHsmBackupStatus = "Microsoft.KeyVault/managedHsm/backup/status/action", - /** Read an HSM restore status. */ - ReadHsmRestoreStatus = "Microsoft.KeyVault/managedHsm/restore/status/action", - /** Generate random numbers. */ - RandomNumbersGenerate = "Microsoft.KeyVault/managedHsm/rng/action" -} - -/** - * Defines values for DataAction. \ - * {@link KnownDataAction} can be used interchangeably with DataAction, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Microsoft.KeyVault\/managedHsm\/keys\/read\/action**: Read HSM key metadata. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/write\/action**: Update an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/deletedKeys\/read\/action**: Read deleted HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/deletedKeys\/recover\/action**: Recover deleted HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/backup\/action**: Backup HSM keys. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/restore\/action**: Restore HSM keys. \ - * **Microsoft.KeyVault\/managedHsm\/roleAssignments\/delete\/action**: Delete role assignment. \ - * **Microsoft.KeyVault\/managedHsm\/roleAssignments\/read\/action**: Get role assignment. \ - * **Microsoft.KeyVault\/managedHsm\/roleAssignments\/write\/action**: Create or update role assignment. \ - * **Microsoft.KeyVault\/managedHsm\/roleDefinitions\/read\/action**: Get role definition. \ - * **Microsoft.KeyVault\/managedHsm\/roleDefinitions\/write\/action**: Create or update role definition. \ - * **Microsoft.KeyVault\/managedHsm\/roleDefinitions\/delete\/action**: Delete role definition. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/encrypt\/action**: Encrypt using an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/decrypt\/action**: Decrypt using an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/wrap\/action**: Wrap using an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/unwrap\/action**: Unwrap using an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/sign\/action**: Sign using an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/verify\/action**: Verify using an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/create**: Create an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/delete**: Delete an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/export\/action**: Export an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/release\/action**: Release an HSM key using Secure Key Release. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/import\/action**: Import an HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/keys\/deletedKeys\/delete**: Purge a deleted HSM key. \ - * **Microsoft.KeyVault\/managedHsm\/securitydomain\/download\/action**: Download an HSM security domain. \ - * **Microsoft.KeyVault\/managedHsm\/securitydomain\/download\/read**: Check status of HSM security domain download. \ - * **Microsoft.KeyVault\/managedHsm\/securitydomain\/upload\/action**: Upload an HSM security domain. \ - * **Microsoft.KeyVault\/managedHsm\/securitydomain\/upload\/read**: Check the status of the HSM security domain exchange file. \ - * **Microsoft.KeyVault\/managedHsm\/securitydomain\/transferkey\/read**: Download an HSM security domain transfer key. \ - * **Microsoft.KeyVault\/managedHsm\/backup\/start\/action**: Start an HSM backup. \ - * **Microsoft.KeyVault\/managedHsm\/restore\/start\/action**: Start an HSM restore. \ - * **Microsoft.KeyVault\/managedHsm\/backup\/status\/action**: Read an HSM backup status. \ - * **Microsoft.KeyVault\/managedHsm\/restore\/status\/action**: Read an HSM restore status. \ - * **Microsoft.KeyVault\/managedHsm\/rng\/action**: Generate random numbers. - */ -export type DataAction = string; - -/** Known values of {@link RoleScope} that the service accepts. */ -export enum KnownRoleScope { - /** Global scope */ - Global = "/", - /** Keys scope */ - Keys = "/keys" -} - -/** - * Defines values for RoleScope. \ - * {@link KnownRoleScope} can be used interchangeably with RoleScope, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **\/**: Global scope \ - * **\/keys**: Keys scope - */ -export type RoleScope = string; - -/** Known values of {@link RoleDefinitionType} that the service accepts. */ -export enum KnownRoleDefinitionType { - MicrosoftAuthorizationRoleDefinitions = "Microsoft.Authorization/roleDefinitions" -} - -/** - * Defines values for RoleDefinitionType. \ - * {@link KnownRoleDefinitionType} can be used interchangeably with RoleDefinitionType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Microsoft.Authorization\/roleDefinitions** - */ -export type RoleDefinitionType = string; - -/** Known values of {@link SettingTypeEnum} that the service accepts. */ -export enum KnownSettingTypeEnum { - Boolean = "boolean" -} - -/** - * Defines values for SettingTypeEnum. \ - * {@link KnownSettingTypeEnum} can be used interchangeably with SettingTypeEnum, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **boolean** - */ -export type SettingTypeEnum = string; - -/** Optional parameters. */ -export interface RoleDefinitionsDeleteOptionalParams - extends coreClient.OperationOptions {} - -/** Optional parameters. */ -export interface RoleDefinitionsCreateOrUpdateOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the createOrUpdate operation. */ -export type RoleDefinitionsCreateOrUpdateResponse = RoleDefinition; - -/** Optional parameters. */ -export interface RoleDefinitionsGetOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the get operation. */ -export type RoleDefinitionsGetResponse = RoleDefinition; - -/** Optional parameters. */ -export interface RoleDefinitionsListOptionalParams - extends coreClient.OperationOptions { - /** The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. */ - filter?: string; -} - -/** Contains response data for the list operation. */ -export type RoleDefinitionsListResponse = RoleDefinitionListResult; - -/** Optional parameters. */ -export interface RoleDefinitionsListNextOptionalParams - extends coreClient.OperationOptions { - /** The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. */ - filter?: string; -} - -/** Contains response data for the listNext operation. */ -export type RoleDefinitionsListNextResponse = RoleDefinitionListResult; - -/** Optional parameters. */ -export interface RoleAssignmentsDeleteOptionalParams - extends coreClient.OperationOptions {} - -/** Optional parameters. */ -export interface RoleAssignmentsCreateOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the create operation. */ -export type RoleAssignmentsCreateResponse = RoleAssignment; - -/** Optional parameters. */ -export interface RoleAssignmentsGetOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the get operation. */ -export type RoleAssignmentsGetResponse = RoleAssignment; - -/** Optional parameters. */ -export interface RoleAssignmentsListForScopeOptionalParams - extends coreClient.OperationOptions { - /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ - filter?: string; -} - -/** Contains response data for the listForScope operation. */ -export type RoleAssignmentsListForScopeResponse = RoleAssignmentListResult; - -/** Optional parameters. */ -export interface RoleAssignmentsListForScopeNextOptionalParams - extends coreClient.OperationOptions { - /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ - filter?: string; -} - -/** Contains response data for the listForScopeNext operation. */ -export type RoleAssignmentsListForScopeNextResponse = RoleAssignmentListResult; - -/** Optional parameters. */ -export interface FullBackupOptionalParams extends coreClient.OperationOptions { - /** Azure blob shared access signature token pointing to a valid Azure blob container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the time of making this call */ - azureStorageBlobContainerUri?: SASTokenParameter; -} - -/** Contains response data for the fullBackup operation. */ -export type FullBackupResponse = KeyVaultClientFullBackupHeaders & - FullBackupOperation; - -/** Optional parameters. */ -export interface FullBackupStatusOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the fullBackupStatus operation. */ -export type FullBackupStatusResponse = FullBackupOperation; - -/** Optional parameters. */ -export interface FullRestoreOperationOptionalParams - extends coreClient.OperationOptions { - /** The Azure blob SAS token pointing to a folder where the previous successful full backup was stored */ - restoreBlobDetails?: RestoreOperationParameters; -} - -/** Contains response data for the fullRestoreOperation operation. */ -export type FullRestoreOperationResponse = KeyVaultClientFullRestoreOperationHeaders & - RestoreOperation; - -/** Optional parameters. */ -export interface RestoreStatusOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the restoreStatus operation. */ -export type RestoreStatusResponse = RestoreOperation; - -/** Optional parameters. */ -export interface SelectiveKeyRestoreOperationOptionalParams - extends coreClient.OperationOptions { - /** The Azure blob SAS token pointing to a folder where the previous successful full backup was stored */ - restoreBlobDetails?: SelectiveKeyRestoreOperationParameters; -} - -/** Contains response data for the selectiveKeyRestoreOperation operation. */ -export type SelectiveKeyRestoreOperationResponse = KeyVaultClientSelectiveKeyRestoreOperationHeaders & - SelectiveKeyRestoreOperation; - -/** Optional parameters. */ -export interface UpdateSettingOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the updateSetting operation. */ -export type UpdateSettingResponse = Setting; - -/** Optional parameters. */ -export interface GetSettingOptionalParams extends coreClient.OperationOptions {} - -/** Contains response data for the getSetting operation. */ -export type GetSettingResponse = Setting; - -/** Optional parameters. */ -export interface GetSettingsOptionalParams - extends coreClient.OperationOptions {} - -/** Contains response data for the getSettings operation. */ -export type GetSettingsResponse = SettingsListResult; - -/** Optional parameters. */ -export interface KeyVaultClientOptionalParams - extends coreClient.ServiceClientOptions { - /** Overrides client endpoint. */ - endpoint?: string; -} diff --git a/sdk/keyvault/keyvault-admin/src/generated/models/mappers.ts b/sdk/keyvault/keyvault-admin/src/generated/models/mappers.ts deleted file mode 100644 index c06ef2547b1f..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/models/mappers.ts +++ /dev/null @@ -1,784 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; - -export const KeyVaultError: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "KeyVaultError", - modelProperties: { - error: { - serializedName: "error", - type: { - name: "Composite", - className: "ErrorModel" - } - } - } - } -}; - -export const ErrorModel: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "ErrorModel", - modelProperties: { - code: { - serializedName: "code", - readOnly: true, - type: { - name: "String" - } - }, - message: { - serializedName: "message", - readOnly: true, - type: { - name: "String" - } - }, - innerError: { - serializedName: "innererror", - type: { - name: "Composite", - className: "ErrorModel" - } - } - } - } -}; - -export const RoleDefinitionCreateParameters: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleDefinitionCreateParameters", - modelProperties: { - properties: { - serializedName: "properties", - type: { - name: "Composite", - className: "RoleDefinitionProperties" - } - } - } - } -}; - -export const RoleDefinitionProperties: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleDefinitionProperties", - modelProperties: { - roleName: { - serializedName: "roleName", - type: { - name: "String" - } - }, - description: { - serializedName: "description", - type: { - name: "String" - } - }, - roleType: { - serializedName: "type", - type: { - name: "String" - } - }, - permissions: { - serializedName: "permissions", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "Permission" - } - } - } - }, - assignableScopes: { - serializedName: "assignableScopes", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - } - } - } -}; - -export const Permission: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "Permission", - modelProperties: { - actions: { - serializedName: "actions", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - }, - notActions: { - serializedName: "notActions", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - }, - dataActions: { - serializedName: "dataActions", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - }, - notDataActions: { - serializedName: "notDataActions", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - } - } - } -}; - -export const RoleDefinition: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleDefinition", - modelProperties: { - id: { - serializedName: "id", - readOnly: true, - type: { - name: "String" - } - }, - name: { - serializedName: "name", - readOnly: true, - type: { - name: "String" - } - }, - type: { - serializedName: "type", - readOnly: true, - type: { - name: "String" - } - }, - roleName: { - serializedName: "properties.roleName", - type: { - name: "String" - } - }, - description: { - serializedName: "properties.description", - type: { - name: "String" - } - }, - roleType: { - serializedName: "properties.type", - type: { - name: "String" - } - }, - permissions: { - serializedName: "properties.permissions", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "Permission" - } - } - } - }, - assignableScopes: { - serializedName: "properties.assignableScopes", - type: { - name: "Sequence", - element: { - type: { - name: "String" - } - } - } - } - } - } -}; - -export const RoleDefinitionListResult: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleDefinitionListResult", - modelProperties: { - value: { - serializedName: "value", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "RoleDefinition" - } - } - } - }, - nextLink: { - serializedName: "nextLink", - type: { - name: "String" - } - } - } - } -}; - -export const RoleAssignmentCreateParameters: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleAssignmentCreateParameters", - modelProperties: { - properties: { - serializedName: "properties", - type: { - name: "Composite", - className: "RoleAssignmentProperties" - } - } - } - } -}; - -export const RoleAssignmentProperties: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleAssignmentProperties", - modelProperties: { - roleDefinitionId: { - serializedName: "roleDefinitionId", - required: true, - type: { - name: "String" - } - }, - principalId: { - serializedName: "principalId", - required: true, - type: { - name: "String" - } - } - } - } -}; - -export const RoleAssignment: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleAssignment", - modelProperties: { - id: { - serializedName: "id", - readOnly: true, - type: { - name: "String" - } - }, - name: { - serializedName: "name", - readOnly: true, - type: { - name: "String" - } - }, - type: { - serializedName: "type", - readOnly: true, - type: { - name: "String" - } - }, - properties: { - serializedName: "properties", - type: { - name: "Composite", - className: "RoleAssignmentPropertiesWithScope" - } - } - } - } -}; - -export const RoleAssignmentPropertiesWithScope: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleAssignmentPropertiesWithScope", - modelProperties: { - scope: { - serializedName: "scope", - type: { - name: "String" - } - }, - roleDefinitionId: { - serializedName: "roleDefinitionId", - type: { - name: "String" - } - }, - principalId: { - serializedName: "principalId", - type: { - name: "String" - } - } - } - } -}; - -export const RoleAssignmentListResult: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleAssignmentListResult", - modelProperties: { - value: { - serializedName: "value", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "RoleAssignment" - } - } - } - }, - nextLink: { - serializedName: "nextLink", - type: { - name: "String" - } - } - } - } -}; - -export const SASTokenParameter: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "SASTokenParameter", - modelProperties: { - storageResourceUri: { - serializedName: "storageResourceUri", - required: true, - type: { - name: "String" - } - }, - token: { - serializedName: "token", - type: { - name: "String" - } - }, - useManagedIdentity: { - defaultValue: false, - serializedName: "useManagedIdentity", - type: { - name: "Boolean" - } - } - } - } -}; - -export const FullBackupOperation: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "FullBackupOperation", - modelProperties: { - status: { - serializedName: "status", - type: { - name: "String" - } - }, - statusDetails: { - serializedName: "statusDetails", - type: { - name: "String" - } - }, - error: { - serializedName: "error", - type: { - name: "Composite", - className: "ErrorModel" - } - }, - startTime: { - serializedName: "startTime", - type: { - name: "UnixTime" - } - }, - endTime: { - serializedName: "endTime", - nullable: true, - type: { - name: "UnixTime" - } - }, - jobId: { - serializedName: "jobId", - type: { - name: "String" - } - }, - azureStorageBlobContainerUri: { - serializedName: "azureStorageBlobContainerUri", - type: { - name: "String" - } - } - } - } -}; - -export const RestoreOperationParameters: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RestoreOperationParameters", - modelProperties: { - sasTokenParameters: { - serializedName: "sasTokenParameters", - type: { - name: "Composite", - className: "SASTokenParameter" - } - }, - folderToRestore: { - serializedName: "folderToRestore", - required: true, - type: { - name: "String" - } - } - } - } -}; - -export const RestoreOperation: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RestoreOperation", - modelProperties: { - status: { - serializedName: "status", - type: { - name: "String" - } - }, - statusDetails: { - serializedName: "statusDetails", - type: { - name: "String" - } - }, - error: { - serializedName: "error", - type: { - name: "Composite", - className: "ErrorModel" - } - }, - jobId: { - serializedName: "jobId", - type: { - name: "String" - } - }, - startTime: { - serializedName: "startTime", - type: { - name: "UnixTime" - } - }, - endTime: { - serializedName: "endTime", - nullable: true, - type: { - name: "UnixTime" - } - } - } - } -}; - -export const SelectiveKeyRestoreOperationParameters: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "SelectiveKeyRestoreOperationParameters", - modelProperties: { - sasTokenParameters: { - serializedName: "sasTokenParameters", - type: { - name: "Composite", - className: "SASTokenParameter" - } - }, - folder: { - serializedName: "folder", - required: true, - type: { - name: "String" - } - } - } - } -}; - -export const SelectiveKeyRestoreOperation: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "SelectiveKeyRestoreOperation", - modelProperties: { - status: { - serializedName: "status", - type: { - name: "String" - } - }, - statusDetails: { - serializedName: "statusDetails", - type: { - name: "String" - } - }, - error: { - serializedName: "error", - type: { - name: "Composite", - className: "ErrorModel" - } - }, - jobId: { - serializedName: "jobId", - type: { - name: "String" - } - }, - startTime: { - serializedName: "startTime", - type: { - name: "UnixTime" - } - }, - endTime: { - serializedName: "endTime", - nullable: true, - type: { - name: "UnixTime" - } - } - } - } -}; - -export const UpdateSettingRequest: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "UpdateSettingRequest", - modelProperties: { - value: { - serializedName: "value", - required: true, - type: { - name: "String" - } - } - } - } -}; - -export const Setting: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "Setting", - modelProperties: { - name: { - serializedName: "name", - required: true, - type: { - name: "String" - } - }, - value: { - serializedName: "value", - required: true, - type: { - name: "String" - } - }, - type: { - serializedName: "type", - type: { - name: "String" - } - } - } - } -}; - -export const SettingsListResult: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "SettingsListResult", - modelProperties: { - settings: { - serializedName: "settings", - readOnly: true, - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "Setting" - } - } - } - } - } - } -}; - -export const RoleAssignmentFilter: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleAssignmentFilter", - modelProperties: { - principalId: { - serializedName: "principalId", - type: { - name: "String" - } - } - } - } -}; - -export const RoleDefinitionFilter: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "RoleDefinitionFilter", - modelProperties: { - roleName: { - serializedName: "roleName", - type: { - name: "String" - } - } - } - } -}; - -export const KeyVaultClientFullBackupHeaders: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "KeyVaultClientFullBackupHeaders", - modelProperties: { - retryAfter: { - serializedName: "retry-after", - type: { - name: "Number" - } - }, - azureAsyncOperation: { - serializedName: "azure-asyncoperation", - type: { - name: "String" - } - } - } - } -}; - -export const KeyVaultClientFullRestoreOperationHeaders: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "KeyVaultClientFullRestoreOperationHeaders", - modelProperties: { - retryAfter: { - serializedName: "retry-after", - type: { - name: "Number" - } - }, - azureAsyncOperation: { - serializedName: "azure-asyncoperation", - type: { - name: "String" - } - } - } - } -}; - -export const KeyVaultClientSelectiveKeyRestoreOperationHeaders: coreClient.CompositeMapper = { - type: { - name: "Composite", - className: "KeyVaultClientSelectiveKeyRestoreOperationHeaders", - modelProperties: { - retryAfter: { - serializedName: "retry-after", - type: { - name: "Number" - } - }, - azureAsyncOperation: { - serializedName: "azure-asyncoperation", - type: { - name: "String" - } - } - } - } -}; diff --git a/sdk/keyvault/keyvault-admin/src/generated/models/parameters.ts b/sdk/keyvault/keyvault-admin/src/generated/models/parameters.ts deleted file mode 100644 index 10d8ee6fc087..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/models/parameters.ts +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import { - OperationParameter, - OperationURLParameter, - OperationQueryParameter -} from "@azure/core-client"; -import { - RoleDefinitionCreateParameters as RoleDefinitionCreateParametersMapper, - RoleAssignmentCreateParameters as RoleAssignmentCreateParametersMapper, - SASTokenParameter as SASTokenParameterMapper, - RestoreOperationParameters as RestoreOperationParametersMapper, - SelectiveKeyRestoreOperationParameters as SelectiveKeyRestoreOperationParametersMapper, - UpdateSettingRequest as UpdateSettingRequestMapper -} from "../models/mappers.js"; - -export const accept: OperationParameter = { - parameterPath: "accept", - mapper: { - defaultValue: "application/json", - isConstant: true, - serializedName: "Accept", - type: { - name: "String" - } - } -}; - -export const vaultBaseUrl: OperationURLParameter = { - parameterPath: "vaultBaseUrl", - mapper: { - serializedName: "vaultBaseUrl", - required: true, - type: { - name: "String" - } - }, - skipEncoding: true -}; - -export const scope: OperationURLParameter = { - parameterPath: "scope", - mapper: { - serializedName: "scope", - required: true, - type: { - name: "String" - } - }, - skipEncoding: true -}; - -export const roleDefinitionName: OperationURLParameter = { - parameterPath: "roleDefinitionName", - mapper: { - serializedName: "roleDefinitionName", - required: true, - type: { - name: "String" - } - } -}; - -export const apiVersion: OperationQueryParameter = { - parameterPath: "apiVersion", - mapper: { - serializedName: "api-version", - required: true, - type: { - name: "String" - } - } -}; - -export const contentType: OperationParameter = { - parameterPath: ["options", "contentType"], - mapper: { - defaultValue: "application/json", - isConstant: true, - serializedName: "Content-Type", - type: { - name: "String" - } - } -}; - -export const parameters: OperationParameter = { - parameterPath: "parameters", - mapper: RoleDefinitionCreateParametersMapper -}; - -export const filter: OperationQueryParameter = { - parameterPath: ["options", "filter"], - mapper: { - serializedName: "$filter", - type: { - name: "String" - } - } -}; - -export const nextLink: OperationURLParameter = { - parameterPath: "nextLink", - mapper: { - serializedName: "nextLink", - required: true, - type: { - name: "String" - } - }, - skipEncoding: true -}; - -export const roleAssignmentName: OperationURLParameter = { - parameterPath: "roleAssignmentName", - mapper: { - serializedName: "roleAssignmentName", - required: true, - type: { - name: "String" - } - } -}; - -export const parameters1: OperationParameter = { - parameterPath: "parameters", - mapper: RoleAssignmentCreateParametersMapper -}; - -export const azureStorageBlobContainerUri: OperationParameter = { - parameterPath: ["options", "azureStorageBlobContainerUri"], - mapper: SASTokenParameterMapper -}; - -export const jobId: OperationURLParameter = { - parameterPath: "jobId", - mapper: { - serializedName: "jobId", - required: true, - type: { - name: "String" - } - } -}; - -export const restoreBlobDetails: OperationParameter = { - parameterPath: ["options", "restoreBlobDetails"], - mapper: RestoreOperationParametersMapper -}; - -export const restoreBlobDetails1: OperationParameter = { - parameterPath: ["options", "restoreBlobDetails"], - mapper: SelectiveKeyRestoreOperationParametersMapper -}; - -export const keyName: OperationURLParameter = { - parameterPath: "keyName", - mapper: { - serializedName: "keyName", - required: true, - type: { - name: "String" - } - } -}; - -export const value: OperationParameter = { - parameterPath: "value", - mapper: UpdateSettingRequestMapper -}; - -export const settingName: OperationURLParameter = { - parameterPath: "settingName", - mapper: { - serializedName: "setting-name", - required: true, - type: { - name: "String" - } - } -}; diff --git a/sdk/keyvault/keyvault-admin/src/generated/operations/index.ts b/sdk/keyvault/keyvault-admin/src/generated/operations/index.ts deleted file mode 100644 index b7ab5f5ab28b..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/operations/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -export * from "./roleDefinitions.js"; -export * from "./roleAssignments.js"; diff --git a/sdk/keyvault/keyvault-admin/src/generated/operations/roleAssignments.ts b/sdk/keyvault/keyvault-admin/src/generated/operations/roleAssignments.ts deleted file mode 100644 index ba5f0ac923c8..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/operations/roleAssignments.ts +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import { RoleAssignments } from "../operationsInterfaces/index.js"; -import * as coreClient from "@azure/core-client"; -import * as Mappers from "../models/mappers.js"; -import * as Parameters from "../models/parameters.js"; -import { KeyVaultClientContext } from "../keyVaultClientContext.js"; -import { - RoleAssignmentsDeleteOptionalParams, - RoleAssignmentCreateParameters, - RoleAssignmentsCreateOptionalParams, - RoleAssignmentsCreateResponse, - RoleAssignmentsGetOptionalParams, - RoleAssignmentsGetResponse, - RoleAssignmentsListForScopeOptionalParams, - RoleAssignmentsListForScopeResponse, - RoleAssignmentsListForScopeNextOptionalParams, - RoleAssignmentsListForScopeNextResponse -} from "../models/index.js"; - -/** Class containing RoleAssignments operations. */ -export class RoleAssignmentsImpl implements RoleAssignments { - private readonly client: KeyVaultClientContext; - - /** - * Initialize a new instance of the class RoleAssignments class. - * @param client Reference to the service client - */ - constructor(client: KeyVaultClientContext) { - this.client = client; - } - - /** - * Deletes a role assignment. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @param options The options parameters. - */ - delete( - vaultBaseUrl: string, - scope: string, - roleAssignmentName: string, - options?: RoleAssignmentsDeleteOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, roleAssignmentName, options }, - deleteOperationSpec - ); - } - - /** - * Creates a role assignment. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @param options The options parameters. - */ - create( - vaultBaseUrl: string, - scope: string, - roleAssignmentName: string, - parameters: RoleAssignmentCreateParameters, - options?: RoleAssignmentsCreateOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, roleAssignmentName, parameters, options }, - createOperationSpec - ); - } - - /** - * Get the specified role assignment. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @param options The options parameters. - */ - get( - vaultBaseUrl: string, - scope: string, - roleAssignmentName: string, - options?: RoleAssignmentsGetOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, roleAssignmentName, options }, - getOperationSpec - ); - } - - /** - * Gets role assignments for a scope. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param options The options parameters. - */ - listForScope( - vaultBaseUrl: string, - scope: string, - options?: RoleAssignmentsListForScopeOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, options }, - listForScopeOperationSpec - ); - } - - /** - * ListForScopeNext - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param nextLink The nextLink from the previous successful call to the ListForScope method. - * @param options The options parameters. - */ - listForScopeNext( - vaultBaseUrl: string, - scope: string, - nextLink: string, - options?: RoleAssignmentsListForScopeNextOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, nextLink, options }, - listForScopeNextOperationSpec - ); - } -} -// Operation Specifications -const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); - -const deleteOperationSpec: coreClient.OperationSpec = { - path: - "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", - httpMethod: "DELETE", - responses: { - 200: {}, - 404: {}, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.roleAssignmentName - ], - headerParameters: [Parameters.accept], - serializer -}; -const createOperationSpec: coreClient.OperationSpec = { - path: - "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", - httpMethod: "PUT", - responses: { - 201: { - bodyMapper: Mappers.RoleAssignment - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - requestBody: Parameters.parameters1, - queryParameters: [Parameters.apiVersion], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.roleAssignmentName - ], - headerParameters: [Parameters.accept, Parameters.contentType], - mediaType: "json", - serializer -}; -const getOperationSpec: coreClient.OperationSpec = { - path: - "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.RoleAssignment - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.roleAssignmentName - ], - headerParameters: [Parameters.accept], - serializer -}; -const listForScopeOperationSpec: coreClient.OperationSpec = { - path: "/{scope}/providers/Microsoft.Authorization/roleAssignments", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.RoleAssignmentListResult - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion, Parameters.filter], - urlParameters: [Parameters.vaultBaseUrl, Parameters.scope], - headerParameters: [Parameters.accept], - serializer -}; -const listForScopeNextOperationSpec: coreClient.OperationSpec = { - path: "{nextLink}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.RoleAssignmentListResult - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion, Parameters.filter], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.nextLink - ], - headerParameters: [Parameters.accept], - serializer -}; diff --git a/sdk/keyvault/keyvault-admin/src/generated/operations/roleDefinitions.ts b/sdk/keyvault/keyvault-admin/src/generated/operations/roleDefinitions.ts deleted file mode 100644 index bc0e124db9ba..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/operations/roleDefinitions.ts +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import { RoleDefinitions } from "../operationsInterfaces/index.js"; -import * as coreClient from "@azure/core-client"; -import * as Mappers from "../models/mappers.js"; -import * as Parameters from "../models/parameters.js"; -import { KeyVaultClientContext } from "../keyVaultClientContext.js"; -import { - RoleDefinitionsDeleteOptionalParams, - RoleDefinitionCreateParameters, - RoleDefinitionsCreateOrUpdateOptionalParams, - RoleDefinitionsCreateOrUpdateResponse, - RoleDefinitionsGetOptionalParams, - RoleDefinitionsGetResponse, - RoleDefinitionsListOptionalParams, - RoleDefinitionsListResponse, - RoleDefinitionsListNextOptionalParams, - RoleDefinitionsListNextResponse -} from "../models/index.js"; - -/** Class containing RoleDefinitions operations. */ -export class RoleDefinitionsImpl implements RoleDefinitions { - private readonly client: KeyVaultClientContext; - - /** - * Initialize a new instance of the class RoleDefinitions class. - * @param client Reference to the service client - */ - constructor(client: KeyVaultClientContext) { - this.client = client; - } - - /** - * Deletes a custom role definition. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @param options The options parameters. - */ - delete( - vaultBaseUrl: string, - scope: string, - roleDefinitionName: string, - options?: RoleDefinitionsDeleteOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, roleDefinitionName, options }, - deleteOperationSpec - ); - } - - /** - * Creates or updates a custom role definition. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid - * GUID. - * @param parameters Parameters for the role definition. - * @param options The options parameters. - */ - createOrUpdate( - vaultBaseUrl: string, - scope: string, - roleDefinitionName: string, - parameters: RoleDefinitionCreateParameters, - options?: RoleDefinitionsCreateOrUpdateOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, roleDefinitionName, parameters, options }, - createOrUpdateOperationSpec - ); - } - - /** - * Get the specified role definition. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @param options The options parameters. - */ - get( - vaultBaseUrl: string, - scope: string, - roleDefinitionName: string, - options?: RoleDefinitionsGetOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, roleDefinitionName, options }, - getOperationSpec - ); - } - - /** - * Get all role definitions that are applicable at scope and above. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param options The options parameters. - */ - list( - vaultBaseUrl: string, - scope: string, - options?: RoleDefinitionsListOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, options }, - listOperationSpec - ); - } - - /** - * ListNext - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param nextLink The nextLink from the previous successful call to the List method. - * @param options The options parameters. - */ - listNext( - vaultBaseUrl: string, - scope: string, - nextLink: string, - options?: RoleDefinitionsListNextOptionalParams - ): Promise { - return this.client.sendOperationRequest( - { vaultBaseUrl, scope, nextLink, options }, - listNextOperationSpec - ); - } -} -// Operation Specifications -const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); - -const deleteOperationSpec: coreClient.OperationSpec = { - path: - "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}", - httpMethod: "DELETE", - responses: { - 200: {}, - 404: {}, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.roleDefinitionName - ], - headerParameters: [Parameters.accept], - serializer -}; -const createOrUpdateOperationSpec: coreClient.OperationSpec = { - path: - "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}", - httpMethod: "PUT", - responses: { - 201: { - bodyMapper: Mappers.RoleDefinition - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - requestBody: Parameters.parameters, - queryParameters: [Parameters.apiVersion], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.roleDefinitionName - ], - headerParameters: [Parameters.accept, Parameters.contentType], - mediaType: "json", - serializer -}; -const getOperationSpec: coreClient.OperationSpec = { - path: - "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.RoleDefinition - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.roleDefinitionName - ], - headerParameters: [Parameters.accept], - serializer -}; -const listOperationSpec: coreClient.OperationSpec = { - path: "/{scope}/providers/Microsoft.Authorization/roleDefinitions", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.RoleDefinitionListResult - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion, Parameters.filter], - urlParameters: [Parameters.vaultBaseUrl, Parameters.scope], - headerParameters: [Parameters.accept], - serializer -}; -const listNextOperationSpec: coreClient.OperationSpec = { - path: "{nextLink}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.RoleDefinitionListResult - }, - default: { - bodyMapper: Mappers.KeyVaultError - } - }, - queryParameters: [Parameters.apiVersion, Parameters.filter], - urlParameters: [ - Parameters.vaultBaseUrl, - Parameters.scope, - Parameters.nextLink - ], - headerParameters: [Parameters.accept], - serializer -}; diff --git a/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/index.ts b/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/index.ts deleted file mode 100644 index b7ab5f5ab28b..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -export * from "./roleDefinitions.js"; -export * from "./roleAssignments.js"; diff --git a/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleAssignments.ts b/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleAssignments.ts deleted file mode 100644 index e6a0ffc434f6..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleAssignments.ts +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import { - RoleAssignmentsDeleteOptionalParams, - RoleAssignmentCreateParameters, - RoleAssignmentsCreateOptionalParams, - RoleAssignmentsCreateResponse, - RoleAssignmentsGetOptionalParams, - RoleAssignmentsGetResponse, - RoleAssignmentsListForScopeOptionalParams, - RoleAssignmentsListForScopeResponse, - RoleAssignmentsListForScopeNextOptionalParams, - RoleAssignmentsListForScopeNextResponse -} from "../models/index.js"; - -/** Interface representing a RoleAssignments. */ -export interface RoleAssignments { - /** - * Deletes a role assignment. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @param options The options parameters. - */ - delete( - vaultBaseUrl: string, - scope: string, - roleAssignmentName: string, - options?: RoleAssignmentsDeleteOptionalParams - ): Promise; - /** - * Creates a role assignment. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @param options The options parameters. - */ - create( - vaultBaseUrl: string, - scope: string, - roleAssignmentName: string, - parameters: RoleAssignmentCreateParameters, - options?: RoleAssignmentsCreateOptionalParams - ): Promise; - /** - * Get the specified role assignment. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @param options The options parameters. - */ - get( - vaultBaseUrl: string, - scope: string, - roleAssignmentName: string, - options?: RoleAssignmentsGetOptionalParams - ): Promise; - /** - * Gets role assignments for a scope. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param options The options parameters. - */ - listForScope( - vaultBaseUrl: string, - scope: string, - options?: RoleAssignmentsListForScopeOptionalParams - ): Promise; - /** - * ListForScopeNext - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param nextLink The nextLink from the previous successful call to the ListForScope method. - * @param options The options parameters. - */ - listForScopeNext( - vaultBaseUrl: string, - scope: string, - nextLink: string, - options?: RoleAssignmentsListForScopeNextOptionalParams - ): Promise; -} diff --git a/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleDefinitions.ts b/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleDefinitions.ts deleted file mode 100644 index 7fa13eb8846d..000000000000 --- a/sdk/keyvault/keyvault-admin/src/generated/operationsInterfaces/roleDefinitions.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import { - RoleDefinitionsDeleteOptionalParams, - RoleDefinitionCreateParameters, - RoleDefinitionsCreateOrUpdateOptionalParams, - RoleDefinitionsCreateOrUpdateResponse, - RoleDefinitionsGetOptionalParams, - RoleDefinitionsGetResponse, - RoleDefinitionsListOptionalParams, - RoleDefinitionsListResponse, - RoleDefinitionsListNextOptionalParams, - RoleDefinitionsListNextResponse -} from "../models/index.js"; - -/** Interface representing a RoleDefinitions. */ -export interface RoleDefinitions { - /** - * Deletes a custom role definition. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @param options The options parameters. - */ - delete( - vaultBaseUrl: string, - scope: string, - roleDefinitionName: string, - options?: RoleDefinitionsDeleteOptionalParams - ): Promise; - /** - * Creates or updates a custom role definition. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid - * GUID. - * @param parameters Parameters for the role definition. - * @param options The options parameters. - */ - createOrUpdate( - vaultBaseUrl: string, - scope: string, - roleDefinitionName: string, - parameters: RoleDefinitionCreateParameters, - options?: RoleDefinitionsCreateOrUpdateOptionalParams - ): Promise; - /** - * Get the specified role definition. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @param options The options parameters. - */ - get( - vaultBaseUrl: string, - scope: string, - roleDefinitionName: string, - options?: RoleDefinitionsGetOptionalParams - ): Promise; - /** - * Get all role definitions that are applicable at scope and above. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param options The options parameters. - */ - list( - vaultBaseUrl: string, - scope: string, - options?: RoleDefinitionsListOptionalParams - ): Promise; - /** - * ListNext - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param nextLink The nextLink from the previous successful call to the List method. - * @param options The options parameters. - */ - listNext( - vaultBaseUrl: string, - scope: string, - nextLink: string, - options?: RoleDefinitionsListNextOptionalParams - ): Promise; -} diff --git a/sdk/keyvault/keyvault-admin/src/index.ts b/sdk/keyvault/keyvault-admin/src/index.ts deleted file mode 100644 index e2176e3bf891..000000000000 --- a/sdk/keyvault/keyvault-admin/src/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export * from "./accessControlClient.js"; -export * from "./accessControlModels.js"; - -export * from "./backupClient.js"; -export * from "./backupClientModels.js"; - -export * from "./settingsClient.js"; -export * from "./settingsClientModels.js"; - -export { LATEST_API_VERSION, SDK_VERSION, SUPPORTED_API_VERSIONS } from "./constants.js"; diff --git a/sdk/keyvault/keyvault-admin/src/log.ts b/sdk/keyvault/keyvault-admin/src/log.ts deleted file mode 100644 index 46c541bfd279..000000000000 --- a/sdk/keyvault/keyvault-admin/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-admin"); diff --git a/sdk/keyvault/keyvault-admin/src/lro/backup/operation.ts b/sdk/keyvault/keyvault-admin/src/lro/backup/operation.ts deleted file mode 100644 index 133268eb6e3d..000000000000 --- a/sdk/keyvault/keyvault-admin/src/lro/backup/operation.ts +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - FullBackupOperation, - FullBackupOptionalParams, - FullBackupResponse, - FullBackupStatusResponse, -} from "../../generated/models/index.js"; -import type { KeyVaultAdminPollOperationState } from "../keyVaultAdminPoller.js"; -import { KeyVaultAdminPollOperation } from "../keyVaultAdminPoller.js"; -import type { KeyVaultBackupResult, KeyVaultBeginBackupOptions } from "../../backupClientModels.js"; -import type { AbortSignalLike } from "@azure/abort-controller"; -import type { KeyVaultClient } from "../../generated/keyVaultClient.js"; -import { tracingClient } from "../../tracing.js"; - -/** - * An interface representing the publicly available properties of the state of a backup Key Vault's poll operation. - */ -export type KeyVaultBackupOperationState = KeyVaultAdminPollOperationState; - -/** - * An internal interface representing the state of a backup Key Vault's poll operation. - */ -export interface KeyVaultBackupPollOperationState - extends KeyVaultAdminPollOperationState { - /** - * The URI of the blob storage account. - */ - blobStorageUri: string; - /** - * The SAS token. - */ - sasToken?: string; -} - -/** - * The backup Key Vault's poll operation. - */ -export class KeyVaultBackupPollOperation extends KeyVaultAdminPollOperation< - KeyVaultBackupPollOperationState, - string -> { - constructor( - public state: KeyVaultBackupPollOperationState, - private vaultUrl: string, - private client: KeyVaultClient, - private requestOptions: KeyVaultBeginBackupOptions = {}, - ) { - super(state, { cancelMessage: "Cancelling a full Key Vault backup is not supported." }); - } - - /** - * Tracing the fullBackup operation - */ - private fullBackup(options: FullBackupOptionalParams): Promise { - return tracingClient.withSpan("KeyVaultBackupPoller.fullBackup", options, (updatedOptions) => - this.client.fullBackup(this.vaultUrl, updatedOptions), - ); - } - - /** - * Tracing the fullBackupStatus operation - */ - private fullBackupStatus( - jobId: string, - options: KeyVaultBeginBackupOptions, - ): Promise { - return tracingClient.withSpan( - "KeyVaultBackupPoller.fullBackupStatus", - options, - (updatedOptions) => this.client.fullBackupStatus(this.vaultUrl, jobId, updatedOptions), - ); - } - - /** - * Reaches to the service and updates the backup's poll operation. - */ - async update( - options: { - abortSignal?: AbortSignalLike; - fireProgress?: (state: KeyVaultBackupPollOperationState) => void; - } = {}, - ): Promise { - const state = this.state; - const { blobStorageUri, sasToken } = state; - - if (options.abortSignal) { - this.requestOptions.abortSignal = options.abortSignal; - } - - if (!state.isStarted) { - const serviceOperation = await this.fullBackup({ - ...this.requestOptions, - azureStorageBlobContainerUri: { - storageResourceUri: blobStorageUri!, - token: sasToken, - useManagedIdentity: sasToken === undefined, - }, - }); - - this.mapState(serviceOperation); - } else if (!state.isCompleted) { - if (!state.jobId) { - throw new Error(`Missing "jobId" from the full backup operation.`); - } - const serviceOperation = await this.fullBackupStatus(state.jobId, this.requestOptions); - this.mapState(serviceOperation); - } - - return this; - } - - private mapState(serviceOperation: FullBackupOperation): void { - const state = this.state; - const { - startTime, - jobId, - azureStorageBlobContainerUri, - endTime, - error, - status, - statusDetails, - } = serviceOperation; - if (!startTime) { - throw new Error( - `Missing "startTime" from the full backup operation. Full backup did not start successfully.`, - ); - } - - state.isStarted = true; - state.jobId = jobId; - state.endTime = endTime; - state.startTime = startTime; - state.status = status; - state.statusDetails = statusDetails; - state.isCompleted = !!endTime; - - if (state.isCompleted && error?.code) { - throw new Error(error?.message || statusDetails); - } - - if (state.isCompleted) { - state.result = { - folderUri: azureStorageBlobContainerUri, - startTime, - endTime, - }; - } - } -} diff --git a/sdk/keyvault/keyvault-admin/src/lro/backup/poller.ts b/sdk/keyvault/keyvault-admin/src/lro/backup/poller.ts deleted file mode 100644 index 5140c692f7fc..000000000000 --- a/sdk/keyvault/keyvault-admin/src/lro/backup/poller.ts +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { KeyVaultAdminPollerOptions } from "../keyVaultAdminPoller.js"; -import { KeyVaultAdminPoller } from "../keyVaultAdminPoller.js"; -import type { - KeyVaultBackupOperationState, - KeyVaultBackupPollOperationState, -} from "./operation.js"; -import { KeyVaultBackupPollOperation } from "./operation.js"; -import type { KeyVaultBackupResult } from "../../backupClientModels.js"; - -export interface KeyVaultBackupPollerOptions extends KeyVaultAdminPollerOptions { - blobStorageUri: string; - sasToken?: string; -} - -/** - * Class that creates a poller that waits until the backup of a Key Vault ends up being generated. - */ -export class KeyVaultBackupPoller extends KeyVaultAdminPoller< - KeyVaultBackupOperationState, - KeyVaultBackupResult -> { - constructor(options: KeyVaultBackupPollerOptions) { - const { - client, - vaultUrl, - blobStorageUri, - sasToken, - requestOptions, - intervalInMs = 2000, - resumeFrom, - } = options; - - let state: KeyVaultBackupPollOperationState | undefined; - - if (resumeFrom) { - state = JSON.parse(resumeFrom).state; - } - - const operation = new KeyVaultBackupPollOperation( - { - ...state, - blobStorageUri, - sasToken, - }, - vaultUrl, - client, - requestOptions, - ); - - super(operation); - - this.intervalInMs = intervalInMs; - } -} diff --git a/sdk/keyvault/keyvault-admin/src/lro/keyVaultAdminPoller.ts b/sdk/keyvault/keyvault-admin/src/lro/keyVaultAdminPoller.ts deleted file mode 100644 index 97f6da621dfd..000000000000 --- a/sdk/keyvault/keyvault-admin/src/lro/keyVaultAdminPoller.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { PollOperation, PollOperationState } from "@azure/core-lro"; -import { Poller } from "@azure/core-lro"; -import type { KeyVaultClient } from "../generated/keyVaultClient.js"; -import type { OperationOptions } from "@azure/core-client"; - -/** - * Common parameters to a Key Vault Admin Poller. - */ -export interface KeyVaultAdminPollerOptions { - vaultUrl: string; - client: KeyVaultClient; - requestOptions?: OperationOptions; - intervalInMs?: number; - resumeFrom?: string; -} - -/** - * An interface representing the state of a Key Vault Admin Poller's operation. - */ -export interface KeyVaultAdminPollOperationState extends PollOperationState { - /** - * Identifier for the full restore operation. - */ - jobId?: string; - /** - * Status of the restore operation. - */ - status?: string; - /** - * The status details of restore operation. - */ - statusDetails?: string; - /** - * The start time of the restore operation in UTC - */ - startTime?: Date; - /** - * The end time of the restore operation in UTC - */ - endTime?: Date; -} - -/** - * Generates a version of the state with only public properties. At least those common for all of the Key Vault Admin pollers. - */ -export function cleanState, TResult>( - state: TState, -): KeyVaultAdminPollOperationState { - return { - jobId: state.jobId, - status: state.status, - statusDetails: state.statusDetails, - startTime: state.startTime, - endTime: state.endTime, - isStarted: state.isStarted, - isCancelled: state.isCancelled, - isCompleted: state.isCompleted, - error: state.error, - result: state.result, - }; -} - -/** - * Common properties and methods of the Key Vault Admin Pollers. - */ -export abstract class KeyVaultAdminPoller< - TState extends KeyVaultAdminPollOperationState, - 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 new Promise((resolve) => setTimeout(resolve, this.intervalInMs)); - } - - /** - * Gets the public state of the polling operation - */ - public getOperationState(): TState { - return cleanState(this.operation.state) as TState; - } -} - -/** - * Optional parameters to the KeyVaultAdminPollOperation - */ -export interface KeyVaultAdminPollOperationOptions { - cancelMessage: string; -} - -/** - * Common properties and methods of the Key Vault Admin Poller operations. - */ -export class KeyVaultAdminPollOperation< - TState extends KeyVaultAdminPollOperationState, - TResult, -> implements PollOperation -{ - private cancelMessage: string; - - constructor( - public state: TState, - options: KeyVaultAdminPollOperationOptions, - ) { - 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: cleanState(this.state), - }); - } -} diff --git a/sdk/keyvault/keyvault-admin/src/lro/restore/operation.ts b/sdk/keyvault/keyvault-admin/src/lro/restore/operation.ts deleted file mode 100644 index dd60804d0558..000000000000 --- a/sdk/keyvault/keyvault-admin/src/lro/restore/operation.ts +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - FullRestoreOperationOptionalParams, - FullRestoreOperationResponse, - RestoreOperation, - RestoreStatusResponse, -} from "../../generated/models/index.js"; -import type { KeyVaultAdminPollOperationState } from "../keyVaultAdminPoller.js"; -import { KeyVaultAdminPollOperation } from "../keyVaultAdminPoller.js"; -import type { - KeyVaultBeginRestoreOptions, - KeyVaultRestoreResult, -} from "../../backupClientModels.js"; - -import type { AbortSignalLike } from "@azure/abort-controller"; -import type { KeyVaultClient } from "../../generated/keyVaultClient.js"; -import type { OperationOptions } from "@azure/core-client"; -import { tracingClient } from "../../tracing.js"; - -/** - * An interface representing the publicly available properties of the state of a restore Key Vault's poll operation. - */ -export interface KeyVaultRestoreOperationState - extends KeyVaultAdminPollOperationState {} - -/** - * An internal interface representing the state of a restore Key Vault's poll operation. - * @internal - */ -export interface KeyVaultRestorePollOperationState - extends KeyVaultAdminPollOperationState { - /** - * The URI of the blob storage account. - */ - folderUri: string; - /** - * The SAS token. - */ - sasToken?: string; - /** - * The Folder name of the blob where the previous successful full backup was stored - */ - folderName: string; -} - -/** - * An interface representing a restore Key Vault's poll operation. - */ -export class KeyVaultRestorePollOperation extends KeyVaultAdminPollOperation< - KeyVaultRestorePollOperationState, - KeyVaultRestoreResult -> { - constructor( - public state: KeyVaultRestorePollOperationState, - private vaultUrl: string, - private client: KeyVaultClient, - private requestOptions: KeyVaultBeginRestoreOptions = {}, - ) { - super(state, { - cancelMessage: "Cancelling the restoration full Key Vault backup is not supported.", - }); - } - - /** - * Tracing the fullRestore operation - */ - private fullRestore( - options: FullRestoreOperationOptionalParams, - ): Promise { - return tracingClient.withSpan("KeyVaultRestorePoller.fullRestore", options, (updatedOptions) => - this.client.fullRestoreOperation(this.vaultUrl, updatedOptions), - ); - } - - /** - * Tracing the restoreStatus operation. - */ - private async restoreStatus( - jobId: string, - options: OperationOptions, - ): Promise { - return tracingClient.withSpan( - "KeyVaultRestorePoller.restoreStatus", - options, - (updatedOptions) => this.client.restoreStatus(this.vaultUrl, jobId, updatedOptions), - ); - } - - /** - * Reaches to the service and updates the restore poll operation. - */ - async update( - options: { - abortSignal?: AbortSignalLike; - fireProgress?: (state: KeyVaultRestorePollOperationState) => void; - } = {}, - ): Promise { - const state = this.state; - const { folderUri, sasToken, folderName } = state; - - if (options.abortSignal) { - this.requestOptions.abortSignal = options.abortSignal; - } - - if (!state.isStarted) { - const serviceOperation = await this.fullRestore({ - ...this.requestOptions, - restoreBlobDetails: { - folderToRestore: folderName, - sasTokenParameters: { - storageResourceUri: folderUri, - token: sasToken, - useManagedIdentity: sasToken === undefined, - }, - }, - }); - - this.mapState(serviceOperation); - } else if (!state.isCompleted) { - if (!state.jobId) { - throw new Error(`Missing "jobId" from the full restore operation.`); - } - const serviceOperation = await this.restoreStatus(state.jobId, this.requestOptions); - this.mapState(serviceOperation); - } - - return this; - } - - private mapState(serviceOperation: RestoreOperation): void { - const state = this.state; - const { startTime, jobId, endTime, error, status, statusDetails } = serviceOperation; - - if (!startTime) { - throw new Error( - `Missing "startTime" from the full restore operation. Restore did not start successfully.`, - ); - } - - state.isStarted = true; - state.jobId = jobId; - state.endTime = endTime; - state.startTime = startTime; - state.status = status; - state.statusDetails = statusDetails; - - state.isCompleted = !!endTime; - - if (state.isCompleted && error?.code) { - throw new Error(error?.message || statusDetails); - } - - if (state.isCompleted) { - state.result = { - startTime, - endTime, - }; - } - } -} diff --git a/sdk/keyvault/keyvault-admin/src/lro/restore/poller.ts b/sdk/keyvault/keyvault-admin/src/lro/restore/poller.ts deleted file mode 100644 index bc1ecb861425..000000000000 --- a/sdk/keyvault/keyvault-admin/src/lro/restore/poller.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { KeyVaultAdminPollerOptions } from "../keyVaultAdminPoller.js"; -import { KeyVaultAdminPoller } from "../keyVaultAdminPoller.js"; -import type { - KeyVaultRestoreOperationState, - KeyVaultRestorePollOperationState, -} from "./operation.js"; -import { KeyVaultRestorePollOperation } from "./operation.js"; -import type { KeyVaultRestoreResult } from "../../backupClientModels.js"; - -export interface KeyVaultRestorePollerOptions extends KeyVaultAdminPollerOptions { - folderUri: string; - sasToken?: string; - folderName: string; -} - -/** - * Class that creates a poller that waits until a Key Vault ends up being restored. - */ -export class KeyVaultRestorePoller extends KeyVaultAdminPoller< - KeyVaultRestoreOperationState, - KeyVaultRestoreResult -> { - constructor(options: KeyVaultRestorePollerOptions) { - const { - client, - vaultUrl, - folderUri, - sasToken, - folderName, - requestOptions, - intervalInMs = 2000, - resumeFrom, - } = options; - - let state: KeyVaultRestorePollOperationState | undefined; - - if (resumeFrom) { - state = JSON.parse(resumeFrom).state; - } - - const operation = new KeyVaultRestorePollOperation( - { - ...state, - folderUri, - sasToken, - folderName, - }, - vaultUrl, - client, - requestOptions, - ); - - super(operation); - - this.intervalInMs = intervalInMs; - } -} diff --git a/sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/operation.ts b/sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/operation.ts deleted file mode 100644 index 58526fb5f3aa..000000000000 --- a/sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/operation.ts +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { KeyVaultAdminPollOperationState } from "../keyVaultAdminPoller.js"; -import { KeyVaultAdminPollOperation } from "../keyVaultAdminPoller.js"; -import type { - KeyVaultBeginSelectiveKeyRestoreOptions, - KeyVaultSelectiveKeyRestoreResult, -} from "../../backupClientModels.js"; -import type { - RestoreOperation, - RestoreStatusResponse, - SelectiveKeyRestoreOperationOptionalParams, - SelectiveKeyRestoreOperationResponse, -} from "../../generated/models/index.js"; -import type { AbortSignalLike } from "@azure/abort-controller"; -import type { KeyVaultClient } from "../../generated/keyVaultClient.js"; -import type { OperationOptions } from "@azure/core-client"; -import { tracingClient } from "../../tracing.js"; - -/** - * An interface representing the publicly available properties of the state of a restore Key Vault's poll operation. - */ -export interface KeyVaultSelectiveKeyRestoreOperationState - extends KeyVaultAdminPollOperationState {} - -/** - * An internal interface representing the state of a restore Key Vault's poll operation. - */ -export interface KeyVaultSelectiveKeyRestorePollOperationState - extends KeyVaultAdminPollOperationState { - /** - * The name of a Key Vault Key. - */ - keyName: string; - /** - * The Folder name of the blob where the previous successful full backup was stored - */ - folderName: string; - /** - * The URI of the blob storage account where the previous successful full backup was stored. - */ - folderUri: string; - /** - * The SAS token. - */ - sasToken?: string; -} - -/** - * The selective restore Key Vault's poll operation. - */ -export class KeyVaultSelectiveKeyRestorePollOperation extends KeyVaultAdminPollOperation< - KeyVaultSelectiveKeyRestorePollOperationState, - string -> { - constructor( - public state: KeyVaultSelectiveKeyRestorePollOperationState, - private vaultUrl: string, - private client: KeyVaultClient, - private requestOptions: KeyVaultBeginSelectiveKeyRestoreOptions = {}, - ) { - super(state, { cancelMessage: "Cancelling a selective Key Vault restore is not supported." }); - } - - /** - * Tracing the selectiveRestore operation - */ - private selectiveRestore( - keyName: string, - options: SelectiveKeyRestoreOperationOptionalParams, - ): Promise { - return tracingClient.withSpan( - "KeyVaultSelectiveKeyRestorePoller.selectiveRestore", - options, - (updatedOptions) => - this.client.selectiveKeyRestoreOperation(this.vaultUrl, keyName, updatedOptions), - ); - } - - /** - * Tracing the restoreStatus operation. - */ - private restoreStatus(jobId: string, options: OperationOptions): Promise { - return tracingClient.withSpan( - "KeyVaultSelectiveKeyRestorePoller.restoreStatus", - options, - (updatedOptions) => this.client.restoreStatus(this.vaultUrl, jobId, updatedOptions), - ); - } - - /** - * Reaches to the service and updates the selective restore poll operation. - */ - async update( - options: { - abortSignal?: AbortSignalLike; - fireProgress?: (state: KeyVaultSelectiveKeyRestorePollOperationState) => void; - } = {}, - ): Promise { - const state = this.state; - const { keyName, folderUri, sasToken, folderName } = state; - - if (options.abortSignal) { - this.requestOptions.abortSignal = options.abortSignal; - } - - if (!state.isStarted) { - const selectiveRestoreOperation = await this.selectiveRestore(keyName, { - ...this.requestOptions, - restoreBlobDetails: { - folder: folderName, - sasTokenParameters: { - storageResourceUri: folderUri, - token: sasToken, - useManagedIdentity: sasToken === undefined, - }, - }, - }); - this.mapState(selectiveRestoreOperation); - } else if (!state.isCompleted) { - if (!state.jobId) { - throw new Error(`Missing "jobId" from the full restore operation.`); - } - const serviceOperation = await this.restoreStatus(state.jobId, this.requestOptions); - this.mapState(serviceOperation); - } - - return this; - } - - private mapState(serviceOperation: RestoreOperation): void { - const state = this.state; - const { startTime, jobId, endTime, error, status, statusDetails } = serviceOperation; - - if (!startTime) { - throw new Error(`Missing "startTime" from the selective restore operation.`); - } - - state.isStarted = true; - state.jobId = jobId; - state.endTime = endTime; - state.startTime = startTime; - state.status = status; - state.statusDetails = statusDetails; - state.isCompleted = !!endTime; - - if (state.isCompleted && error?.code) { - throw new Error(error?.message || statusDetails); - } - - if (state.isCompleted) { - state.result = { - startTime, - endTime, - }; - } - } -} diff --git a/sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/poller.ts b/sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/poller.ts deleted file mode 100644 index 09a8e92aa06f..000000000000 --- a/sdk/keyvault/keyvault-admin/src/lro/selectiveKeyRestore/poller.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { KeyVaultAdminPollerOptions } from "../keyVaultAdminPoller.js"; -import { KeyVaultAdminPoller } from "../keyVaultAdminPoller.js"; -import type { - KeyVaultSelectiveKeyRestoreOperationState, - KeyVaultSelectiveKeyRestorePollOperationState, -} from "./operation.js"; -import { KeyVaultSelectiveKeyRestorePollOperation } from "./operation.js"; -import type { KeyVaultSelectiveKeyRestoreResult } from "../../backupClientModels.js"; - -export interface KeyVaultSelectiveKeyRestorePollerOptions extends KeyVaultAdminPollerOptions { - keyName: string; - folderUri: string; - sasToken?: string; - folderName: string; -} - -/** - * Class that creates a poller that waits until a key of a Key Vault backup ends up being restored. - */ -export class KeyVaultSelectiveKeyRestorePoller extends KeyVaultAdminPoller< - KeyVaultSelectiveKeyRestoreOperationState, - KeyVaultSelectiveKeyRestoreResult -> { - constructor(options: KeyVaultSelectiveKeyRestorePollerOptions) { - const { - client, - vaultUrl, - keyName, - folderUri, - sasToken, - folderName, - requestOptions, - intervalInMs = 2000, - resumeFrom, - } = options; - - let state: KeyVaultSelectiveKeyRestorePollOperationState | undefined; - - if (resumeFrom) { - state = JSON.parse(resumeFrom).state; - } - - const operation = new KeyVaultSelectiveKeyRestorePollOperation( - { - ...state, - keyName, - folderUri: folderUri, - sasToken, - folderName, - }, - vaultUrl, - client, - requestOptions, - ); - - super(operation); - - this.intervalInMs = intervalInMs; - } -} diff --git a/sdk/keyvault/keyvault-admin/src/mappings.ts b/sdk/keyvault/keyvault-admin/src/mappings.ts deleted file mode 100644 index 57ea87ac32ca..000000000000 --- a/sdk/keyvault/keyvault-admin/src/mappings.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - KeyVaultRoleAssignment, - KeyVaultRoleDefinition, - KeyVaultRoleScope, -} from "./accessControlModels.js"; -import type { RoleAssignment, RoleDefinition } from "./generated/models/index.js"; - -export const mappings = { - roleAssignment: { - generatedToPublic(roleAssignment: RoleAssignment): KeyVaultRoleAssignment { - const { id, name, type, properties } = roleAssignment; - const { scope, roleDefinitionId, principalId } = properties || {}; - return { - id: id!, - name: name!, - kind: type!, - properties: { - scope: scope as KeyVaultRoleScope, - roleDefinitionId: roleDefinitionId!, - principalId: principalId!, - }, - }; - }, - }, - roleDefinition: { - generatedToPublic(roleDefinition: RoleDefinition): KeyVaultRoleDefinition { - const { id, name, type, roleName, description, roleType, permissions, assignableScopes } = - roleDefinition; - return { - id: id!, - name: name!, - kind: type!, - roleName: roleName!, - description: description!, - roleType: roleType!, - permissions: permissions!, - assignableScopes: assignableScopes!, - }; - }, - }, - folderUriParts(folderUri: string): { folderName: string; folderUri: string } { - const uriParts = folderUri.split("/"); - const folderName = uriParts.pop(); - const storageUri = uriParts.join("/"); - - if (!folderName) { - throw new Error("The provided folder URI is missing the folder name."); - } - - return { - folderName, - folderUri: storageUri, - }; - }, -}; diff --git a/sdk/keyvault/keyvault-admin/src/settingsClient.ts b/sdk/keyvault/keyvault-admin/src/settingsClient.ts deleted file mode 100644 index 8244b0946b93..000000000000 --- a/sdk/keyvault/keyvault-admin/src/settingsClient.ts +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { TokenCredential } from "@azure/core-auth"; -import { keyVaultAuthenticationPolicy } from "@azure/keyvault-common"; -import { LATEST_API_VERSION } from "./constants.js"; -import type { Setting as GeneratedSetting } from "./generated/index.js"; -import { KeyVaultClient } from "./generated/index.js"; -import { logger } from "./log.js"; -import type { - UpdateSettingOptions, - GetSettingOptions, - ListSettingsOptions, - ListSettingsResponse, - KeyVaultSetting, - SettingsClientOptions, - BooleanKeyVaultSetting, -} from "./settingsClientModels.js"; - -function makeSetting(generatedSetting: GeneratedSetting): KeyVaultSetting { - if (generatedSetting.type === "boolean") { - return { - kind: "boolean", - name: generatedSetting.name, - value: generatedSetting.value === "true" ? true : false, - }; - } else { - return { - kind: generatedSetting.type, - name: generatedSetting.name, - value: generatedSetting.value, - }; - } -} - -/** - * Determines whether a given {@link KeyVaultSetting} is a {@link BooleanKeyVaultSetting}, i.e. has a boolean value. - */ -export function isBooleanSetting(setting: KeyVaultSetting): setting is BooleanKeyVaultSetting { - return setting.kind === "boolean" && typeof setting.value === "boolean"; -} - -/** - * The KeyVaultSettingsClient provides asynchronous methods to create, update, get and list - * settings for the Azure Key Vault. - */ -export class KeyVaultSettingsClient { - /** - * The base URL to the vault. - */ - public readonly vaultUrl: string; - - /** - * A reference to the auto-generated Key Vault HTTP client. - */ - private readonly client: KeyVaultClient; - - /** - * Creates an instance of the KeyVaultSettingsClient. - * - * Example usage: - * ```ts - * import { KeyVaultSettingsClient } from "@azure/keyvault-admin"; - * import { DefaultAzureCredential } from "@azure/identity"; - * - * let vaultUrl = `https://.vault.azure.net`; - * let credentials = new DefaultAzureCredential(); - * - * let client = new KeyVaultSettingsClient(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 options - options used to configure Key Vault API requests. - - */ - // eslint-disable-next-line @azure/azure-sdk/ts-naming-options - constructor(vaultUrl: string, credential: TokenCredential, options: SettingsClientOptions = {}) { - this.vaultUrl = vaultUrl; - - const apiVersion = options.serviceVersion || LATEST_API_VERSION; - - const clientOptions = { - ...options, - loggingOptions: { - logger: logger.info, - additionalAllowedHeaderNames: [ - "x-ms-keyvault-region", - "x-ms-keyvault-network-info", - "x-ms-keyvault-service-version", - ], - }, - }; - - this.client = new KeyVaultClient(apiVersion, clientOptions); - - // The authentication policy must come after the deserialization policy since the deserialization policy - // converts 401 responses to an Error, and we don't want to deal with that. - this.client.pipeline.addPolicy(keyVaultAuthenticationPolicy(credential, clientOptions), { - afterPolicies: ["deserializationPolicy"], - }); - } - - /** - * Updates the named account setting. - * - * @param setting - the setting to update. The name of the setting must be a valid settings option. - * @param options - the optional parameters. - */ - async updateSetting( - setting: KeyVaultSetting, - options: UpdateSettingOptions = {}, - ): Promise { - return makeSetting( - await this.client.updateSetting(this.vaultUrl, setting.name, String(setting.value), options), - ); - } - - /** - * Get the value of a specific account setting. - * - * @param settingName - the name of the setting. - * @param options - the optional parameters. - */ - async getSetting(settingName: string, options: GetSettingOptions = {}): Promise { - return makeSetting(await this.client.getSetting(this.vaultUrl, settingName, options)); - } - - /** - * List the account's settings. - * - * @param options - the optional parameters. - */ - // eslint-disable-next-line @azure/azure-sdk/ts-naming-options - async getSettings(options: ListSettingsOptions = {}): Promise { - const { settings } = await this.client.getSettings(this.vaultUrl, options); - return { settings: settings?.map(makeSetting) ?? [] }; - } -} diff --git a/sdk/keyvault/keyvault-admin/src/settingsClientModels.ts b/sdk/keyvault/keyvault-admin/src/settingsClientModels.ts deleted file mode 100644 index a11123eeec3c..000000000000 --- a/sdk/keyvault/keyvault-admin/src/settingsClientModels.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { CommonClientOptions, OperationOptions } from "@azure/core-client"; -import type { SUPPORTED_API_VERSIONS } from "./constants.js"; - -/** - * The optional parameters accepted by the KeyVaultSettingsClient. - */ -export interface SettingsClientOptions extends CommonClientOptions { - /** - * The accepted versions of the Key Vault's service API. - */ - serviceVersion?: SUPPORTED_API_VERSIONS; - - /** - * Whether to disable verification that the authentication challenge resource matches the Key Vault or Managed HSM domain. - * Defaults to false. - */ - disableChallengeResourceVerification?: boolean; -} - -/** - * An interface representing the optional parameters that can be passed to {@link KeyVaultSettingsClient.updateSetting} - */ -export interface UpdateSettingOptions extends OperationOptions {} - -/** - * An interface representing the optional parameters that can be passed to {@link KeyVaultSettingsClient.getSetting} - */ -export interface GetSettingOptions extends OperationOptions {} - -/** - * An interface representing the optional parameters that can be passed to {@link KeyVaultSettingsClient.listSettings} - */ -export interface ListSettingsOptions extends OperationOptions {} - -/** - * A Key Vault setting. - */ -export interface KeyVaultSetting { - /** - * The kind of the setting. - */ - kind?: string; - - /** - * The name of the setting. - */ - name: string; - - /** - * The value of a setting. The type of the value depends on the value of the kind property. - */ - value: unknown; -} - -/** - * A Key Vault setting of boolean type. To check if a given KeyVaultSetting is a boolean, use {@link isBooleanSetting}. - */ -export interface BooleanKeyVaultSetting extends KeyVaultSetting { - /** - * The kind of the setting. - */ - kind: "boolean"; - - /** - * The value of the setting as a boolean. - */ - value: boolean; -} - -/** - * An interface representing the response returned by {@link KeyVaultSettingsClient.listSettings} - */ -export interface ListSettingsResponse { - /** - * The account's settings. - */ - settings: KeyVaultSetting[]; -} diff --git a/sdk/keyvault/keyvault-admin/src/tracing.ts b/sdk/keyvault/keyvault-admin/src/tracing.ts deleted file mode 100644 index 6a2d35814dde..000000000000 --- a/sdk/keyvault/keyvault-admin/src/tracing.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { SDK_VERSION } from "./constants.js"; -import { createTracingClient } from "@azure/core-tracing"; - -export const tracingClient = createTracingClient({ - namespace: "Microsoft.KeyVault", - packageName: "@azure/keyvault-admin", - packageVersion: SDK_VERSION, -}); diff --git a/sdk/keyvault/keyvault-admin/swagger/README.md b/sdk/keyvault/keyvault-admin/swagger/README.md deleted file mode 100644 index 413d80c13173..000000000000 --- a/sdk/keyvault/keyvault-admin/swagger/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# KeyVault Admin Swagger Configuration - -> see https://aka.ms/autorest - -```yaml -package-name: "@azure/keyvault-admin" -azure-arm: false -disable-async-iterators: true -api-version-parameter: choice -generate-metadata: false -add-credentials: false -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/rbac.json - - https://raw.githubusercontent.com/Azure/azure-rest-api-specs/7452e1cc7db72fbc6cd9539b390d8b8e5c2a1864/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.5/backuprestore.json - - https://raw.githubusercontent.com/Azure/azure-rest-api-specs/7452e1cc7db72fbc6cd9539b390d8b8e5c2a1864/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.5/settings.json -output-folder: ../ -source-code-folder-path: ./src/generated -package-version: 4.6.1 -use-extension: - "@autorest/typescript": "6.0.0-beta.15" -``` - -### Hide LROs - -```yaml -directive: - - from: swagger-document - where: $["paths"] - transform: > - for (var path in $) { - for (var op of Object.values($[path])) { - if (op["x-ms-long-running-operation"]) { - delete op["x-ms-long-running-operation"]; - } - } - } -``` - -### Ignore 404s for DELETE operations - -Treat HTTP 404 responses for DELETE operations for RBAC as non-errors. - -```yaml -directive: - - where-operation: RoleAssignments_Delete - transform: > - $.responses["404"] = { - "description": "The resource to delete does not exist.", - "x-ms-error-response": false - }; - - where-operation: RoleDefinitions_Delete - transform: > - $.responses["404"] = { - "description": "The resource to delete does not exist.", - "x-ms-error-response": false - }; -``` - -### Return void for DELETE operations - -Do not parse response bodies unnecessarily. - -```yaml -directive: - - where-operation: RoleAssignments_Delete - transform: > - delete $.responses["200"].schema; - - where-operation: RoleDefinitions_Delete - transform: > - delete $.responses["200"].schema; -``` - -### Operation renames for Settings API - -```yaml -directive: - - rename-operation: - from: GetSettingValue - to: GetSetting -``` diff --git a/sdk/keyvault/keyvault-admin/test/README.md b/sdk/keyvault/keyvault-admin/test/README.md deleted file mode 100644 index 5a73d846a95e..000000000000 --- a/sdk/keyvault/keyvault-admin/test/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# Testing - -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. - -> Only Managed HSM instances support the KeyVault Administration client package, as such you'll need to ensure one is deployed to run these tests. 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. - -The Azure resource that is used by the tests in this project is: - -- An [Azure Managed HSM](https://docs.microsoft.com/azure/key-vault/managed-hsm/overview). 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). - -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. -- `AZURE_MANAGEDHSM_URI`: The URI of the Azure Managed HSM to use in the tests. -- `BLOB_STORAGE_URI`: URI of the Blob Storage instance, with the name of the container where the Key Vault backups will be generated. -- `BLOB_STORAGE_SAS_TOKEN`: URI of the Blob Storage instance, with the name of the container where the Key Vault backups will be generated. -- `CLIENT_OBJECT_ID`: Object ID of the application, tenant or principal to whom the role will be assigned to. These tests add and remove roles to and from this ID. **Do not use the same Object Id of the application, tenant or principal you're using to authenticate the client.** - -The live tests in this project will assign access roles to an Azure Key Vault, as well as generate backups and delete backups of an 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://docs.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://docs.microsoft.com/azure/key-vault/managed-hsm/access-control) - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fkeyvault%2Fkeyvault-admin%2Ftest%2FREADME.png) diff --git a/sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts b/sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts deleted file mode 100644 index 85a0745e6f90..000000000000 --- a/sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { KeyVaultAccessControlClient, KeyVaultBackupClient } from "../../src/index.js"; -import { LATEST_API_VERSION } from "../../src/constants.js"; -import { - PipelineRequest, - PipelineResponse, - createHttpHeaders, - HttpClient, - SendRequest, -} from "@azure/core-rest-pipeline"; -import { ClientSecretCredential } from "@azure/identity"; -import { env } from "@azure-tools/test-recorder"; -import { URL } from "url"; -import { describe, it, expect, beforeEach, afterEach, vi, MockInstance } from "vitest"; - -// Adding this to the source would change the public API. -type ApiVersions = "7.2" | "7.3"; - -const baseUrl = "https://managed_hsm.managedhsm.azure.net/"; - -describe("The keyvault-admin clients should set the serviceVersion", () => { - function makeHTTPMock(path: string, status = 200): HttpClient { - return { - async sendRequest(request: PipelineRequest): Promise { - return { - status, - headers: createHttpHeaders(), - request: request, - bodyAsText: JSON.stringify({ - id: `${baseUrl}${path}`, - startTime: new Date(), - attributes: {}, - }), - }; - }, - }; - } - - let mockHttpClient: HttpClient; - let spy: MockInstance; - let credential: ClientSecretCredential; - - beforeEach(async () => { - credential = new ClientSecretCredential( - env.AZURE_TENANT_ID || "tenant", - env.AZURE_CLIENT_ID || "client", - env.AZURE_CLIENT_SECRET || "secret", - ); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - describe("KeyVaultAccessControlClient", () => { - beforeEach(async () => { - mockHttpClient = makeHTTPMock("/providers/Microsoft.Authorization/roleDefinitions"); - spy = vi.spyOn(mockHttpClient, "sendRequest"); - }); - - it("it should default to the latest API version", async function () { - const client = new KeyVaultAccessControlClient(baseUrl, credential, { - httpClient: mockHttpClient, - }); - await client.listRoleDefinitions("/").next(); - - expect(spy).toHaveBeenCalled(); - const params = new URL(spy.mock.calls[0][0].url); - expect(params.searchParams.get("api-version")).toEqual(LATEST_API_VERSION); - }); - - it("it should allow us to specify an API version from a specific set of versions", async function () { - const serviceVersion = "7.2"; - const client = new KeyVaultAccessControlClient(baseUrl, credential, { - serviceVersion: serviceVersion as ApiVersions, - httpClient: mockHttpClient, - }); - await client.listRoleDefinitions("/").next(); - - expect(spy).toHaveBeenCalled(); - const params = new URL(spy.mock.calls[0][0].url); - expect(params.searchParams.get("api-version")).toEqual(serviceVersion); - }); - }); - - describe("KeyVaultBackupClient", () => { - beforeEach(async () => { - mockHttpClient = makeHTTPMock("/backup", 202); - spy = vi.spyOn(mockHttpClient, "sendRequest"); - }); - - it("it should default to the latest API version", async function () { - const client = new KeyVaultBackupClient(baseUrl, credential, { - httpClient: mockHttpClient, - }); - await client.beginBackup("secretName", "value"); - - expect(spy).toHaveBeenCalled(); - const params = new URL(spy.mock.calls[0][0].url); - expect(params.searchParams.get("api-version")).toEqual(LATEST_API_VERSION); - }); - - it("it should allow us to specify an API version from a specific set of versions", async function () { - const serviceVersion = "7.2"; - const client = new KeyVaultBackupClient(baseUrl, credential, { - serviceVersion: serviceVersion as ApiVersions, - httpClient: mockHttpClient, - }); - await client.beginBackup("secretName", "value"); - - expect(spy).toHaveBeenCalled(); - const params = new URL(spy.mock.calls[0][0].url); - expect(params.searchParams.get("api-version")).toEqual(serviceVersion); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts b/sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts deleted file mode 100644 index 40f5f8435663..000000000000 --- a/sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { KeyVaultAccessControlClient, SDK_VERSION } from "../../src/index.js"; -import { TokenCredential } from "@azure/core-auth"; -import { describe, it, expect } from "vitest"; - -describe("Key Vault Admin's user agent", function () { - it("SDK_VERSION and user-agent should match", async function () { - let userAgent: string | undefined; - const client = new KeyVaultAccessControlClient( - "https://myvault.vault.azure.net", - {} as TokenCredential, - { - httpClient: { - sendRequest: async (request) => { - userAgent = request.headers.get("user-agent"); - throw new Error("only a test"); - }, - }, - }, - ); - - try { - await client.getRoleAssignment("/", ""); - } catch { - // no-op, we don't care about the response, only the user-agent header - } - expect(userAgent).toBeDefined(); - expect(userAgent).toContain(`azsdk-js-keyvault-admin/${SDK_VERSION}`); - }); -}); diff --git a/sdk/keyvault/keyvault-admin/test/public/accessControlClient.aborts.spec.ts b/sdk/keyvault/keyvault-admin/test/public/accessControlClient.aborts.spec.ts deleted file mode 100644 index 3a47f31ddda9..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/accessControlClient.aborts.spec.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { assertEnvironmentVariable, Recorder } from "@azure-tools/test-recorder"; - -import { KeyVaultAccessControlClient } from "../../src/index.js"; -import { authenticate } from "./utils/authentication.js"; -import { describe, it, beforeEach, afterEach, expect } from "vitest"; -import { AbortError } from "@azure/abort-controller"; - -describe("Aborting KeyVaultAccessControlClient's requests", () => { - let client: KeyVaultAccessControlClient; - let recorder: Recorder; - let generateFakeUUID: () => string; - const globalScope = "/"; - - beforeEach(async function (ctx) { - const authentication = await authenticate(ctx); - client = authentication.accessControlClient; - recorder = authentication.recorder; - generateFakeUUID = authentication.generateFakeUUID; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - // The tests follow - - it("can abort listRoleDefinitions", async function () { - const controller = new AbortController(); - controller.abort(); - - await expect( - client.listRoleDefinitions("/", { abortSignal: controller.signal }).next(), - ).rejects.toThrow(AbortError); - }); - - it("can abort listRoleAssignments", async function () { - const controller = new AbortController(); - controller.abort(); - - await expect( - client - .listRoleAssignments("/", { - abortSignal: controller.signal, - }) - .next(), - ).rejects.toThrow(AbortError); - }); - - it("can abort createRoleAssignment", async function () { - const roleDefinitionId = generateFakeUUID(); - const name = generateFakeUUID(); - - const controller = new AbortController(); - controller.abort(); - - await expect( - client.createRoleAssignment( - globalScope, - name, - roleDefinitionId, - assertEnvironmentVariable("CLIENT_OBJECT_ID"), - { - abortSignal: controller.signal, - }, - ), - ).rejects.toThrow(AbortError); - }); - - it("can abort getRoleAssignment", async function () { - const name = generateFakeUUID(); - - const controller = new AbortController(); - controller.abort(); - - await expect( - client.getRoleAssignment(globalScope, name, { - abortSignal: controller.signal, - }), - ).rejects.toThrow(AbortError); - }); - - it("can abort deleteRoleAssignment", async function () { - const name = generateFakeUUID(); - - const controller = new AbortController(); - controller.abort(); - - await expect( - client.deleteRoleAssignment(globalScope, name, { - abortSignal: controller.signal, - }), - ).rejects.toThrow(AbortError); - }); -}); diff --git a/sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts b/sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts deleted file mode 100644 index 89ceafe06440..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { assertEnvironmentVariable, env, Recorder } from "@azure-tools/test-recorder"; -import { getYieldedValue, toSupportTracing } from "@azure-tools/test-utils-vitest"; - -import { - KeyVaultAccessControlClient, - KeyVaultPermission, - KeyVaultRoleDefinition, - KnownKeyVaultDataAction, -} from "../../src/index.js"; -import { authenticate } from "./utils/authentication.js"; -import { describe, it, beforeEach, afterEach, expect } from "vitest"; -import { KnownRoleScope } from "../../src/generated/index.js"; -expect.extend({ toSupportTracing }); - -describe("KeyVaultAccessControlClient", () => { - let client: KeyVaultAccessControlClient; - let recorder: Recorder; - let generateFakeUUID: () => string; - const globalScope = "/"; - - beforeEach(async function (ctx) { - const authentication = await authenticate(ctx); - client = authentication.accessControlClient; - recorder = authentication.recorder; - generateFakeUUID = authentication.generateFakeUUID; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - describe("role definitions", function () { - const permissions: KeyVaultPermission[] = [ - { - actions: [], - dataActions: [ - KnownKeyVaultDataAction.StartHsmBackup, - KnownKeyVaultDataAction.ReadHsmBackupStatus, - ], - notActions: [], - notDataActions: [], - }, - ]; - - it("can list role definitions", async function () { - const expectedType = "Microsoft.Authorization/roleDefinitions"; - const receivedRoles: string[] = []; - - for await (const roleDefinition of client.listRoleDefinitions(globalScope)) { - // Each role definition will have the shape of: - // - // { - // id: 'Microsoft.KeyVault/providers/Microsoft.Authorization/roleDefinitions/', - // name: '', - // type: '', - // roleName: '', - // // ... - // } - // - expect(roleDefinition.kind).toEqual(expectedType); - receivedRoles.push(roleDefinition.roleName!); - } - - // Roles might change - expect(receivedRoles.length).toBeGreaterThan(0); - }); - - describe("getRoleDefinition", function () { - it("returns a role definition by name", async function () { - const anyRoleDefinition = getYieldedValue( - await client.listRoleDefinitions(globalScope).next(), - ); - - const roleDefinition = await client.getRoleDefinition(globalScope, anyRoleDefinition.name); - - expect(roleDefinition).to.deep.equal(anyRoleDefinition); - }); - - it("errors when the role definition cannot be found", async function () { - await expect(client.getRoleDefinition(globalScope, "does_not_exist")).rejects.toThrow(); - }); - }); - - it("can create, update, and delete a role definition", async function () { - const name = generateFakeUUID(); - const roleName = "custom role definition name"; - const description = "custom role description"; - let roleDefinition: KeyVaultRoleDefinition = await client.setRoleDefinition(globalScope, { - roleDefinitionName: name, - roleName, - permissions, - description, - }); - - expect(roleDefinition.name).to.equal(name); - expect(roleDefinition.description).to.equal(description); - expect(roleDefinition.permissions).to.deep.equal(permissions); - expect(roleDefinition.assignableScopes[0]).to.equal(globalScope); - expect(roleDefinition.kind).to.equal("Microsoft.Authorization/roleDefinitions"); - expect(roleDefinition.roleType).to.equal("CustomRole"); - - const id = roleDefinition.id; - - permissions.push({ - actions: [], - notActions: [], - dataActions: [], - notDataActions: [KnownKeyVaultDataAction.EncryptHsmKey], - }); - - roleDefinition = await client.setRoleDefinition(globalScope, { - roleDefinitionName: name, - roleName, - permissions, - description, - }); - - expect(roleDefinition.id).to.equal(id); - expect(roleDefinition.permissions).to.deep.equal(permissions); - - await client.deleteRoleDefinition(globalScope, roleDefinition.name); - - for await (const definition of client.listRoleDefinitions(globalScope)) { - if (definition.id === roleDefinition.id) { - expect.fail( - "expected to successfully delete custom role definition, but it still exists.", - ); - } - } - }); - - describe("setRoleDefinition", function () { - it("errors when name is not a valid guid", async function () { - await expect( - client.setRoleDefinition(globalScope, { - roleDefinitionName: "foo unique value", - roleName: "foo role definition name", - permissions: [], - }), - ).rejects.toThrow(); - }); - - it("errors when updating a built-in role definition", async function () { - let builtInDefinition: KeyVaultRoleDefinition | undefined = undefined; - - for await (const definition of client.listRoleDefinitions(globalScope)) { - if (definition.roleType !== "CustomRole") { - builtInDefinition = definition; - } - } - - if (!builtInDefinition) { - expect.fail("Could not find a built in role definition to test against."); - } - - await expect( - client.setRoleDefinition(globalScope, { - roleDefinitionName: builtInDefinition.name, - roleName: builtInDefinition.roleName, - permissions, - }), - ).rejects.toThrow(); - }); - }); - - describe("deleteRoleDefinition", function () { - it("errors when deleting a built-in role definition", async function () { - let builtInDefinition: KeyVaultRoleDefinition | undefined = undefined; - - for await (const definition of client.listRoleDefinitions(globalScope)) { - if (definition.roleType !== "CustomRole") { - builtInDefinition = definition; - } - } - - if (!builtInDefinition) { - expect.fail("Could not find a built in role definition to test against."); - } - - await expect( - client.deleteRoleDefinition(globalScope, builtInDefinition.name), - ).rejects.toThrow(); - }); - - it("succeeds when deleting a non-existent role definition", async function () { - await expect(client.deleteRoleDefinition(globalScope, "foobar")).resolves.not.toThrow(); - }); - }); - }); - - describe("role assignments", async function () { - it("can list role assignments", async function () { - const expectedType = "Microsoft.Authorization/roleAssignments"; - const receivedRoles: string[] = []; - - for await (const roleAssignment of client.listRoleAssignments(globalScope)) { - // Each role assignment will have the shape of: - // - // { - // id: '/providers/Microsoft.Authorization/roleAssignments/', - // name: '', - // type: '', - // // ... - // } - // - expect(roleAssignment.kind).toEqual(expectedType); - receivedRoles.push(roleAssignment.name); - } - - // Roles might change - expect(receivedRoles.length).toBeGreaterThan(0); - }); - - it("can create, read, and delete role assignments", async function () { - const assignmentName = generateFakeUUID(); - const roleName = "Managed HSM Crypto Auditor"; - - let roleDefinition: KeyVaultRoleDefinition | undefined; - - // Find the right role definition to use - for await (const definition of client.listRoleDefinitions(globalScope)) { - if (definition.roleName === roleName) { - roleDefinition = definition; - } - } - - if (!roleDefinition) { - expect.fail(`Unable to find role definition with name ${roleName}`); - } - - const assignment = await client.createRoleAssignment( - globalScope, - assignmentName, - roleDefinition.id, - assertEnvironmentVariable("CLIENT_OBJECT_ID"), - ); - expect(assignment.name).toEqual(assignmentName); - expect(assignment.properties?.roleDefinitionId).toEqual(roleDefinition.id); - expect(assignment.properties?.principalId).toEqual(env.CLIENT_OBJECT_ID); - expect(assignment.properties.scope).toEqual(globalScope); - - await client.getRoleAssignment(globalScope, assignmentName); - expect(assignment.name).toEqual(assignmentName); - expect(assignment.properties?.roleDefinitionId).toEqual(roleDefinition.id); - expect(assignment.properties?.principalId).toEqual(env.CLIENT_OBJECT_ID); - expect(assignment.properties.scope).toEqual(globalScope); - - await client.deleteRoleAssignment(globalScope, assignmentName); - expect(assignment.name).toEqual(assignmentName); - expect(assignment.properties?.roleDefinitionId).toEqual(roleDefinition.id); - expect(assignment.properties?.principalId).toEqual(env.CLIENT_OBJECT_ID); - - try { - await client.getRoleAssignment(globalScope, generateFakeUUID()); - expect.fail("Expected an error to be thrown."); - } catch (e: any) { - expect(e.message).toMatch(/Requested role assignment not found/); - } - }); - - it("succeeds when deleting a role assignment that doesn't exist", async () => { - await expect( - client.deleteRoleAssignment(globalScope, generateFakeUUID()), - ).resolves.not.toThrow(); - }); - }); - - describe("tracing", () => { - it("traces through the various operations", async () => { - const roleDefinitionName = generateFakeUUID(); - const roleAssignmentName = generateFakeUUID(); - await expect(async (options: any) => { - const roleDefinition = await client.setRoleDefinition(KnownRoleScope.Global, { - roleDefinitionName, - roleName: roleDefinitionName, - ...options, - }); - await client.getRoleDefinition(KnownRoleScope.Global, roleDefinitionName, options); - await client.createRoleAssignment( - globalScope, - roleAssignmentName, - roleDefinition.id, - assertEnvironmentVariable("CLIENT_OBJECT_ID"), - options, - ); - await client.getRoleAssignment(KnownRoleScope.Global, roleAssignmentName, options); - await client.listRoleAssignments(KnownRoleScope.Global, options).next(); - await client.listRoleDefinitions(KnownRoleScope.Global, options).next(); - await client.deleteRoleAssignment(KnownRoleScope.Global, roleDefinitionName, options); - await client.deleteRoleDefinition(KnownRoleScope.Global, roleDefinitionName, options); - }).toSupportTracing([ - "KeyVaultAccessControlClient.setRoleDefinition", - "KeyVaultAccessControlClient.getRoleDefinition", - "KeyVaultAccessControlClient.createRoleAssignment", - "KeyVaultAccessControlClient.getRoleAssignment", - "KeyVaultAccessControlClient.listRoleAssignmentsPage", - "KeyVaultAccessControlClient.listRoleDefinitionsPage", - "KeyVaultAccessControlClient.deleteRoleAssignment", - "KeyVaultAccessControlClient.deleteRoleDefinition", - ]); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-admin/test/public/backupClient.abort.spec.ts b/sdk/keyvault/keyvault-admin/test/public/backupClient.abort.spec.ts deleted file mode 100644 index 3b1cb74a71e7..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/backupClient.abort.spec.ts +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { Recorder } from "@azure-tools/test-recorder"; - -import { KeyVaultBackupClient } from "../../src/index.js"; -import { authenticate } from "./utils/authentication.js"; -import { testPollerProperties } from "./utils/recorder.js"; -import { getSasToken } from "./utils/common.js"; -import { describe, it, beforeEach, afterEach, expect } from "vitest"; -import { AbortError } from "@azure/abort-controller"; - -// TODO: https://github.com/Azure/azure-sdk-for-js/issues/30273 -describe.skip("Aborting KeyVaultBackupClient's requests", () => { - let client: KeyVaultBackupClient; - let recorder: Recorder; - let blobStorageUri: string; - let blobSasToken: string; - - let generateFakeUUID: () => string; - - beforeEach(async function (ctx) { - const authentication = await authenticate(ctx); - client = authentication.backupClient; - recorder = authentication.recorder; - generateFakeUUID = authentication.generateFakeUUID; - - const sasTokenData = getSasToken(); - blobStorageUri = sasTokenData.blobStorageUri; - blobSasToken = sasTokenData.blobSasToken; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - it("can abort beginBackup", async function () { - const controller = new AbortController(); - controller.abort(); - - await expect( - client.beginBackup(blobStorageUri, blobSasToken, { - ...testPollerProperties, - abortSignal: controller.signal, - }), - ).rejects.toThrow(AbortError); - }); - - it("can abort beginRestore", async function () { - const backupURI = `${blobStorageUri}/${generateFakeUUID()}`; - const controller = new AbortController(); - controller.abort(); - - await expect( - client.beginRestore(backupURI, blobSasToken, { - ...testPollerProperties, - abortSignal: controller.signal, - }), - ).rejects.toThrow(AbortError); - }); - - it("can abort beginSelectiveKeyRestore", async function () { - const backupURI = `${blobStorageUri}/${generateFakeUUID()}`; - - const controller = new AbortController(); - controller.abort(); - - await expect( - client.beginSelectiveKeyRestore("key-name", backupURI, blobSasToken, { - ...testPollerProperties, - abortSignal: controller.signal, - }), - ).rejects.toThrow(AbortError); - }); -}); diff --git a/sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts b/sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts deleted file mode 100644 index 2dec59d72932..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { isPlaybackMode, Recorder } from "@azure-tools/test-recorder"; - -import { KeyVaultBackupClient } from "../../src/index.js"; -import { authenticate } from "./utils/authentication.js"; -import { testPollerProperties } from "./utils/recorder.js"; -import { getSasToken } from "./utils/common.js"; -import { delay } from "@azure/core-util"; -import { KeyClient } from "@azure/keyvault-keys"; -import { describe, it, expect, beforeEach, afterEach } from "vitest"; - -// TODO: https://github.com/Azure/azure-sdk-for-js/issues/30273 -describe.skip("KeyVaultBackupClient", () => { - let client: KeyVaultBackupClient; - let keyClient: KeyClient; - - let recorder: Recorder; - let blobStorageUri: string; - let blobSasToken: string; - - beforeEach(async function (ctx) { - const authentication = await authenticate(ctx); - client = authentication.backupClient; - keyClient = authentication.keyClient; - recorder = authentication.recorder; - const sasTokenData = getSasToken(); - blobStorageUri = sasTokenData.blobStorageUri; - blobSasToken = sasTokenData.blobSasToken; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - describe("beginBackup", function () { - it("returns the correct backup result when successful", async function () { - const backupPoller = await client.beginBackup( - blobStorageUri, - blobSasToken, - testPollerProperties, - ); - await backupPoller.poll(); - - // A poller can be serialized and then resumed - const resumedPoller = await client.beginBackup(blobStorageUri, blobSasToken, { - resumeFrom: backupPoller.toString(), - ...testPollerProperties, - }); - - expect(resumedPoller.getOperationState().isStarted).toEqual(true); // without polling - expect(resumedPoller.getOperationState().jobId).toEqual( - backupPoller.getOperationState().jobId, - ); - - const backupResult = await backupPoller.pollUntilDone(); - expect(backupPoller.getOperationState().error).toBeUndefined(); - expect(backupResult.folderUri).toBeDefined(); - expect(backupResult.startTime).toEqual(backupPoller.getOperationState().startTime); - expect(backupResult.endTime).toEqual(backupPoller.getOperationState().endTime); - expect(backupResult.folderUri!).toMatch(new RegExp(blobStorageUri)); - }); - - it("throws when polling errors", async function () { - await expect( - client.beginBackup(blobStorageUri, "invalid_sas_token", testPollerProperties), - ).rejects.toThrow(/SAS token/); - }); - }); - - describe("beginRestore", function () { - it("full restore completes successfully", async function () { - const backupPoller = await client.beginBackup( - blobStorageUri, - blobSasToken, - testPollerProperties, - ); - const backupResult = await backupPoller.pollUntilDone(); - expect(backupResult.folderUri).toBeDefined(); - - const restorePoller = await client.beginRestore( - backupResult.folderUri!, - blobSasToken, - testPollerProperties, - ); - await restorePoller.poll(); - - // A poller can be serialized and then resumed - const resumedPoller = await client.beginRestore(backupResult.folderUri!, blobSasToken, { - ...testPollerProperties, - resumeFrom: restorePoller.toString(), - }); - expect(resumedPoller.getOperationState().isStarted).toEqual(true); // without polling - expect(resumedPoller.getOperationState().jobId).toEqual( - restorePoller.getOperationState().jobId, - ); - - const restoreResult = await restorePoller.pollUntilDone(); - const operationState = restorePoller.getOperationState(); - expect(restoreResult.startTime).toEqual(operationState.startTime); - expect(restoreResult.endTime).toEqual(operationState.endTime); - expect(operationState.isCompleted).toEqual(true); - expect(operationState.error).toBeUndefined(); - // Restore is eventually consistent so while we work - // through the retry operations adding a delay here allows - // tests to pass the 5s polling delay. - if (!isPlaybackMode()) { - await delay(5000); - } - }); - - // This test can only be run in playback mode because running a backup - // or restore puts the instance in a bad state (tracked in IcM). - it.skipIf(!isPlaybackMode())("selectiveKeyRestore completes successfully", async function () { - const keyName = "rsa1"; - await keyClient.createRsaKey(keyName); - const backupPoller = await client.beginBackup( - blobStorageUri, - blobSasToken, - testPollerProperties, - ); - const backupURI = await backupPoller.pollUntilDone(); - expect(backupURI.folderUri).toBeDefined(); - - // Delete the key (purging it is required), then restore and ensure it's restored - await (await keyClient.beginDeleteKey(keyName, testPollerProperties)).pollUntilDone(); - await keyClient.purgeDeletedKey(keyName); - - const selectiveKeyRestorePoller = await client.beginSelectiveKeyRestore( - keyName, - backupURI.folderUri!, - blobSasToken, - testPollerProperties, - ); - await selectiveKeyRestorePoller.poll(); - - // A poller can be serialized and then resumed - const resumedPoller = await client.beginSelectiveKeyRestore( - keyName, - blobStorageUri, - blobSasToken, - { - ...testPollerProperties, - resumeFrom: selectiveKeyRestorePoller.toString(), - }, - ); - expect(resumedPoller.getOperationState().isStarted).toEqual(true); // without polling - expect(resumedPoller.getOperationState().jobId).toEqual( - selectiveKeyRestorePoller.getOperationState().jobId, - ); - - await selectiveKeyRestorePoller.pollUntilDone(); - const operationState = selectiveKeyRestorePoller.getOperationState(); - expect(operationState.isCompleted).toEqual(true); - - await keyClient.getKey(keyName); - }); - - it("throws when polling errors", async function () { - await expect( - client.beginRestore(blobStorageUri, "bad_token", testPollerProperties), - ).rejects.toThrow(/SAS token is malformed/); - }); - }); -}); diff --git a/sdk/keyvault/keyvault-admin/test/public/settingsClient.spec.ts b/sdk/keyvault/keyvault-admin/test/public/settingsClient.spec.ts deleted file mode 100644 index 2bbed4942c61..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/settingsClient.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { Recorder } from "@azure-tools/test-recorder"; -import { KeyVaultSettingsClient } from "../../src/settingsClient.js"; -import { authenticate } from "./utils/authentication.js"; -import { describe, it, beforeEach, afterEach, expect } from "vitest"; - -describe("KeyVaultSettingsClient", () => { - let client: KeyVaultSettingsClient; - let recorder: Recorder; - - beforeEach(async function (ctx) { - const authentication = await authenticate(ctx); - client = authentication.settingsClient; - recorder = authentication.recorder; - }); - - afterEach(async function () { - await recorder.stop(); - }); - - it("getSettings lists all settings", async () => { - const { settings } = await client.getSettings(); - - expect(settings).toBeDefined(); - expect(settings.length).toBeGreaterThan(0); - }); - - it("can get and update settings", async () => { - const setting = await client.getSetting("AllowKeyManagementOperationsThroughARM"); - setting.value = true; - const updated = await client.updateSetting(setting); - - expect(setting.kind).toEqual("boolean"); - expect(setting.value).toBeTypeOf("boolean"); - expect(updated.value).toBeTruthy(); - }); -}); diff --git a/sdk/keyvault/keyvault-admin/test/public/utils/authentication.ts b/sdk/keyvault/keyvault-admin/test/public/utils/authentication.ts deleted file mode 100644 index 4e96839399dd..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/utils/authentication.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { createTestCredential } from "@azure-tools/test-credential"; -import { env, Recorder, RecorderStartOptions, TestInfo } from "@azure-tools/test-recorder"; -import { KeyClient } from "@azure/keyvault-keys"; -import { - KeyVaultAccessControlClient, - KeyVaultBackupClient, - KeyVaultSettingsClient, -} from "../../../src/index.js"; - -import { getEnvironmentVariable } from "./common.js"; -import { randomUUID } from "@azure/core-util"; - -export async function authenticate(that: TestInfo): Promise { - const recorder = new Recorder(that); - let generatedUUIDs = 0; - - function generateFakeUUID(): string { - return recorder.variable(`uuid-${++generatedUUIDs}`, randomUUID()); - } - - const recorderStartOptions: RecorderStartOptions = { - envSetupForPlayback: { - AZURE_MANAGEDHSM_URI: "https://azure_managedhsm.managedhsm.azure.net/", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "12345678-1234-1234-1234-123456789012", - BLOB_CONTAINER_NAME: "uri", - BLOB_STORAGE_ACCOUNT_NAME: "blob_storage_account_name", - BLOB_STORAGE_SAS_TOKEN: "blob_storage_sas_token", - BLOB_STORAGE_URI: "https://uri.blob.core.windows.net/", - CLIENT_OBJECT_ID: "01ea9a65-813e-4238-8204-bf7328d63fc6", - }, - sanitizerOptions: { - generalSanitizers: [ - { - target: `keyvault_name\\.[a-z-]+\\.azure[a-z-]*\\.net`, - regex: true, - value: `keyvault_name.managedhsm.azure.net`, - }, - { - target: `[a-zA-Z0-9-]+\\.blob\\.core\\.windows\\.net`, - regex: true, - value: `uri.blob.core.windows.net`, - }, - ], - }, - removeCentralSanitizers: [ - // Setting "name" is not a secret - "AZSDK3493", - // Role definition ID is not a secret - "AZSDK3430", - // Principal ID is not a secret in this context - "AZSDK3444", - ], - }; - - await recorder.start(recorderStartOptions); - const suffix = recorder.variable("suffix", `suffix-${Math.floor(Math.random() * 1000000)}`); - - const credential = createTestCredential({ - authorityHost: env.AZURE_AUTHORITY_HOST, // undefined by default is expected - }); - - const keyVaultHsmUrl = getEnvironmentVariable("AZURE_MANAGEDHSM_URI"); - - const accessControlClient = new KeyVaultAccessControlClient( - keyVaultHsmUrl, - credential, - recorder.configureClientOptions({ - disableChallengeResourceVerification: true, - }), - ); - const keyClient = new KeyClient( - keyVaultHsmUrl, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: true }), - ); - const backupClient = new KeyVaultBackupClient( - keyVaultHsmUrl, - credential, - recorder.configureClientOptions({ disableChallengeResourceVerification: true }), - ); - const settingsClient = new KeyVaultSettingsClient( - keyVaultHsmUrl, - credential, - recorder.configureClientOptions({ - disableChallengeResourceVerification: true, - }), - ); - - return { - recorder, - accessControlClient, - backupClient, - keyClient, - settingsClient, - suffix, - generateFakeUUID, - }; -} diff --git a/sdk/keyvault/keyvault-admin/test/public/utils/common.ts b/sdk/keyvault/keyvault-admin/test/public/utils/common.ts deleted file mode 100644 index dba7c09f0edb..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/utils/common.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { env } from "@azure-tools/test-recorder"; - -export function formatName(name: string): string { - return name.replace(/[^0-9a-zA-Z-]/g, ""); -} - -// Receives: -// https://uri.blob.core.windows.net/backup/ -// Splits into: -// ["https:", "", "uri.blob.core.windows.net", "backup", ""] -// Returns: -// "" -export function getFolderName(uri: string): string { - return uri.split("/")[4]; -} - -/** - * Safely get an environment variable by name, throwing an error if it doesn't exist. - * @param envVarName - The name of the environment variable to return - */ -export function getEnvironmentVariable(envVarName: string): string { - const envVar = env[envVarName]; - if (!envVar) { - throw new Error(`Missing required environment variable ${envVarName}`); - } - return envVar; -} - -/** - * Get a predefined SAS token and Storage URI to use when backing up a KeyVault - */ -export function getSasToken(): { blobStorageUri: string; blobSasToken: string } { - const baseStorageUri = getEnvironmentVariable("BLOB_STORAGE_URI").replace(/\/$/, ""); - const blobStorageUri = `${baseStorageUri}/${getEnvironmentVariable("BLOB_CONTAINER_NAME")}`; - const blobSasToken = getEnvironmentVariable("BLOB_STORAGE_SAS_TOKEN"); - - return { blobStorageUri, blobSasToken }; -} diff --git a/sdk/keyvault/keyvault-admin/test/public/utils/recorder.ts b/sdk/keyvault/keyvault-admin/test/public/utils/recorder.ts deleted file mode 100644 index a2021b99c68e..000000000000 --- a/sdk/keyvault/keyvault-admin/test/public/utils/recorder.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { isPlaybackMode } from "@azure-tools/test-recorder"; - -/** - * 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-admin/tests.yml b/sdk/keyvault/keyvault-admin/tests.yml deleted file mode 100644 index 15406351cb3f..000000000000 --- a/sdk/keyvault/keyvault-admin/tests.yml +++ /dev/null @@ -1,23 +0,0 @@ -trigger: none - -extends: - template: /eng/pipelines/templates/stages/archetype-sdk-tests.yml - parameters: - PackageName: "@azure/keyvault-admin" - ServiceDirectory: keyvault - # KV HSM limitation prevents us from running live tests - # against multiple platforms in parallel (we're limited to five - # instances per region per subscription) so we're only running - # live tests against a single instance. - Location: eastus2 - MatrixConfigs: - - Name: Keyvault_live_test_base - Path: sdk/keyvault/keyvault-admin/platform-matrix.json - Selection: sparse - GenerateVMJobs: true - - ${{ if not(contains(variables['Build.DefinitionName'], 'tests-weekly')) }}: - # Due to the high cost of Managed HSMs, which keyvault-admin requires, we only want to run - # the live tests weekly. - MatrixFilters: - - ArmTemplateParameters=^(?!.*enableHsm.*true) diff --git a/sdk/keyvault/keyvault-admin/tsconfig.json b/sdk/keyvault/keyvault-admin/tsconfig.json deleted file mode 100644 index 5cd0af66f05e..000000000000 --- a/sdk/keyvault/keyvault-admin/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "../../../tsconfig", - "compilerOptions": { - "lib": ["dom"], - "resolveJsonModule": true, - "paths": { - "@azure/keyvault-admin": ["./src/index.js"] - }, - "module": "NodeNext", - "moduleResolution": "NodeNext", - "rootDir": "." - }, - "include": [ - "./src/**/*.ts", - "./src/**/*.mts", - "./src/**/*.cts", - "./samples-dev/**/*.ts", - "./test/**/*.ts" - ] -} diff --git a/sdk/keyvault/keyvault-admin/tsdoc.json b/sdk/keyvault/keyvault-admin/tsdoc.json deleted file mode 100644 index 81c5a8a2aa2f..000000000000 --- a/sdk/keyvault/keyvault-admin/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-admin/tsp-location.yaml b/sdk/keyvault/keyvault-admin/tsp-location.yaml new file mode 100644 index 000000000000..972f28ebd755 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/keyvault/Security.KeyVault.Administration +commit: 731ffebe0f58c613a0ecff464050866aabd28b1e +repo: ../azure-rest-api-specs +additionalDirectories: diff --git a/sdk/keyvault/keyvault-admin/vitest.config.ts b/sdk/keyvault/keyvault-admin/vitest.config.ts deleted file mode 100644 index 39267dd2f56f..000000000000 --- a/sdk/keyvault/keyvault-admin/vitest.config.ts +++ /dev/null @@ -1,15 +0,0 @@ - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { defineConfig, mergeConfig } from "vitest/config"; -import viteConfig from "../../../vitest.shared.config.ts"; - -export default mergeConfig( - viteConfig, - defineConfig({ - test: { - include: ["test/**/*.spec.ts"], - }, - }), -);