diff --git a/sdk/core/core-lro/review/core-lro.api.md b/sdk/core/core-lro/review/core-lro.api.md index 389deac09548..db6c7f537561 100644 --- a/sdk/core/core-lro/review/core-lro.api.md +++ b/sdk/core/core-lro/review/core-lro.api.md @@ -19,6 +19,7 @@ export interface CreateHttpPollerOptions { resolveOnUnsuccessful?: boolean; resourceLocationConfig?: ResourceLocationConfig; restoreFrom?: string; + skipFinalGet?: boolean; updateState?: (state: TState, response: OperationResponse) => void; withOperationLocation?: (operationLocation: string) => void; } diff --git a/sdk/core/core-lro/src/http/models.ts b/sdk/core/core-lro/src/http/models.ts index f8b32552ce6d..22d2610637a9 100644 --- a/sdk/core/core-lro/src/http/models.ts +++ b/sdk/core/core-lro/src/http/models.ts @@ -120,4 +120,8 @@ export interface CreateHttpPollerOptions { * Control whether to throw an exception if the operation failed or was canceled. */ resolveOnUnsuccessful?: boolean; + /** + * Skip final get request. + */ + skipFinalGet?: boolean; } diff --git a/sdk/core/core-lro/src/http/poller.ts b/sdk/core/core-lro/src/http/poller.ts index 60ffe04ed374..1f4abac1bc2d 100644 --- a/sdk/core/core-lro/src/http/poller.ts +++ b/sdk/core/core-lro/src/http/poller.ts @@ -15,6 +15,7 @@ import { } from "./operation.js"; import type { CreateHttpPollerOptions } from "./models.js"; import { buildCreatePoller } from "../poller/poller.js"; +import { logger } from "../logger.js"; /** * Creates a poller that can be used to poll a long-running operation. @@ -34,6 +35,7 @@ export function createHttpPoller updateState, withOperationLocation, resolveOnUnsuccessful = false, + skipFinalGet = false, } = options || {}; return buildCreatePoller({ getStatusFromInitialResponse, @@ -49,6 +51,10 @@ export function createHttpPoller init: async () => { const response = await lro.sendInitialRequest(); const config = inferLroMode(response.rawResponse, resourceLocationConfig); + if (skipFinalGet && config?.resourceLocation) { + logger.info("skipFinalGet is enabled, skipping final GET operation of LRO"); + config.resourceLocation = undefined; + } return { response, operationLocation: config?.operationLocation, diff --git a/sdk/keyvault/generate.ts b/sdk/keyvault/generate.ts new file mode 100644 index 000000000000..8e745b15c748 --- /dev/null +++ b/sdk/keyvault/generate.ts @@ -0,0 +1,86 @@ +#!/usr/bin/env node + +const { execSync } = require("child_process"); +const fs = require("fs"); +const path = require("path"); + +// Helper to execute shell commands and log output +function execCommand(command) { + try { + execSync(command, { stdio: "inherit" }); + } catch (error) { + console.error(`Command failed: ${command}`); + process.exit(1); + } +} + +console.log("Setting up the environment..."); + +// Workaround for src-folder support in emitter: +// End state: src/generated/* contains generated code (instead of src/generated/src/*) + +// Step 1: Remove all files in src/generated/* +execCommand("rm -rf src/generated/*"); + +// Step 2: Copy tsp-location.yaml to src/generated +execCommand("cp tsp-location.yaml src/generated"); + +// Step 3: Run tsp-client command +// emitter-option as a workaround for https://github.com/Azure/azure-rest-api-specs/issues/31610 +execCommand(`tsp-client update -d -o src/generated --emitter-options generateMetadata=false`); +// execCommand( +// "tsp-client update -d -o src/generated --tsp-config ~/workspace/azure-rest-api-specs/specification/keyvault/Security.KeyVault.Keys/tspconfig.yaml --local-spec-repo ~/workspace/azure-rest-api-specs/specification/keyvault/Security.KeyVault.Keys --repo ~/workspace/azure-rest-api-specs --commit 9561bad7d2eed94cc91aa6164d3721b8aa8699fe --emitter-options generateMetadata=false" +// ); + +// Step 4: Move generated/src/* files to generated until src-folder is supported +execCommand("mv src/generated/src/* src/generated/"); + +// Step 5: Remove generated/src +execCommand("rm -rf src/generated/src"); + +// Step 6: Remove tsp-location.yaml from generated folder +execCommand("rm src/generated/tsp-location.yaml"); + +// Step 7: Read and update package.json +console.log("Updating package.json dependencies..."); +const packageJsonPath = path.resolve("./package.json"); +const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); + +// Remove dependency on @azure/core-client and add @azure-rest/core-client +delete packageJson.dependencies["@azure/core-client"]; +packageJson.dependencies["@azure-rest/core-client"] = "^2.0.0"; + +// Write updated package.json back to disk +fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), "utf8"); + +// Generated code changes +// Workaround for https://github.com/Azure/autorest.typescript/pull/2135/files +const modelsPath = path.resolve("./src/generated/models/models.ts"); +let modelsContent = fs.readFileSync(modelsPath, "utf8"); +modelsContent = modelsContent + .replace( + /created: !item\["created"\] \? item\["created"\] : new Date\(item\["created"\]\),/g, + 'created: !item["created"] ? item["created"] : new Date(item["created"] * 1000),' + ) + .replace( + /updated: !item\["updated"\] \? item\["updated"\] : new Date\(item\["updated"\]\),/g, + 'updated: !item["updated"] ? item["updated"] : new Date(item["updated"] * 1000),' + ) + .replace( + /notBefore: !item\["nbf"\] \? item\["nbf"\] : new Date\(item\["nbf"\]\),/g, + 'notBefore: !item["nbf"] ? item["nbf"] : new Date(item["nbf"] * 1000),' + ) + .replace( + /expires: !item\["exp"\] \? item\["exp"\] : new Date\(item\["exp"\]\),/g, + 'expires: !item["exp"] ? item["exp"] : new Date(item["exp"] * 1000),' + ) + .replace( + /nbf: !item\["notBefore"\] \? item\["notBefore"\] : item\["notBefore"\].getTime\(\),/g, + 'nbf: !item["notBefore"] ? item["notBefore"] : item["notBefore"].getTime() / 1000,' + ) + .replace( + /exp: !item\["expires"\] \? item\["expires"\] : item\["expires"\].getTime\(\),/g, + 'exp: !item["expires"] ? item["expires"] : item["expires"].getTime() / 1000,' + ); + +fs.writeFileSync(modelsPath, modelsContent, "utf8"); diff --git a/sdk/keyvault/keyvault-admin/assets.json b/sdk/keyvault/keyvault-admin/assets.json index cc97db2d357b..42bbdee55625 100644 --- a/sdk/keyvault/keyvault-admin/assets.json +++ b/sdk/keyvault/keyvault-admin/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "js", "TagPrefix": "js/keyvault/keyvault-admin", - "Tag": "js/keyvault/keyvault-admin_1ce65643a5" + "Tag": "js/keyvault/keyvault-admin_46c9877128" } diff --git a/sdk/keyvault/keyvault-admin/package.json b/sdk/keyvault/keyvault-admin/package.json index 6bc0fff9d36e..eb377a5d59ae 100644 --- a/sdk/keyvault/keyvault-admin/package.json +++ b/sdk/keyvault/keyvault-admin/package.json @@ -90,10 +90,10 @@ }, "sideEffects": false, "dependencies": { + "@azure-rest/core-client": "^2.0.0", "@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-lro": "^3.1.0", "@azure/core-paging": "^1.1.1", "@azure/core-rest-pipeline": "^1.1.0", "@azure/core-tracing": "^1.0.0", diff --git a/sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md b/sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md index 7c94bc9858b2..802313c670ab 100644 --- a/sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md +++ b/sdk/keyvault/keyvault-admin/review/keyvault-admin.api.md @@ -4,15 +4,15 @@ ```ts -import type { CommonClientOptions } from '@azure/core-client'; -import type { OperationOptions } from '@azure/core-client'; +import type { AbortSignalLike } from '@azure/abort-controller'; +import type { CancelOnProgress } from '@azure/core-lro'; +import type { ClientOptions } from '@azure-rest/core-client'; +import type { OperationOptions } from '@azure-rest/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 { +export interface AccessControlClientOptions extends ClientOptions { disableChallengeResourceVerification?: boolean; serviceVersion?: SUPPORTED_API_VERSIONS; } @@ -65,17 +65,23 @@ export class KeyVaultAccessControlClient { } // @public -export interface KeyVaultAdminPollOperationState extends PollOperationState { +export interface KeyVaultAdminPollOperationState { endTime?: Date; + error?: Error; + isCompleted?: boolean; + isStarted?: boolean; jobId?: string; + result?: TResult; startTime?: Date; - status?: string; + // Warning: (ae-forgotten-export) The symbol "OperationStatus" needs to be exported by the entry point index.d.ts + status: OperationStatus; statusDetails?: string; } // @public export class KeyVaultBackupClient { constructor(vaultUrl: string, credential: TokenCredential, options?: KeyVaultBackupClientOptions); + // Warning: (ae-forgotten-export) The symbol "PollerLike" needs to be exported by the entry point index.d.ts beginBackup(blobStorageUri: string, sasToken: string, options?: KeyVaultBeginBackupOptions): Promise>; beginBackup(blobStorageUri: string, options?: KeyVaultBeginBackupOptions): Promise>; beginRestore(folderUri: string, sasToken: string, options?: KeyVaultBeginRestoreOptions): Promise>; @@ -86,7 +92,7 @@ export class KeyVaultBackupClient { } // @public -export interface KeyVaultBackupClientOptions extends CommonClientOptions { +export interface KeyVaultBackupClientOptions extends ClientOptions { disableChallengeResourceVerification?: boolean; serviceVersion?: SUPPORTED_API_VERSIONS; } @@ -104,7 +110,7 @@ export interface KeyVaultBackupPollerOptions extends OperationOptions { export interface KeyVaultBackupResult { endTime?: Date; folderUri?: string; - startTime: Date; + startTime?: Date; } // @public @@ -137,7 +143,7 @@ export interface KeyVaultRestoreOperationState extends KeyVaultAdminPollOperatio // @public export interface KeyVaultRestoreResult { endTime?: Date; - startTime: Date; + startTime?: Date; } // @public @@ -177,7 +183,7 @@ export interface KeyVaultSelectiveKeyRestoreOperationState extends KeyVaultAdmin // @public export interface KeyVaultSelectiveKeyRestoreResult { endTime?: Date; - startTime: Date; + startTime?: Date; } // @public @@ -283,7 +289,7 @@ export interface SetRoleDefinitionOptions extends OperationOptions { } // @public -export interface SettingsClientOptions extends CommonClientOptions { +export interface SettingsClientOptions extends ClientOptions { disableChallengeResourceVerification?: boolean; serviceVersion?: SUPPORTED_API_VERSIONS; } diff --git a/sdk/keyvault/keyvault-admin/src/accessControlClient.ts b/sdk/keyvault/keyvault-admin/src/accessControlClient.ts index a7d052f757a0..3835dc6be81f 100644 --- a/sdk/keyvault/keyvault-admin/src/accessControlClient.ts +++ b/sdk/keyvault/keyvault-admin/src/accessControlClient.ts @@ -13,21 +13,16 @@ import type { 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 { KeyVaultClient } from "./generated/keyVaultClient.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 { mapPagedAsyncIterable, mappings } from "./mappings.js"; import { tracingClient } from "./tracing.js"; import { randomUUID } from "@azure/core-util"; +import { createKeyVaultClient } from "./createKeyVaultClient.js"; /** * The KeyVaultAccessControlClient provides methods to manage @@ -69,27 +64,7 @@ export class KeyVaultAccessControlClient { ) { 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"], - }); + this.client = createKeyVaultClient(vaultUrl, credential, options); } /** @@ -121,7 +96,6 @@ export class KeyVaultAccessControlClient { options, async (updatedOptions) => { const response = await this.client.roleAssignments.create( - this.vaultUrl, roleScope, name, { @@ -160,7 +134,14 @@ export class KeyVaultAccessControlClient { "KeyVaultAccessControlClient.deleteRoleAssignment", options, async (updatedOptions) => { - await this.client.roleAssignments.delete(this.vaultUrl, roleScope, name, updatedOptions); + try { + await this.client.roleAssignments.delete(roleScope, name, updatedOptions); + } catch (err: any) { + // If the role assignment doesn't exist, we can consider it deleted. + if (err.statusCode !== 404) { + throw err; + } + } }, ); } @@ -189,78 +170,12 @@ export class KeyVaultAccessControlClient { "KeyVaultAccessControlClient.getRoleAssignment", options, async (updatedOptions) => { - const response = await this.client.roleAssignments.get( - this.vaultUrl, - roleScope, - name, - updatedOptions, - ); + const response = await this.client.roleAssignments.get(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. * @@ -279,77 +194,10 @@ export class KeyVaultAccessControlClient { 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; - } + return mapPagedAsyncIterable( + this.client.roleAssignments.listForScope(roleScope, options), + mappings.roleAssignment.generatedToPublic, + ); } /** @@ -370,18 +218,10 @@ export class KeyVaultAccessControlClient { 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), - }; + return mapPagedAsyncIterable( + this.client.roleDefinitions.list(roleScope, options), + mappings.roleDefinition.generatedToPublic, + ); } /** @@ -406,12 +246,7 @@ export class KeyVaultAccessControlClient { "KeyVaultAccessControlClient.getRoleDefinition", options, async (updatedOptions) => { - const response = await this.client.roleDefinitions.get( - this.vaultUrl, - roleScope, - name, - updatedOptions, - ); + const response = await this.client.roleDefinitions.get(roleScope, name, updatedOptions); return mappings.roleDefinition.generatedToPublic(response); }, ); @@ -440,7 +275,6 @@ export class KeyVaultAccessControlClient { options, async (updatedOptions) => { const response = await this.client.roleDefinitions.createOrUpdate( - this.vaultUrl, roleScope, options.roleDefinitionName || randomUUID(), { @@ -481,7 +315,14 @@ export class KeyVaultAccessControlClient { "KeyVaultAccessControlClient.deleteRoleDefinition", options, async (updatedOptions) => { - await this.client.roleDefinitions.delete(this.vaultUrl, roleScope, name, updatedOptions); + try { + await this.client.roleDefinitions.delete(roleScope, name, updatedOptions); + } catch (err: any) { + // If the role definition doesn't exist, we can consider it deleted. + if (err.statusCode !== 404) { + throw err; + } + } }, ); } diff --git a/sdk/keyvault/keyvault-admin/src/accessControlModels.ts b/sdk/keyvault/keyvault-admin/src/accessControlModels.ts index 777ee31bccba..921af6ca6d2d 100644 --- a/sdk/keyvault/keyvault-admin/src/accessControlModels.ts +++ b/sdk/keyvault/keyvault-admin/src/accessControlModels.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { CommonClientOptions, OperationOptions } from "@azure/core-client"; +import type { ClientOptions, OperationOptions } from "@azure-rest/core-client"; import { DataAction as KeyVaultDataAction, RoleScope as KeyVaultRoleScope, @@ -15,7 +15,7 @@ export { KeyVaultDataAction, KeyVaultRoleScope, KnownKeyVaultDataAction, KnownKe /** * The optional parameters accepted by the Key Vault's AccessControlClient */ -export interface AccessControlClientOptions extends CommonClientOptions { +export interface AccessControlClientOptions extends ClientOptions { /** * The accepted versions of the Key Vault's service API. */ diff --git a/sdk/keyvault/keyvault-admin/src/backupClient.ts b/sdk/keyvault/keyvault-admin/src/backupClient.ts index 3df315bac0a0..9b7fad9cd2a5 100644 --- a/sdk/keyvault/keyvault-admin/src/backupClient.ts +++ b/sdk/keyvault/keyvault-admin/src/backupClient.ts @@ -10,20 +10,19 @@ import type { 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 { KeyVaultClient } from "./generated/keyVaultClient.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 { createKeyVaultClient } from "./createKeyVaultClient.js"; +import type { PollerLike } from "./lro/shim.js"; +import { wrapPoller } from "./lro/shim.js"; +import { + KeyVaultAdminPollOperationState, + KeyVaultBackupOperationState, + KeyVaultRestoreOperationState, + KeyVaultSelectiveKeyRestoreOperationState, +} from "./lro/models.js"; +import { restorePoller } from "./generated/restorePollerHelpers.js"; export { KeyVaultBackupOperationState, @@ -73,26 +72,7 @@ export class KeyVaultBackupClient { ) { 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"], - }); + this.client = createKeyVaultClient(vaultUrl, credential, options); } /** @@ -177,20 +157,27 @@ export class KeyVaultBackupClient { 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(); + if (options.resumeFrom) { + return wrapPoller( + restorePoller(this.client, options.resumeFrom, this.client.fullBackup, options), + ); + } - return poller; + return wrapPoller( + this.client.fullBackup({ + abortSignal: options.abortSignal, + requestOptions: options.requestOptions, + azureStorageBlobContainerUri: { + storageResourceUri: blobStorageUri, + token: sasToken, + useManagedIdentity: sasToken === undefined, + }, + onResponse: options.onResponse, + tracingOptions: options.tracingOptions, + updateIntervalInMs: options.intervalInMs, + skipFinalGet: true, + }), + ); } /** @@ -277,20 +264,32 @@ export class KeyVaultBackupClient { 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, - }); + const folderUriParts = mappings.folderUriParts(folderUri); - // This will initialize the poller's operation (the generation of the backup). - await poller.poll(); + if (options.resumeFrom) { + return wrapPoller( + restorePoller(this.client, options.resumeFrom, this.client.fullRestoreOperation, options), + ); + } - return poller; + return wrapPoller( + this.client.fullRestoreOperation({ + abortSignal: options.abortSignal, + requestOptions: options.requestOptions, + restoreBlobDetails: { + folderToRestore: folderUriParts.folderName, + sasTokenParameters: { + storageResourceUri: folderUriParts.folderUri, + token: sasToken, + useManagedIdentity: sasToken === undefined, + }, + }, + onResponse: options.onResponse, + tracingOptions: options.tracingOptions, + updateIntervalInMs: options.intervalInMs, + skipFinalGet: true, + }), + ); } /** @@ -388,20 +387,36 @@ export class KeyVaultBackupClient { 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, - }); + const folderUriParts = mappings.folderUriParts(folderUri); - // This will initialize the poller's operation (the generation of the backup). - await poller.poll(); + if (options.resumeFrom) { + return wrapPoller( + restorePoller( + this.client, + options.resumeFrom, + this.client.selectiveKeyRestoreOperation, + options, + ), + ); + } - return poller; + return wrapPoller( + this.client.selectiveKeyRestoreOperation(keyName, { + abortSignal: options.abortSignal, + requestOptions: options.requestOptions, + onResponse: options.onResponse, + restoreBlobDetails: { + folder: folderUriParts.folderName, + sasTokenParameters: { + storageResourceUri: folderUriParts.folderUri, + token: sasToken, + useManagedIdentity: sasToken === undefined, + }, + }, + tracingOptions: options.tracingOptions, + updateIntervalInMs: options.intervalInMs, + skipFinalGet: true, + }), + ); } } diff --git a/sdk/keyvault/keyvault-admin/src/backupClientModels.ts b/sdk/keyvault/keyvault-admin/src/backupClientModels.ts index fd75b39042cf..41ea5f41931e 100644 --- a/sdk/keyvault/keyvault-admin/src/backupClientModels.ts +++ b/sdk/keyvault/keyvault-admin/src/backupClientModels.ts @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { CommonClientOptions, OperationOptions } from "@azure/core-client"; +import type { ClientOptions, OperationOptions } from "@azure-rest/core-client"; import type { SUPPORTED_API_VERSIONS } from "./constants.js"; /** * The optional parameters accepted by the KeyVaultBackupClient */ -export interface KeyVaultBackupClientOptions extends CommonClientOptions { +export interface KeyVaultBackupClientOptions extends ClientOptions { /** * The accepted versions of the Key Vault's service API. */ @@ -65,7 +65,7 @@ export interface KeyVaultBackupResult { /** * The start time of the backup operation. */ - startTime: Date; + startTime?: Date; /** * The end time of the backup operation. @@ -80,7 +80,7 @@ export interface KeyVaultRestoreResult { /** * The start time of the restore operation. */ - startTime: Date; + startTime?: Date; /** * The end time of the restore operation. @@ -95,7 +95,7 @@ export interface KeyVaultSelectiveKeyRestoreResult { /** * The start time of the selective key restore operation. */ - startTime: Date; + startTime?: Date; /** * The end time of the selective key restore operation. diff --git a/sdk/keyvault/keyvault-admin/src/createKeyVaultClient.ts b/sdk/keyvault/keyvault-admin/src/createKeyVaultClient.ts new file mode 100644 index 000000000000..e3d9944b6e91 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/createKeyVaultClient.ts @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { TokenCredential } from "@azure/core-auth"; +import type { KeyVaultClientOptionalParams } from "./generated/keyVaultClient.js"; +import { KeyVaultClient } from "./generated/keyVaultClient.js"; +import { bearerTokenAuthenticationPolicyName } from "@azure/core-rest-pipeline"; +import { keyVaultAuthenticationPolicy } from "@azure/keyvault-common"; +import type { AccessControlClientOptions } from "./accessControlModels.js"; +import type { KeyVaultBackupClientOptions } from "./backupClientModels.js"; +import type { SettingsClientOptions } from "./settingsClientModels.js"; +import { LATEST_API_VERSION, SDK_VERSION } from "./constants.js"; +import { logger } from "./log.js"; + +export function createKeyVaultClient( + vaultUrl: string, + credential: TokenCredential, + options: AccessControlClientOptions | KeyVaultBackupClientOptions | SettingsClientOptions, +): KeyVaultClient { + const clientOptions: KeyVaultClientOptionalParams = { + ...options, + apiVersion: options.serviceVersion || LATEST_API_VERSION, + loggingOptions: { + logger: logger.info, + additionalAllowedHeaderNames: [ + "x-ms-keyvault-region", + "x-ms-keyvault-network-info", + "x-ms-keyvault-service-version", + ], + }, + }; + clientOptions.userAgentOptions ??= {}; + clientOptions.userAgentOptions.userAgentPrefix = `${clientOptions.userAgentOptions.userAgentPrefix ?? ""} azsdk-js-keyvault-admin/${SDK_VERSION}`; + + const client = new KeyVaultClient(vaultUrl, credential, clientOptions); + + client.pipeline.removePolicy({ name: bearerTokenAuthenticationPolicyName }); + client.pipeline.addPolicy(keyVaultAuthenticationPolicy(credential, options)); + // Workaround for: https://github.com/Azure/azure-sdk-for-js/issues/31843 + client.pipeline.addPolicy({ + name: "ContentTypePolicy", + sendRequest(request, next) { + const contentType = request.headers.get("Content-Type") ?? ""; + if (contentType.startsWith("application/json")) { + request.headers.set("Content-Type", "application/json"); + } + return next(request); + }, + }); + return client; +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/api/index.ts b/sdk/keyvault/keyvault-admin/src/generated/api/index.ts new file mode 100644 index 000000000000..98c6057da558 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/api/index.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { + createKeyVault, + KeyVaultContext, + KeyVaultClientOptionalParams, +} from "./keyVaultContext.js"; +export { + fullBackupStatus, + fullBackup, + preFullBackup, + restoreStatus, + preFullRestoreOperation, + fullRestoreOperation, + selectiveKeyRestoreOperation, + updateSetting, + getSetting, + getSettings, +} from "./operations.js"; +export { + FullBackupStatusOptionalParams, + FullBackupOptionalParams, + PreFullBackupOptionalParams, + RestoreStatusOptionalParams, + PreFullRestoreOperationOptionalParams, + FullRestoreOperationOptionalParams, + SelectiveKeyRestoreOperationOptionalParams, + UpdateSettingOptionalParams, + GetSettingOptionalParams, + GetSettingsOptionalParams, + RoleAssignmentsDeleteOptionalParams, + RoleAssignmentsCreateOptionalParams, + RoleAssignmentsGetOptionalParams, + RoleAssignmentsListForScopeOptionalParams, + RoleDefinitionsDeleteOptionalParams, + RoleDefinitionsCreateOrUpdateOptionalParams, + RoleDefinitionsGetOptionalParams, + RoleDefinitionsListOptionalParams, +} from "./options.js"; diff --git a/sdk/keyvault/keyvault-admin/src/generated/api/keyVaultContext.ts b/sdk/keyvault/keyvault-admin/src/generated/api/keyVaultContext.ts new file mode 100644 index 000000000000..61259f1833c1 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/api/keyVaultContext.ts @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { logger } from "../logger.js"; +import { KnownVersions } from "../models/models.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; + +/** The key vault client performs cryptographic key operations and vault operations against the Key Vault service. */ +export interface KeyVaultContext extends Client {} + +/** Optional parameters for the client. */ +export interface KeyVaultClientOptionalParams extends ClientOptions { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion?: string; +} + +/** The key vault client performs cryptographic key operations and vault operations against the Key Vault service. */ +export function createKeyVault( + vaultBaseUrl: string, + credential: TokenCredential, + options: KeyVaultClientOptionalParams = {}, +): KeyVaultContext { + const endpointUrl = options.endpoint ?? options.baseUrl ?? `${vaultBaseUrl}`; + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentInfo = `azsdk-js-keyvault-admin/1.0.0-beta.1`; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api ${userAgentInfo}` + : `azsdk-js-api ${userAgentInfo}`; + const { apiVersion: _, ...updatedOptions } = { + ...options, + userAgentOptions: { userAgentPrefix }, + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, + credentials: { + scopes: options.credentials?.scopes ?? [ + "https://vault.azure.net/.default", + ], + }, + }; + const clientContext = getClient(endpointUrl, credential, updatedOptions); + clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + const apiVersion = options.apiVersion ?? "7.6-preview.1"; + clientContext.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version")) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return clientContext; +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/api/operations.ts b/sdk/keyvault/keyvault-admin/src/generated/api/operations.ts new file mode 100644 index 000000000000..483c17c896af --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/api/operations.ts @@ -0,0 +1,426 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + KeyVaultContext as Client, + FullBackupOptionalParams, + FullBackupStatusOptionalParams, + FullRestoreOperationOptionalParams, + GetSettingOptionalParams, + GetSettingsOptionalParams, + PreFullBackupOptionalParams, + PreFullRestoreOperationOptionalParams, + RestoreStatusOptionalParams, + SelectiveKeyRestoreOperationOptionalParams, + UpdateSettingOptionalParams, +} from "./index.js"; +import { + FullBackupOperation, + fullBackupOperationDeserializer, + sASTokenParameterSerializer, + preBackupOperationParametersSerializer, + RestoreOperation, + restoreOperationDeserializer, + preRestoreOperationParametersSerializer, + restoreOperationParametersSerializer, + selectiveKeyRestoreOperationParametersSerializer, + UpdateSettingRequest, + updateSettingRequestSerializer, + Setting, + settingDeserializer, + SettingsListResult, + settingsListResultDeserializer, +} from "../models/models.js"; +import { getLongRunningPoller } from "../static-helpers/pollingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { PollerLike, OperationState } from "@azure/core-lro"; + +export function _fullBackupStatusSend( + context: Client, + jobId: string, + options: FullBackupStatusOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/backup/{jobId}/pending", jobId) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _fullBackupStatusDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return fullBackupOperationDeserializer(result.body); +} + +/** Returns the status of full backup operation */ +export async function fullBackupStatus( + context: Client, + jobId: string, + options: FullBackupStatusOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _fullBackupStatusSend(context, jobId, options); + return _fullBackupStatusDeserialize(result); +} + +export function _fullBackupSend( + context: Client, + options: FullBackupOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/backup") + .post({ + ...operationOptionsToRequestParameters(options), + body: !options["azureStorageBlobContainerUri"] + ? options["azureStorageBlobContainerUri"] + : sASTokenParameterSerializer(options["azureStorageBlobContainerUri"]), + }); +} + +export async function _fullBackupDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202", "200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return fullBackupOperationDeserializer(result.body); +} + +/** Creates a full backup using a user-provided SAS token to an Azure blob storage container. */ +export function fullBackup( + context: Client, + options: FullBackupOptionalParams = { requestOptions: {} }, +): PollerLike, FullBackupOperation> { + return getLongRunningPoller(context, _fullBackupDeserialize, ["202", "200"], { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => _fullBackupSend(context, options), + resourceLocationConfig: "azure-async-operation", + skipFinalGet: options?.skipFinalGet, + }) as PollerLike, FullBackupOperation>; +} + +export function _preFullBackupSend( + context: Client, + options: PreFullBackupOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/prebackup") + .post({ + ...operationOptionsToRequestParameters(options), + body: !options["preBackupOperationParameters"] + ? options["preBackupOperationParameters"] + : preBackupOperationParametersSerializer( + options["preBackupOperationParameters"], + ), + }); +} + +export async function _preFullBackupDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202", "200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return fullBackupOperationDeserializer(result.body); +} + +/** Pre-backup operation for checking whether the customer can perform a full backup operation. */ +export function preFullBackup( + context: Client, + options: PreFullBackupOptionalParams = { requestOptions: {} }, +): PollerLike, FullBackupOperation> { + return getLongRunningPoller( + context, + _preFullBackupDeserialize, + ["202", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => _preFullBackupSend(context, options), + resourceLocationConfig: "azure-async-operation", + }, + ) as PollerLike, FullBackupOperation>; +} + +export function _restoreStatusSend( + context: Client, + jobId: string, + options: RestoreStatusOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/restore/{jobId}/pending", jobId) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _restoreStatusDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return restoreOperationDeserializer(result.body); +} + +/** Returns the status of restore operation */ +export async function restoreStatus( + context: Client, + jobId: string, + options: RestoreStatusOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _restoreStatusSend(context, jobId, options); + return _restoreStatusDeserialize(result); +} + +export function _preFullRestoreOperationSend( + context: Client, + options: PreFullRestoreOperationOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/prerestore") + .put({ + ...operationOptionsToRequestParameters(options), + body: !options["preRestoreOperationParameters"] + ? options["preRestoreOperationParameters"] + : preRestoreOperationParametersSerializer( + options["preRestoreOperationParameters"], + ), + }); +} + +export async function _preFullRestoreOperationDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202", "200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return restoreOperationDeserializer(result.body); +} + +/** Pre-restore operation for checking whether the customer can perform a full restore operation. */ +export function preFullRestoreOperation( + context: Client, + options: PreFullRestoreOperationOptionalParams = { requestOptions: {} }, +): PollerLike, RestoreOperation> { + return getLongRunningPoller( + context, + _preFullRestoreOperationDeserialize, + ["202", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => _preFullRestoreOperationSend(context, options), + resourceLocationConfig: "azure-async-operation", + }, + ) as PollerLike, RestoreOperation>; +} + +export function _fullRestoreOperationSend( + context: Client, + options: FullRestoreOperationOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/restore") + .put({ + ...operationOptionsToRequestParameters(options), + body: !options["restoreBlobDetails"] + ? options["restoreBlobDetails"] + : restoreOperationParametersSerializer(options["restoreBlobDetails"]), + }); +} + +export async function _fullRestoreOperationDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202", "200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return restoreOperationDeserializer(result.body); +} + +/** Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder */ +export function fullRestoreOperation( + context: Client, + options: FullRestoreOperationOptionalParams = { requestOptions: {} }, +): PollerLike, RestoreOperation> { + return getLongRunningPoller( + context, + _fullRestoreOperationDeserialize, + ["202", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => _fullRestoreOperationSend(context, options), + resourceLocationConfig: "azure-async-operation", + skipFinalGet: options?.skipFinalGet, + }, + ) as PollerLike, RestoreOperation>; +} + +export function _selectiveKeyRestoreOperationSend( + context: Client, + keyName: string, + options: SelectiveKeyRestoreOperationOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/keys/{keyName}/restore", keyName) + .put({ + ...operationOptionsToRequestParameters(options), + body: !options["restoreBlobDetails"] + ? options["restoreBlobDetails"] + : selectiveKeyRestoreOperationParametersSerializer( + options["restoreBlobDetails"], + ), + }); +} + +export async function _selectiveKeyRestoreOperationDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202", "200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return restoreOperationDeserializer(result.body); +} + +/** Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder */ +export function selectiveKeyRestoreOperation( + context: Client, + keyName: string, + options: SelectiveKeyRestoreOperationOptionalParams = { requestOptions: {} }, +): PollerLike, RestoreOperation> { + return getLongRunningPoller( + context, + _selectiveKeyRestoreOperationDeserialize, + ["202", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _selectiveKeyRestoreOperationSend(context, keyName, options), + resourceLocationConfig: "azure-async-operation", + skipFinalGet: options?.skipFinalGet, + }, + ) as PollerLike, RestoreOperation>; +} + +export function _updateSettingSend( + context: Client, + settingName: string, + parameters: UpdateSettingRequest, + options: UpdateSettingOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/settings/{setting-name}", settingName) + .patch({ + ...operationOptionsToRequestParameters(options), + body: updateSettingRequestSerializer(parameters), + }); +} + +export async function _updateSettingDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return settingDeserializer(result.body); +} + +/** Description of the pool setting to be updated */ +export async function updateSetting( + context: Client, + settingName: string, + parameters: UpdateSettingRequest, + options: UpdateSettingOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateSettingSend( + context, + settingName, + parameters, + options, + ); + return _updateSettingDeserialize(result); +} + +export function _getSettingSend( + context: Client, + settingName: string, + options: GetSettingOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/settings/{setting-name}", settingName) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _getSettingDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return settingDeserializer(result.body); +} + +/** Retrieves the setting object of a specified setting name. */ +export async function getSetting( + context: Client, + settingName: string, + options: GetSettingOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSettingSend(context, settingName, options); + return _getSettingDeserialize(result); +} + +export function _getSettingsSend( + context: Client, + options: GetSettingsOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/settings") + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _getSettingsDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return settingsListResultDeserializer(result.body); +} + +/** Retrieves a list of all the available account settings that can be configured. */ +export async function getSettings( + context: Client, + options: GetSettingsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSettingsSend(context, options); + return _getSettingsDeserialize(result); +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/api/options.ts b/sdk/keyvault/keyvault-admin/src/generated/api/options.ts new file mode 100644 index 000000000000..aa60d04d8953 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/api/options.ts @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { OperationOptions } from "@azure-rest/core-client"; +import { + SASTokenParameter, + PreBackupOperationParameters, + PreRestoreOperationParameters, + RestoreOperationParameters, + SelectiveKeyRestoreOperationParameters, +} from "../models/models.js"; + +/** Optional parameters. */ +export interface FullBackupStatusOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface FullBackupOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** 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; + /** Skip final GET request */ + skipFinalGet?: boolean; +} + +/** Optional parameters. */ +export interface PreFullBackupOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** Optional parameters to validate prior to performing a full backup operation. */ + preBackupOperationParameters?: PreBackupOperationParameters; +} + +/** Optional parameters. */ +export interface RestoreStatusOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface PreFullRestoreOperationOptionalParams + extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** Optional pre restore parameters to validate prior to performing a full restore operation. */ + preRestoreOperationParameters?: PreRestoreOperationParameters; +} + +/** Optional parameters. */ +export interface FullRestoreOperationOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** The Azure blob SAS token pointing to a folder where the previous successful full backup was stored. */ + restoreBlobDetails?: RestoreOperationParameters; + /** * Skip final GET request */ + skipFinalGet?: boolean; +} + +/** Optional parameters. */ +export interface SelectiveKeyRestoreOperationOptionalParams + extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** * Skip final GET request */ + skipFinalGet?: boolean; + /** The Azure blob SAS token pointing to a folder where the previous successful full backup was stored */ + restoreBlobDetails?: SelectiveKeyRestoreOperationParameters; +} + +/** Optional parameters. */ +export interface UpdateSettingOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface GetSettingOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface GetSettingsOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface RoleAssignmentsDeleteOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface RoleAssignmentsCreateOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface RoleAssignmentsGetOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface RoleAssignmentsListForScopeOptionalParams + extends 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; +} + +/** Optional parameters. */ +export interface RoleDefinitionsDeleteOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface RoleDefinitionsCreateOrUpdateOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface RoleDefinitionsGetOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface RoleDefinitionsListOptionalParams extends OperationOptions { + /** The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. */ + $filter?: string; +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/api/roleAssignments/index.ts b/sdk/keyvault/keyvault-admin/src/generated/api/roleAssignments/index.ts new file mode 100644 index 000000000000..8d0fa622b71a --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/api/roleAssignments/index.ts @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + KeyVaultContext as Client, + RoleAssignmentsCreateOptionalParams, + RoleAssignmentsDeleteOptionalParams, + RoleAssignmentsGetOptionalParams, + RoleAssignmentsListForScopeOptionalParams, +} from "../index.js"; +import { + RoleAssignment, + roleAssignmentDeserializer, + RoleAssignmentCreateParameters, + roleAssignmentCreateParametersSerializer, + _RoleAssignmentListResult, + _roleAssignmentListResultDeserializer, +} from "../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; + +export function _$deleteSend( + context: Client, + scope: string, + roleAssignmentName: string, + options: RoleAssignmentsDeleteOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", + { value: scope, allowReserved: true }, + roleAssignmentName, + ) + .delete({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _$deleteDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return roleAssignmentDeserializer(result.body); +} + +/** Deletes a role assignment. */ +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export async function $delete( + context: Client, + scope: string, + roleAssignmentName: string, + options: RoleAssignmentsDeleteOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _$deleteSend( + context, + scope, + roleAssignmentName, + options, + ); + return _$deleteDeserialize(result); +} + +export function _createSend( + context: Client, + scope: string, + roleAssignmentName: string, + parameters: RoleAssignmentCreateParameters, + options: RoleAssignmentsCreateOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", + { value: scope, allowReserved: true }, + roleAssignmentName, + ) + .put({ + ...operationOptionsToRequestParameters(options), + body: roleAssignmentCreateParametersSerializer(parameters), + }); +} + +export async function _createDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["201"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return roleAssignmentDeserializer(result.body); +} + +/** Creates a role assignment. */ +export async function create( + context: Client, + scope: string, + roleAssignmentName: string, + parameters: RoleAssignmentCreateParameters, + options: RoleAssignmentsCreateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createSend( + context, + scope, + roleAssignmentName, + parameters, + options, + ); + return _createDeserialize(result); +} + +export function _getSend( + context: Client, + scope: string, + roleAssignmentName: string, + options: RoleAssignmentsGetOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", + { value: scope, allowReserved: true }, + roleAssignmentName, + ) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _getDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return roleAssignmentDeserializer(result.body); +} + +/** Get the specified role assignment. */ +export async function get( + context: Client, + scope: string, + roleAssignmentName: string, + options: RoleAssignmentsGetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSend(context, scope, roleAssignmentName, options); + return _getDeserialize(result); +} + +export function _listForScopeSend( + context: Client, + scope: string, + options: RoleAssignmentsListForScopeOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/{scope}/providers/Microsoft.Authorization/roleAssignments", { + value: scope, + allowReserved: true, + }) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { $filter: options?.$filter }, + }); +} + +export async function _listForScopeDeserialize( + result: PathUncheckedResponse, +): Promise<_RoleAssignmentListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _roleAssignmentListResultDeserializer(result.body); +} + +/** Gets role assignments for a scope. */ +export function listForScope( + context: Client, + scope: string, + options: RoleAssignmentsListForScopeOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listForScopeSend(context, scope, options), + _listForScopeDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/api/roleDefinitions/index.ts b/sdk/keyvault/keyvault-admin/src/generated/api/roleDefinitions/index.ts new file mode 100644 index 000000000000..beeb4dcd6523 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/api/roleDefinitions/index.ts @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + KeyVaultContext as Client, + RoleDefinitionsCreateOrUpdateOptionalParams, + RoleDefinitionsDeleteOptionalParams, + RoleDefinitionsGetOptionalParams, + RoleDefinitionsListOptionalParams, +} from "../index.js"; +import { + RoleDefinition, + roleDefinitionDeserializer, + RoleDefinitionCreateParameters, + roleDefinitionCreateParametersSerializer, + _RoleDefinitionListResult, + _roleDefinitionListResultDeserializer, +} from "../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; + +export function _$deleteSend( + context: Client, + scope: string, + roleDefinitionName: string, + options: RoleDefinitionsDeleteOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}", + { value: scope, allowReserved: true }, + roleDefinitionName, + ) + .delete({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _$deleteDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return roleDefinitionDeserializer(result.body); +} + +/** Deletes a custom role definition. */ +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export async function $delete( + context: Client, + scope: string, + roleDefinitionName: string, + options: RoleDefinitionsDeleteOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _$deleteSend( + context, + scope, + roleDefinitionName, + options, + ); + return _$deleteDeserialize(result); +} + +export function _createOrUpdateSend( + context: Client, + scope: string, + roleDefinitionName: string, + parameters: RoleDefinitionCreateParameters, + options: RoleDefinitionsCreateOrUpdateOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}", + { value: scope, allowReserved: true }, + roleDefinitionName, + ) + .put({ + ...operationOptionsToRequestParameters(options), + body: roleDefinitionCreateParametersSerializer(parameters), + }); +} + +export async function _createOrUpdateDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["201"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return roleDefinitionDeserializer(result.body); +} + +/** Creates or updates a custom role definition. */ +export async function createOrUpdate( + context: Client, + scope: string, + roleDefinitionName: string, + parameters: RoleDefinitionCreateParameters, + options: RoleDefinitionsCreateOrUpdateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateSend( + context, + scope, + roleDefinitionName, + parameters, + options, + ); + return _createOrUpdateDeserialize(result); +} + +export function _getSend( + context: Client, + scope: string, + roleDefinitionName: string, + options: RoleDefinitionsGetOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}", + { value: scope, allowReserved: true }, + roleDefinitionName, + ) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _getDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return roleDefinitionDeserializer(result.body); +} + +/** Get the specified role definition. */ +export async function get( + context: Client, + scope: string, + roleDefinitionName: string, + options: RoleDefinitionsGetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSend(context, scope, roleDefinitionName, options); + return _getDeserialize(result); +} + +export function _listSend( + context: Client, + scope: string, + options: RoleDefinitionsListOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/{scope}/providers/Microsoft.Authorization/roleDefinitions", { + value: scope, + allowReserved: true, + }) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { $filter: options?.$filter }, + }); +} + +export async function _listDeserialize( + result: PathUncheckedResponse, +): Promise<_RoleDefinitionListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _roleDefinitionListResultDeserializer(result.body); +} + +/** Get all role definitions that are applicable at scope and above. */ +export function list( + context: Client, + scope: string, + options: RoleDefinitionsListOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listSend(context, scope, options), + _listDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/classic/index.ts b/sdk/keyvault/keyvault-admin/src/generated/classic/index.ts new file mode 100644 index 000000000000..babf01fb07fc --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/classic/index.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { RoleAssignmentsOperations } from "./roleAssignments/index.js"; +export { RoleDefinitionsOperations } from "./roleDefinitions/index.js"; diff --git a/sdk/keyvault/keyvault-admin/src/generated/classic/roleAssignments/index.ts b/sdk/keyvault/keyvault-admin/src/generated/classic/roleAssignments/index.ts new file mode 100644 index 000000000000..705db5b65af2 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/classic/roleAssignments/index.ts @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { KeyVaultContext } from "../../api/keyVaultContext.js"; +import { + RoleAssignmentsDeleteOptionalParams, + RoleAssignmentsCreateOptionalParams, + RoleAssignmentsGetOptionalParams, + RoleAssignmentsListForScopeOptionalParams, +} from "../../api/options.js"; +import { + $delete, + create, + get, + listForScope, +} from "../../api/roleAssignments/index.js"; +import { + RoleAssignment, + RoleAssignmentCreateParameters, +} from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; + +/** Interface representing a RoleAssignments operations. */ +export interface RoleAssignmentsOperations { + /** Deletes a role assignment. */ + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ + delete: ( + scope: string, + roleAssignmentName: string, + options?: RoleAssignmentsDeleteOptionalParams, + ) => Promise; + /** Creates a role assignment. */ + create: ( + scope: string, + roleAssignmentName: string, + parameters: RoleAssignmentCreateParameters, + options?: RoleAssignmentsCreateOptionalParams, + ) => Promise; + /** Get the specified role assignment. */ + get: ( + scope: string, + roleAssignmentName: string, + options?: RoleAssignmentsGetOptionalParams, + ) => Promise; + /** Gets role assignments for a scope. */ + listForScope: ( + scope: string, + options?: RoleAssignmentsListForScopeOptionalParams, + ) => PagedAsyncIterableIterator; +} + +export function getRoleAssignments(context: KeyVaultContext) { + return { + delete: ( + scope: string, + roleAssignmentName: string, + options?: RoleAssignmentsDeleteOptionalParams, + ) => $delete(context, scope, roleAssignmentName, options), + create: ( + scope: string, + roleAssignmentName: string, + parameters: RoleAssignmentCreateParameters, + options?: RoleAssignmentsCreateOptionalParams, + ) => create(context, scope, roleAssignmentName, parameters, options), + get: ( + scope: string, + roleAssignmentName: string, + options?: RoleAssignmentsGetOptionalParams, + ) => get(context, scope, roleAssignmentName, options), + listForScope: ( + scope: string, + options?: RoleAssignmentsListForScopeOptionalParams, + ) => listForScope(context, scope, options), + }; +} + +export function getRoleAssignmentsOperations( + context: KeyVaultContext, +): RoleAssignmentsOperations { + return { + ...getRoleAssignments(context), + }; +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/classic/roleDefinitions/index.ts b/sdk/keyvault/keyvault-admin/src/generated/classic/roleDefinitions/index.ts new file mode 100644 index 000000000000..7effac9a8422 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/classic/roleDefinitions/index.ts @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { KeyVaultContext } from "../../api/keyVaultContext.js"; +import { + RoleDefinitionsDeleteOptionalParams, + RoleDefinitionsCreateOrUpdateOptionalParams, + RoleDefinitionsGetOptionalParams, + RoleDefinitionsListOptionalParams, +} from "../../api/options.js"; +import { + $delete, + createOrUpdate, + get, + list, +} from "../../api/roleDefinitions/index.js"; +import { + RoleDefinition, + RoleDefinitionCreateParameters, +} from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; + +/** Interface representing a RoleDefinitions operations. */ +export interface RoleDefinitionsOperations { + /** Deletes a custom role definition. */ + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ + delete: ( + scope: string, + roleDefinitionName: string, + options?: RoleDefinitionsDeleteOptionalParams, + ) => Promise; + /** Creates or updates a custom role definition. */ + createOrUpdate: ( + scope: string, + roleDefinitionName: string, + parameters: RoleDefinitionCreateParameters, + options?: RoleDefinitionsCreateOrUpdateOptionalParams, + ) => Promise; + /** Get the specified role definition. */ + get: ( + scope: string, + roleDefinitionName: string, + options?: RoleDefinitionsGetOptionalParams, + ) => Promise; + /** Get all role definitions that are applicable at scope and above. */ + list: ( + scope: string, + options?: RoleDefinitionsListOptionalParams, + ) => PagedAsyncIterableIterator; +} + +export function getRoleDefinitions(context: KeyVaultContext) { + return { + delete: ( + scope: string, + roleDefinitionName: string, + options?: RoleDefinitionsDeleteOptionalParams, + ) => $delete(context, scope, roleDefinitionName, options), + createOrUpdate: ( + scope: string, + roleDefinitionName: string, + parameters: RoleDefinitionCreateParameters, + options?: RoleDefinitionsCreateOrUpdateOptionalParams, + ) => + createOrUpdate(context, scope, roleDefinitionName, parameters, options), + get: ( + scope: string, + roleDefinitionName: string, + options?: RoleDefinitionsGetOptionalParams, + ) => get(context, scope, roleDefinitionName, options), + list: (scope: string, options?: RoleDefinitionsListOptionalParams) => + list(context, scope, options), + }; +} + +export function getRoleDefinitionsOperations( + context: KeyVaultContext, +): RoleDefinitionsOperations { + return { + ...getRoleDefinitions(context), + }; +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/helpers/serializerHelpers.ts b/sdk/keyvault/keyvault-admin/src/generated/helpers/serializerHelpers.ts new file mode 100644 index 000000000000..4baaac77c8be --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/index.ts b/sdk/keyvault/keyvault-admin/src/generated/index.ts index 00de1c72d4c7..105ca6c088be 100644 --- a/sdk/keyvault/keyvault-admin/src/generated/index.ts +++ b/sdk/keyvault/keyvault-admin/src/generated/index.ts @@ -1,12 +1,73 @@ -/* - * 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. - */ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./static-helpers/pagingHelpers.js"; -export * from "./models/index.js"; export { KeyVaultClient } from "./keyVaultClient.js"; -export { KeyVaultClientContext } from "./keyVaultClientContext.js"; -export * from "./operationsInterfaces/index.js"; +export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; +export { + FullBackupOperation, + KnownOperationStatus, + OperationStatus, + ErrorModel, + KeyVaultError, + SASTokenParameter, + PreBackupOperationParameters, + RestoreOperation, + PreRestoreOperationParameters, + RestoreOperationParameters, + SelectiveKeyRestoreOperationParameters, + SelectiveKeyRestoreOperation, + UpdateSettingRequest, + Setting, + KnownSettingTypeEnum, + SettingTypeEnum, + SettingsListResult, + RoleDefinition, + KnownRoleDefinitionType, + RoleDefinitionType, + RoleDefinitionProperties, + KnownRoleType, + RoleType, + Permission, + KnownDataAction, + DataAction, + KnownRoleScope, + RoleScope, + RoleDefinitionCreateParameters, + RoleAssignment, + RoleAssignmentPropertiesWithScope, + RoleAssignmentCreateParameters, + RoleAssignmentProperties, + KnownVersions, +} from "./models/index.js"; +export { + KeyVaultClientOptionalParams, + FullBackupStatusOptionalParams, + FullBackupOptionalParams, + PreFullBackupOptionalParams, + RestoreStatusOptionalParams, + PreFullRestoreOperationOptionalParams, + FullRestoreOperationOptionalParams, + SelectiveKeyRestoreOperationOptionalParams, + UpdateSettingOptionalParams, + GetSettingOptionalParams, + GetSettingsOptionalParams, + RoleAssignmentsDeleteOptionalParams, + RoleAssignmentsCreateOptionalParams, + RoleAssignmentsGetOptionalParams, + RoleAssignmentsListForScopeOptionalParams, + RoleDefinitionsDeleteOptionalParams, + RoleDefinitionsCreateOrUpdateOptionalParams, + RoleDefinitionsGetOptionalParams, + RoleDefinitionsListOptionalParams, +} from "./api/index.js"; +export { + RoleAssignmentsOperations, + RoleDefinitionsOperations, +} from "./classic/index.js"; +export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts b/sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts index 231f5afe0cef..78796777f793 100644 --- a/sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts +++ b/sdk/keyvault/keyvault-admin/src/generated/keyVaultClient.ts @@ -1,332 +1,156 @@ -/* - * 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. - */ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. -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 { + getRoleAssignmentsOperations, + RoleAssignmentsOperations, +} from "./classic/roleAssignments/index.js"; +import { + getRoleDefinitionsOperations, + RoleDefinitionsOperations, +} from "./classic/roleDefinitions/index.js"; +import { + createKeyVault, + KeyVaultContext, KeyVaultClientOptionalParams, - ApiVersion75, - FullBackupOptionalParams, - FullBackupResponse, + fullBackupStatus, + fullBackup, + preFullBackup, + restoreStatus, + preFullRestoreOperation, + fullRestoreOperation, + selectiveKeyRestoreOperation, + updateSetting, + getSetting, + getSettings, FullBackupStatusOptionalParams, - FullBackupStatusResponse, - FullRestoreOperationOptionalParams, - FullRestoreOperationResponse, + FullBackupOptionalParams, + PreFullBackupOptionalParams, RestoreStatusOptionalParams, - RestoreStatusResponse, + PreFullRestoreOperationOptionalParams, + FullRestoreOperationOptionalParams, SelectiveKeyRestoreOperationOptionalParams, - SelectiveKeyRestoreOperationResponse, UpdateSettingOptionalParams, - UpdateSettingResponse, GetSettingOptionalParams, - GetSettingResponse, GetSettingsOptionalParams, - GetSettingsResponse -} from "./models/index.js"; +} from "./api/index.js"; +import { + FullBackupOperation, + RestoreOperation, + UpdateSettingRequest, + Setting, + SettingsListResult, +} from "./models/models.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; +import { PollerLike, OperationState } from "@azure/core-lro"; -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); - } +export { KeyVaultClientOptionalParams } from "./api/keyVaultContext.js"; - /** - * 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( +export class KeyVaultClient { + private _client: KeyVaultContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; + + /** The key vault client performs cryptographic key operations and vault operations against the Key Vault service. */ + constructor( vaultBaseUrl: string, - options?: FullBackupOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, options }, - fullBackupOperationSpec - ); + credential: TokenCredential, + options: KeyVaultClientOptionalParams = {}, + ) { + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : `azsdk-js-client`; + this._client = createKeyVault(vaultBaseUrl, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); + this.pipeline = this._client.pipeline; + this.roleAssignments = getRoleAssignmentsOperations(this._client); + this.roleDefinitions = getRoleDefinitionsOperations(this._client); } - /** - * 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. - */ + /** Returns the status of full backup operation */ fullBackupStatus( - vaultBaseUrl: string, jobId: string, - options?: FullBackupStatusOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, jobId, options }, - fullBackupStatusOperationSpec - ); + options: FullBackupStatusOptionalParams = { requestOptions: {} }, + ): Promise { + return fullBackupStatus(this._client, jobId, options); } - /** - * 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 - ); + /** Creates a full backup using a user-provided SAS token to an Azure blob storage container. */ + fullBackup( + options: FullBackupOptionalParams = { requestOptions: {} }, + ): PollerLike, FullBackupOperation> { + return fullBackup(this._client, options); + } + + /** Pre-backup operation for checking whether the customer can perform a full backup operation. */ + preFullBackup( + options: PreFullBackupOptionalParams = { requestOptions: {} }, + ): PollerLike, FullBackupOperation> { + return preFullBackup(this._client, options); } - /** - * 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. - */ + /** Returns the status of restore operation */ restoreStatus( - vaultBaseUrl: string, jobId: string, - options?: RestoreStatusOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, jobId, options }, - restoreStatusOperationSpec - ); + options: RestoreStatusOptionalParams = { requestOptions: {} }, + ): Promise { + return restoreStatus(this._client, jobId, options); + } + + /** Pre-restore operation for checking whether the customer can perform a full restore operation. */ + preFullRestoreOperation( + options: PreFullRestoreOperationOptionalParams = { requestOptions: {} }, + ): PollerLike, RestoreOperation> { + return preFullRestoreOperation(this._client, options); + } + + /** Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder */ + fullRestoreOperation( + options: FullRestoreOperationOptionalParams = { requestOptions: {} }, + ): PollerLike, RestoreOperation> { + return fullRestoreOperation(this._client, options); } - /** - * 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. - */ + /** Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob storage backup folder */ selectiveKeyRestoreOperation( - vaultBaseUrl: string, keyName: string, - options?: SelectiveKeyRestoreOperationOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, keyName, options }, - selectiveKeyRestoreOperationOperationSpec - ); + options: SelectiveKeyRestoreOperationOptionalParams = { + requestOptions: {}, + }, + ): PollerLike, RestoreOperation> { + return selectiveKeyRestoreOperation(this._client, keyName, options); } - /** - * 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. - */ + /** Description of the pool setting to be updated */ updateSetting( - vaultBaseUrl: string, settingName: string, - value: string, - options?: UpdateSettingOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, settingName, value, options }, - updateSettingOperationSpec - ); + parameters: UpdateSettingRequest, + options: UpdateSettingOptionalParams = { requestOptions: {} }, + ): Promise { + return updateSetting(this._client, settingName, parameters, options); } - /** - * 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. - */ + /** Retrieves the setting object of a specified setting name. */ getSetting( - vaultBaseUrl: string, settingName: string, - options?: GetSettingOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, settingName, options }, - getSettingOperationSpec - ); + options: GetSettingOptionalParams = { requestOptions: {} }, + ): Promise { + return getSetting(this._client, settingName, options); } - /** - * 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. - */ + /** Retrieves a list of all the available account settings that can be configured. */ getSettings( - vaultBaseUrl: string, - options?: GetSettingsOptionalParams - ): Promise { - return this.sendOperationRequest( - { vaultBaseUrl, options }, - getSettingsOperationSpec - ); + options: GetSettingsOptionalParams = { requestOptions: {} }, + ): Promise { + return getSettings(this._client, options); } - roleDefinitions: RoleDefinitions; - roleAssignments: RoleAssignments; + /** The operation groups for RoleAssignments */ + public readonly roleAssignments: RoleAssignmentsOperations; + /** The operation groups for RoleDefinitions */ + public readonly roleDefinitions: RoleDefinitionsOperations; } -// 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/logger.ts b/sdk/keyvault/keyvault-admin/src/generated/logger.ts new file mode 100644 index 000000000000..24ae3e9aa089 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("keyvault-admin"); diff --git a/sdk/keyvault/keyvault-admin/src/generated/models/index.ts b/sdk/keyvault/keyvault-admin/src/generated/models/index.ts index 6ca193d29c71..57d9141513ba 100644 --- a/sdk/keyvault/keyvault-admin/src/generated/models/index.ts +++ b/sdk/keyvault/keyvault-admin/src/generated/models/index.ts @@ -1,632 +1,39 @@ -/* - * 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; -} +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { + FullBackupOperation, + KnownOperationStatus, + OperationStatus, + ErrorModel, + KeyVaultError, + SASTokenParameter, + PreBackupOperationParameters, + RestoreOperation, + PreRestoreOperationParameters, + RestoreOperationParameters, + SelectiveKeyRestoreOperationParameters, + SelectiveKeyRestoreOperation, + UpdateSettingRequest, + Setting, + KnownSettingTypeEnum, + SettingTypeEnum, + SettingsListResult, + RoleDefinition, + KnownRoleDefinitionType, + RoleDefinitionType, + RoleDefinitionProperties, + KnownRoleType, + RoleType, + Permission, + KnownDataAction, + DataAction, + KnownRoleScope, + RoleScope, + RoleDefinitionCreateParameters, + RoleAssignment, + RoleAssignmentPropertiesWithScope, + RoleAssignmentCreateParameters, + RoleAssignmentProperties, + KnownVersions, +} from "./models.js"; 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/models.ts b/sdk/keyvault/keyvault-admin/src/generated/models/models.ts new file mode 100644 index 000000000000..d92d44562e8b --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/models/models.ts @@ -0,0 +1,772 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** Full backup operation */ +export interface FullBackupOperation { + /** Status of the backup operation. */ + status?: OperationStatus; + /** 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 */ + folderUri?: string; +} + +export function fullBackupOperationDeserializer( + item: any, +): FullBackupOperation { + return { + status: item["status"], + statusDetails: item["statusDetails"], + error: !item["error"] ? item["error"] : errorDeserializer(item["error"]), + startTime: !item["startTime"] + ? item["startTime"] + : new Date(item["startTime"] * 1000), + endTime: !item["endTime"] + ? item["endTime"] + : new Date(item["endTime"] * 1000), + jobId: item["jobId"], + folderUri: item["azureStorageBlobContainerUri"], + }; +} + +/** The status of a long-running operation. */ +export enum KnownOperationStatus { + /** The operation is in progress. */ + InProgress = "InProgress", + /** The operation successfully completed. */ + Succeeded = "Succeeded", + /** The operation was canceled. */ + Canceled = "Canceled", + /** The operation failed. */ + Failed = "Failed", +} + +/** + * The status of a long-running operation. \ + * {@link KnownOperationStatus} can be used interchangeably with OperationStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **InProgress**: The operation is in progress. \ + * **Succeeded**: The operation successfully completed. \ + * **Canceled**: The operation was canceled. \ + * **Failed**: The operation failed. + */ +export type OperationStatus = string; + +/** The key vault server error. */ +export interface ErrorModel { + /** The error code. */ + readonly code?: string; + /** The error message. */ + readonly message?: string; + /** The key vault server error. */ + readonly innerError?: ErrorModel; +} + +export function errorDeserializer(item: any): ErrorModel { + return { + code: item["code"], + message: item["message"], + innerError: !item["innererror"] + ? item["innererror"] + : errorDeserializer(item["innererror"]), + }; +} + +/** The key vault error exception. */ +export interface KeyVaultError { + /** The key vault server error. */ + readonly error?: ErrorModel; +} + +export function keyVaultErrorDeserializer(item: any): KeyVaultError { + return { + error: !item["error"] ? item["error"] : errorDeserializer(item["error"]), + }; +} + +/** An authentication method and location for the operation. */ +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; +} + +export function sASTokenParameterSerializer(item: SASTokenParameter): any { + return { + storageResourceUri: item["storageResourceUri"], + token: item["token"], + useManagedIdentity: item["useManagedIdentity"], + }; +} + +/** The authentication method and location for the backup operation. */ +export interface PreBackupOperationParameters { + /** 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; +} + +export function preBackupOperationParametersSerializer( + item: PreBackupOperationParameters, +): any { + return { + storageResourceUri: item["storageResourceUri"], + token: item["token"], + useManagedIdentity: item["useManagedIdentity"], + }; +} + +/** Restore operation */ +export interface RestoreOperation { + /** Status of the restore operation. */ + status?: OperationStatus; + /** 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 function restoreOperationDeserializer(item: any): RestoreOperation { + return { + status: item["status"], + statusDetails: item["statusDetails"], + error: !item["error"] ? item["error"] : errorDeserializer(item["error"]), + jobId: item["jobId"], + startTime: !item["startTime"] + ? item["startTime"] + : new Date(item["startTime"] * 1000), + endTime: !item["endTime"] + ? item["endTime"] + : new Date(item["endTime"] * 1000), + }; +} + +/** The authentication method and location for the restore operation. */ +export interface PreRestoreOperationParameters { + /** A user-provided SAS token to an Azure blob storage container. */ + sasTokenParameters?: SASTokenParameter; + /** The Folder name of the blob where the previous successful full backup was stored */ + folderToRestore?: string; +} + +export function preRestoreOperationParametersSerializer( + item: PreRestoreOperationParameters, +): any { + return { + sasTokenParameters: !item["sasTokenParameters"] + ? item["sasTokenParameters"] + : sASTokenParameterSerializer(item["sasTokenParameters"]), + folderToRestore: item["folderToRestore"], + }; +} + +/** The authentication method and location for the restore operation. */ +export interface RestoreOperationParameters { + /** A user-provided SAS token to an Azure blob storage container. */ + sasTokenParameters: SASTokenParameter; + /** The Folder name of the blob where the previous successful full backup was stored */ + folderToRestore: string; +} + +export function restoreOperationParametersSerializer( + item: RestoreOperationParameters, +): any { + return { + sasTokenParameters: sASTokenParameterSerializer(item["sasTokenParameters"]), + folderToRestore: item["folderToRestore"], + }; +} + +/** The authentication method and location for the selective key restore operation. */ +export interface SelectiveKeyRestoreOperationParameters { + /** A user-provided SAS token to an Azure blob storage container. */ + sasTokenParameters: SASTokenParameter; + /** The Folder name of the blob where the previous successful full backup was stored */ + folder: string; +} + +export function selectiveKeyRestoreOperationParametersSerializer( + item: SelectiveKeyRestoreOperationParameters, +): any { + return { + sasTokenParameters: sASTokenParameterSerializer(item["sasTokenParameters"]), + folder: item["folder"], + }; +} + +/** Selective Key Restore operation */ +export interface SelectiveKeyRestoreOperation { + /** Status of the restore operation. */ + status?: OperationStatus; + /** 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; +} + +export function selectiveKeyRestoreOperationDeserializer( + item: any, +): SelectiveKeyRestoreOperation { + return { + status: item["status"], + statusDetails: item["statusDetails"], + error: !item["error"] ? item["error"] : errorDeserializer(item["error"]), + jobId: item["jobId"], + startTime: !item["startTime"] + ? item["startTime"] + : new Date(item["startTime"] * 1000), + endTime: !item["endTime"] + ? item["endTime"] + : new Date(item["endTime"] * 1000), + }; +} + +/** The update settings request object. */ +export interface UpdateSettingRequest { + /** The value of the pool setting. */ + value: string; +} + +export function updateSettingRequestSerializer( + item: UpdateSettingRequest, +): any { + return { value: item["value"] }; +} + +/** A Key Vault account setting. */ +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; +} + +export function settingDeserializer(item: any): Setting { + return { + name: item["name"], + value: item["value"], + type: item["type"], + }; +} + +/** The type specifier of the value. */ +export enum KnownSettingTypeEnum { + /** A boolean setting value. */ + boolean = "boolean", +} + +/** + * The type specifier of the value. \ + * {@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**: A boolean setting value. + */ +export type SettingTypeEnum = string; + +/** The settings list result. */ +export interface SettingsListResult { + /** A response message containing a list of account settings with their associated value. */ + readonly settings?: Setting[]; +} + +export function settingsListResultDeserializer(item: any): SettingsListResult { + return { + settings: !item["settings"] + ? item["settings"] + : settingArrayDeserializer(item["settings"]), + }; +} + +export function settingArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return settingDeserializer(item); + }); +} + +/** Role definition. */ +export interface RoleDefinition { + /** The role definition ID. */ + readonly id?: string; + /** The role definition name. */ + readonly name?: string; + /** The role definition type. */ + readonly type?: RoleDefinitionType; + /** Role definition properties. */ + properties?: RoleDefinitionProperties; +} + +export function roleDefinitionDeserializer(item: any): RoleDefinition { + return { + id: item["id"], + name: item["name"], + type: item["type"], + properties: !item["properties"] + ? item["properties"] + : roleDefinitionPropertiesDeserializer(item["properties"]), + }; +} + +/** The role definition type. */ +export enum KnownRoleDefinitionType { + /** Microsoft-defined role definitions. */ + "Microsoft.Authorization/roleDefinitions" = "Microsoft.Authorization/roleDefinitions", +} + +/** + * The role definition type. \ + * {@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**: Microsoft-defined role definitions. + */ +export type RoleDefinitionType = string; + +/** 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[]; +} + +export function roleDefinitionPropertiesSerializer( + item: RoleDefinitionProperties, +): any { + return { + roleName: item["roleName"], + description: item["description"], + type: item["roleType"], + permissions: !item["permissions"] + ? item["permissions"] + : permissionArraySerializer(item["permissions"]), + assignableScopes: !item["assignableScopes"] + ? item["assignableScopes"] + : item["assignableScopes"].map((p: any) => { + return p; + }), + }; +} + +export function roleDefinitionPropertiesDeserializer( + item: any, +): RoleDefinitionProperties { + return { + roleName: item["roleName"], + description: item["description"], + roleType: item["type"], + permissions: !item["permissions"] + ? item["permissions"] + : permissionArrayDeserializer(item["permissions"]), + assignableScopes: !item["assignableScopes"] + ? item["assignableScopes"] + : item["assignableScopes"].map((p: any) => { + return p; + }), + }; +} + +/** The role type. */ +export enum KnownRoleType { + /** Built in role. */ + BuiltInRole = "AKVBuiltInRole", + /** Custom role. */ + CustomRole = "CustomRole", +} + +/** + * The role type. \ + * {@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; + +export function permissionArraySerializer(result: Array): any[] { + return result.map((item) => { + return permissionSerializer(item); + }); +} + +export function permissionArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return permissionDeserializer(item); + }); +} + +/** 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[]; +} + +export function permissionSerializer(item: Permission): any { + return { + actions: !item["actions"] + ? item["actions"] + : item["actions"].map((p: any) => { + return p; + }), + notActions: !item["notActions"] + ? item["notActions"] + : item["notActions"].map((p: any) => { + return p; + }), + dataActions: !item["dataActions"] + ? item["dataActions"] + : item["dataActions"].map((p: any) => { + return p; + }), + notDataActions: !item["notDataActions"] + ? item["notDataActions"] + : item["notDataActions"].map((p: any) => { + return p; + }), + }; +} + +export function permissionDeserializer(item: any): Permission { + return { + actions: !item["actions"] + ? item["actions"] + : item["actions"].map((p: any) => { + return p; + }), + notActions: !item["notActions"] + ? item["notActions"] + : item["notActions"].map((p: any) => { + return p; + }), + dataActions: !item["dataActions"] + ? item["dataActions"] + : item["dataActions"].map((p: any) => { + return p; + }), + notDataActions: !item["notDataActions"] + ? item["notDataActions"] + : item["notDataActions"].map((p: any) => { + return p; + }), + }; +} + +/** Supported permissions for data actions. */ +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", +} + +/** + * Supported permissions for data actions. \ + * {@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; + +/** The role scope. */ +export enum KnownRoleScope { + /** Global scope */ + Global = "/", + /** Keys scope */ + Keys = "/keys", +} + +/** + * The role scope. \ + * {@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; + +/** Role definition create parameters. */ +export interface RoleDefinitionCreateParameters { + /** Role definition properties. */ + properties: RoleDefinitionProperties; +} + +export function roleDefinitionCreateParametersSerializer( + item: RoleDefinitionCreateParameters, +): any { + return { properties: roleDefinitionPropertiesSerializer(item["properties"]) }; +} + +/** 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; +} + +export function _roleDefinitionListResultDeserializer( + item: any, +): _RoleDefinitionListResult { + return { + value: !item["value"] + ? item["value"] + : roleDefinitionArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function roleDefinitionArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return roleDefinitionDeserializer(item); + }); +} + +/** Role Assignments */ +export interface RoleAssignment { + /** The role assignment ID. */ + readonly id?: string; + /** The role assignment name. */ + readonly name?: string; + /** The role assignment type. */ + readonly type?: string; + /** Role assignment properties. */ + properties?: RoleAssignmentPropertiesWithScope; +} + +export function roleAssignmentDeserializer(item: any): RoleAssignment { + return { + id: item["id"], + name: item["name"], + type: item["type"], + properties: !item["properties"] + ? item["properties"] + : roleAssignmentPropertiesWithScopeDeserializer(item["properties"]), + }; +} + +/** Role assignment properties with scope. */ +export interface RoleAssignmentPropertiesWithScope { + /** The role scope. */ + scope?: RoleScope; + /** The role definition ID. */ + roleDefinitionId?: string; + /** The principal ID. */ + principalId?: string; +} + +export function roleAssignmentPropertiesWithScopeDeserializer( + item: any, +): RoleAssignmentPropertiesWithScope { + return { + scope: item["scope"], + roleDefinitionId: item["roleDefinitionId"], + principalId: item["principalId"], + }; +} + +/** Role assignment create parameters. */ +export interface RoleAssignmentCreateParameters { + /** Role assignment properties. */ + properties: RoleAssignmentProperties; +} + +export function roleAssignmentCreateParametersSerializer( + item: RoleAssignmentCreateParameters, +): any { + return { properties: roleAssignmentPropertiesSerializer(item["properties"]) }; +} + +/** 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; +} + +export function roleAssignmentPropertiesSerializer( + item: RoleAssignmentProperties, +): any { + return { + roleDefinitionId: item["roleDefinitionId"], + principalId: item["principalId"], + }; +} + +/** 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 function _roleAssignmentListResultDeserializer( + item: any, +): _RoleAssignmentListResult { + return { + value: !item["value"] + ? item["value"] + : roleAssignmentArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function roleAssignmentArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return roleAssignmentDeserializer(item); + }); +} + +/** The available API versions. */ +export enum KnownVersions { + /** The 7.5 API version. */ + "v7.5" = "7.5", + /** The 7.6-preview.1 API version. */ + "v7.6_preview.1" = "7.6-preview.1", +} diff --git a/sdk/keyvault/keyvault-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/generated/restorePollerHelpers.ts b/sdk/keyvault/keyvault-admin/src/generated/restorePollerHelpers.ts new file mode 100644 index 000000000000..de3e1cf42bb5 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/restorePollerHelpers.ts @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { KeyVaultClient } from "./keyVaultClient.js"; +import { + _fullBackupDeserialize, + _preFullBackupDeserialize, + _preFullRestoreOperationDeserialize, + _fullRestoreOperationDeserialize, + _selectiveKeyRestoreOperationDeserialize, +} from "./api/operations.js"; +import { getLongRunningPoller } from "./static-helpers/pollingHelpers.js"; +import { + OperationOptions, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; +import { + PollerLike, + OperationState, + deserializeState, + ResourceLocationConfig, +} from "@azure/core-lro"; + +export interface RestorePollerOptions< + TResult, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +> extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** Deserialization function for raw response body */ + processResponseBody?: (result: TResponse) => Promise; +} + +/** + * Creates a poller from the serialized state of another poller. This can be + * useful when you want to create pollers on a different host or a poller + * needs to be constructed after the original one is not in scope. + */ +export function restorePoller( + client: KeyVaultClient, + serializedState: string, + sourceOperation: ( + ...args: any[] + ) => PollerLike, TResult>, + options?: RestorePollerOptions, +): PollerLike, TResult> { + const pollerConfig = deserializeState(serializedState).config; + const { initialRequestUrl, requestMethod, metadata } = pollerConfig; + if (!initialRequestUrl || !requestMethod) { + throw new Error( + `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, + ); + } + const resourceLocationConfig = metadata?.["resourceLocationConfig"] as + | ResourceLocationConfig + | undefined; + const { deserializer, expectedStatuses = [] } = + getDeserializationHelper(initialRequestUrl, requestMethod) ?? {}; + const deserializeHelper = options?.processResponseBody ?? deserializer; + if (!deserializeHelper) { + throw new Error( + `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, + ); + } + return getLongRunningPoller( + (client as any)["_client"] ?? client, + deserializeHelper as (result: TResponse) => Promise, + expectedStatuses, + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + resourceLocationConfig, + restoreFrom: serializedState, + initialRequestUrl, + }, + ); +} + +interface DeserializationHelper { + deserializer: Function; + expectedStatuses: string[]; +} + +const deserializeMap: Record = { + "POST /backup": { + deserializer: _fullBackupDeserialize, + expectedStatuses: ["202", "200"], + }, + "POST /prebackup": { + deserializer: _preFullBackupDeserialize, + expectedStatuses: ["202", "200"], + }, + "PUT /prerestore": { + deserializer: _preFullRestoreOperationDeserialize, + expectedStatuses: ["202", "200"], + }, + "PUT /restore": { + deserializer: _fullRestoreOperationDeserialize, + expectedStatuses: ["202", "200"], + }, + "PUT /keys/{keyName}/restore": { + deserializer: _selectiveKeyRestoreOperationDeserialize, + expectedStatuses: ["202", "200"], + }, +}; + +function getDeserializationHelper( + urlStr: string, + method: string, +): DeserializationHelper | undefined { + const path = new URL(urlStr).pathname; + const pathParts = path.split("/"); + + // Traverse list to match the longest candidate + // matchedLen: the length of candidate path + // matchedValue: the matched status code array + let matchedLen = -1, + matchedValue: DeserializationHelper | undefined; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(deserializeMap)) { + // Extracting the path from the map key which is in format + // GET /path/foo + if (!key.startsWith(method)) { + continue; + } + const candidatePath = getPathFromMapKey(key); + // Get each part of the url path + const candidateParts = candidatePath.split("/"); + + // track if we have found a match to return the values found. + let found = true; + for ( + let i = candidateParts.length - 1, j = pathParts.length - 1; + i >= 1 && j >= 1; + i--, j-- + ) { + if ( + candidateParts[i]?.startsWith("{") && + candidateParts[i]?.indexOf("}") !== -1 + ) { + const start = candidateParts[i]!.indexOf("}") + 1, + end = candidateParts[i]?.length; + // If the current part of the candidate is a "template" part + // Try to use the suffix of pattern to match the path + // {guid} ==> $ + // {guid}:export ==> :export$ + const isMatched = new RegExp( + `${candidateParts[i]?.slice(start, end)}`, + ).test(pathParts[j] || ""); + + if (!isMatched) { + found = false; + break; + } + continue; + } + + // If the candidate part is not a template and + // the parts don't match mark the candidate as not found + // to move on with the next candidate path. + if (candidateParts[i] !== pathParts[j]) { + found = false; + break; + } + } + + // We finished evaluating the current candidate parts + // Update the matched value if and only if we found the longer pattern + if (found && candidatePath.length > matchedLen) { + matchedLen = candidatePath.length; + matchedValue = value; + } + } + + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/static-helpers/pagingHelpers.ts b/sdk/keyvault/keyvault-admin/src/generated/static-helpers/pagingHelpers.ts new file mode 100644 index 000000000000..97a81e74e301 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/static-helpers/pagingHelpers.ts @@ -0,0 +1,274 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; + +/** + * Options for the byPage method + */ +export interface PageSettings { + /** + * A reference to a specific page to start iterating from. + */ + continuationToken?: string; +} + +/** + * An interface that describes a page of results. + */ +export type ContinuablePage = TPage & { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +}; + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; +} + +/** + * An interface that describes how to communicate with the service. + */ +export interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * Link to the first page of results. + */ + firstPageLink?: string; + /** + * A method that returns a page of results. + */ + getPage: ( + pageLink?: string, + ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; + /** + * a function to implement the `byPage` method on the paged async iterator. + */ + byPage?: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; + + /** + * A function to extract elements from a page. + */ + toElements?: (page: TPage) => TElement[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ +export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +>( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => PromiseLike, + expectedStatuses: string[], + options: BuildPagedAsyncIteratorOptions = {}, +): PagedAsyncIterableIterator { + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; + const pagedResult: PagedResult = { + getPage: async (pageLink?: string) => { + const result = + pageLink === undefined + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + checkPagingRequest(result, expectedStatuses); + const results = await processResponseBody(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName) as TPage; + return { + page: values, + nextPageLink: nextLink, + }; + }, + byPage: (settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }, + }; + return getPagedAsyncIterator(pagedResult); +} + +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ + +function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult, + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; +} + +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + for await (const page of pages) { + yield* page as unknown as TElement[]; + } +} + +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {}, +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink, + ); + if (!response) { + return; + } + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + } +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { + throw new RestError( + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}`, + ); + } + + if (nextLink === null) { + return undefined; + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + if (!Array.isArray(value)) { + throw new RestError( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest( + response: PathUncheckedResponse, + expectedStatuses: string[], +): void { + if (!expectedStatuses.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response, + ); + } +} diff --git a/sdk/keyvault/keyvault-admin/src/generated/static-helpers/pollingHelpers.ts b/sdk/keyvault/keyvault-admin/src/generated/static-helpers/pollingHelpers.ts new file mode 100644 index 000000000000..7d6a9d3ac8ca --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/generated/static-helpers/pollingHelpers.ts @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + PollerLike, + OperationState, + ResourceLocationConfig, + RunningOperation, + createHttpPoller, + OperationResponse, +} from "@azure/core-lro"; + +import { + Client, + PathUncheckedResponse, + createRestError, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; + +export interface GetLongRunningPollerOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** + * The potential location of the result of the LRO if specified by the LRO extension in the swagger. + */ + resourceLocationConfig?: ResourceLocationConfig; + /** + * The original url of the LRO + * Should not be null when restoreFrom is set + */ + initialRequestUrl?: string; + /** + * A serialized poller which can be used to resume an existing paused Long-Running-Operation. + */ + restoreFrom?: string; + /** + * The function to get the initial response + */ + getInitialResponse?: () => PromiseLike; + /** + * Skip final GET request to get the final result + */ + skipFinalGet?: boolean; +} +export function getLongRunningPoller< + TResponse extends PathUncheckedResponse, + TResult = void, +>( + client: Client, + processResponseBody: (result: TResponse) => Promise, + expectedStatuses: string[], + options: GetLongRunningPollerOptions, +): PollerLike, TResult> { + const { restoreFrom, getInitialResponse } = options; + if (!restoreFrom && !getInitialResponse) { + throw new Error( + "Either restoreFrom or getInitialResponse must be specified", + ); + } + let initialResponse: TResponse | undefined = undefined; + const pollAbortController = new AbortController(); + const poller: RunningOperation = { + sendInitialRequest: async () => { + if (!getInitialResponse) { + throw new Error( + "getInitialResponse is required when initializing a new poller", + ); + } + initialResponse = await getInitialResponse(); + return getLroResponse(initialResponse, expectedStatuses); + }, + sendPollRequest: async ( + path: string, + pollOptions?: { + abortSignal?: AbortSignalLike; + }, + ) => { + // The poll request would both listen to the user provided abort signal and the poller's own abort signal + function abortListener(): void { + pollAbortController.abort(); + } + const abortSignal = pollAbortController.signal; + if (options.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (pollOptions?.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (!abortSignal.aborted) { + options.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + pollOptions?.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + let response; + try { + response = await client.pathUnchecked(path).get({ abortSignal }); + } finally { + options.abortSignal?.removeEventListener("abort", abortListener); + pollOptions?.abortSignal?.removeEventListener("abort", abortListener); + } + + return getLroResponse(response as TResponse, expectedStatuses); + }, + }; + return createHttpPoller(poller, { + intervalInMs: options?.updateIntervalInMs, + resourceLocationConfig: options?.resourceLocationConfig, + restoreFrom: options?.restoreFrom, + processResult: (result: unknown) => { + return processResponseBody(result as TResponse); + }, + skipFinalGet: options?.skipFinalGet + }); +} +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @param deserializeFn - deserialize function to convert Rest response to modular output + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResponse, + expectedStatuses: string[], +): OperationResponse { + if (!expectedStatuses.includes(response.status)) { + throw createRestError(response); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} 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/models.ts b/sdk/keyvault/keyvault-admin/src/lro/models.ts new file mode 100644 index 000000000000..c93fa18b4f70 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/lro/models.ts @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// TODO: merge with backupClientModels + +import type { KeyVaultClient } from "../generated/keyVaultClient.js"; +import type { OperationOptions } from "@azure-rest/core-client"; +import type { + KeyVaultBackupResult, + KeyVaultRestoreResult, + KeyVaultSelectiveKeyRestoreResult, +} from "../backupClientModels.js"; +import { OperationStatus } from "../generated/index.js"; + +/** + * 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 { + /** + * Identifier for the full restore operation. + */ + jobId?: string; + /** + * Status of the restore operation. + */ + status: OperationStatus; + /** + * Will exist if the operation encountered any error. + */ + error?: Error; + /** + * Will exist if the operation produced a result of the expected type. + */ + result?: TResult; + /** + * 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; + /** + * isStarted + */ + isStarted?: boolean; + /** + * isCompleted + */ + isCompleted?: boolean; +} + +export interface KeyVaultBackupPollerOptions extends KeyVaultAdminPollerOptions { + blobStorageUri: string; + sasToken?: string; +} + +/** + * 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; +} + +/** + * 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; +} + +export interface KeyVaultRestorePollerOptions extends KeyVaultAdminPollerOptions { + folderUri: string; + sasToken?: string; + folderName: string; +} + +/** + * 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; +} + +export interface KeyVaultSelectiveKeyRestorePollerOptions extends KeyVaultAdminPollerOptions { + keyName: string; + folderUri: string; + sasToken?: string; + folderName: string; +} 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/lro/shim.ts b/sdk/keyvault/keyvault-admin/src/lro/shim.ts new file mode 100644 index 000000000000..8683ba6b711a --- /dev/null +++ b/sdk/keyvault/keyvault-admin/src/lro/shim.ts @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { AbortSignalLike } from "@azure/abort-controller"; +import type { + CancelOnProgress, + OperationState, + PollerLike as CorePollerLike, +} from "@azure/core-lro"; +import type { KeyVaultAdminPollOperationState } from "./models.js"; + +/** + * A simple poller that can be used to poll a long running operation. + */ +export interface PollerLike, TResult> { + /** + * Returns true if the poller has finished polling. + */ + isDone(): boolean; + /** + * Returns true if the poller is stopped. + */ + isStopped(): boolean; + /** + * Returns the state of the operation. + */ + getOperationState(): TState; + /** + * Returns the result value of the operation, + * regardless of the state of the poller. + * It can return undefined or an incomplete form of the final TResult value + * depending on the implementation. + */ + getResult(): TResult | undefined; + /** + * Returns a promise that will resolve once a single polling request finishes. + * It does this by calling the update method of the Poller's operation. + */ + poll(options?: { abortSignal?: AbortSignalLike }): Promise; + /** + * Returns a promise that will resolve once the underlying operation is completed. + */ + pollUntilDone(pollOptions?: { abortSignal?: AbortSignalLike }): Promise; + /** + * Invokes the provided callback after each polling is completed, + * sending the current state of the poller's operation. + * + * It returns a method that can be used to stop receiving updates on the given callback function. + */ + onProgress(callback: (state: TState) => void): CancelOnProgress; + + /** + * Returns a string representation of the poller's operation. Similar to serialize but returns a string. + */ + toString(): string; + + /** + * Stops the poller from continuing to poll. Please note this will only stop the client-side polling + */ + stopPolling(): void; +} + +export async function wrapPoller, TResult>( + httpPoller: CorePollerLike, +): Promise> { + const abortController = new AbortController(); + const simplePoller: PollerLike = { + isDone() { + return httpPoller.isDone; + }, + isStopped() { + return abortController.signal.aborted; + }, + getOperationState() { + if (!httpPoller.operationState) { + throw new Error( + "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", + ); + } + const mergedState = { + ...httpPoller.operationState, + ...httpPoller.operationState.result, + isStarted: httpPoller.operationState.status !== "notStarted", // Shim for isStarted + isCompleted: + httpPoller.operationState.status === "succeeded" || + httpPoller.operationState.status === "failed" || + httpPoller.operationState.status === "canceled", + }; + if (mergedState.error === null) { + mergedState.error = undefined; + } + return mergedState; + }, + getResult() { + return httpPoller.result; + }, + toString() { + if (!httpPoller.operationState) { + throw new Error( + "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", + ); + } + return JSON.stringify({ + state: httpPoller.operationState, + }); + }, + stopPolling() { + abortController.abort(); + }, + onProgress: httpPoller.onProgress, + async poll(options) { + httpPoller.poll(options); + }, + pollUntilDone(pollOptions?: { abortSignal?: AbortSignalLike }) { + function abortListener(): void { + abortController.abort(); + } + const inputAbortSignal = pollOptions?.abortSignal; + const abortSignal = abortController.signal; + if (inputAbortSignal?.aborted) { + abortController.abort(); + } else if (!abortSignal.aborted) { + inputAbortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + return httpPoller.pollUntilDone({ abortSignal: abortController.signal }); + }, + }; + await httpPoller.submitted(); + // clean up the final GET path so that we could skip final GET + // Workaround for https://github.com/Azure/azure-sdk-for-js/issues/32142 + // if ((httpPoller.operationState as any)?.config?.resourceLocation) { + // (httpPoller.operationState as any).config.resourceLocation = undefined; + // } + return simplePoller; +} diff --git a/sdk/keyvault/keyvault-admin/src/mappings.ts b/sdk/keyvault/keyvault-admin/src/mappings.ts index 57ea87ac32ca..50ee846a87d0 100644 --- a/sdk/keyvault/keyvault-admin/src/mappings.ts +++ b/sdk/keyvault/keyvault-admin/src/mappings.ts @@ -6,6 +6,7 @@ import type { KeyVaultRoleDefinition, KeyVaultRoleScope, } from "./accessControlModels.js"; +import { PagedAsyncIterableIterator } from "./generated/index.js"; import type { RoleAssignment, RoleDefinition } from "./generated/models/index.js"; export const mappings = { @@ -27,8 +28,9 @@ export const mappings = { }, roleDefinition: { generatedToPublic(roleDefinition: RoleDefinition): KeyVaultRoleDefinition { - const { id, name, type, roleName, description, roleType, permissions, assignableScopes } = - roleDefinition; + const { id, name, type } = roleDefinition; + const { roleName, description, roleType, permissions, assignableScopes } = + roleDefinition.properties || {}; return { id: id!, name: name!, @@ -56,3 +58,29 @@ export const mappings = { }; }, }; + +// TODO: Add support for maxPageSize, etc +export function mapPagedAsyncIterable( + iter: PagedAsyncIterableIterator, + mapper: (x: T) => U, +): PagedAsyncIterableIterator { + return { + async next() { + const result = await iter.next(); + + return { + ...result, + value: result.value && mapper(result.value), + }; + }, + [Symbol.asyncIterator]() { + return this; + }, + async *byPage(settings) { + const iteratorByPage = iter.byPage(settings); + for await (const page of iteratorByPage) { + yield page.map(mapper); + } + }, + }; +} diff --git a/sdk/keyvault/keyvault-admin/src/settingsClient.ts b/sdk/keyvault/keyvault-admin/src/settingsClient.ts index 0030c9ac089b..2dbda6e68499 100644 --- a/sdk/keyvault/keyvault-admin/src/settingsClient.ts +++ b/sdk/keyvault/keyvault-admin/src/settingsClient.ts @@ -2,11 +2,8 @@ // 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 { KeyVaultClient } from "./generated/index.js"; import type { UpdateSettingOptions, GetSettingOptions, @@ -16,6 +13,7 @@ import type { SettingsClientOptions, BooleanKeyVaultSetting, } from "./settingsClientModels.js"; +import { createKeyVaultClient } from "./createKeyVaultClient.js"; function makeSetting(generatedSetting: GeneratedSetting): KeyVaultSetting { if (generatedSetting.type === "boolean") { @@ -76,27 +74,7 @@ export class KeyVaultSettingsClient { 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"], - }); + this.client = createKeyVaultClient(vaultUrl, credential, options); } /** @@ -110,7 +88,7 @@ export class KeyVaultSettingsClient { options: UpdateSettingOptions = {}, ): Promise { return makeSetting( - await this.client.updateSetting(this.vaultUrl, setting.name, String(setting.value), options), + await this.client.updateSetting(setting.name, { value: String(setting.value) }, options), ); } @@ -121,7 +99,7 @@ export class KeyVaultSettingsClient { * @param options - the optional parameters. */ async getSetting(settingName: string, options: GetSettingOptions = {}): Promise { - return makeSetting(await this.client.getSetting(this.vaultUrl, settingName, options)); + return makeSetting(await this.client.getSetting(settingName, options)); } /** @@ -130,7 +108,7 @@ export class KeyVaultSettingsClient { * @param options - the optional parameters. */ async getSettings(options: ListSettingsOptions = {}): Promise { - const { settings } = await this.client.getSettings(this.vaultUrl, options); + const { settings } = await this.client.getSettings(options); return { settings: settings?.map(makeSetting) ?? [] }; } } diff --git a/sdk/keyvault/keyvault-admin/src/settingsClientModels.ts b/sdk/keyvault/keyvault-admin/src/settingsClientModels.ts index a11123eeec3c..186a9b0c9d30 100644 --- a/sdk/keyvault/keyvault-admin/src/settingsClientModels.ts +++ b/sdk/keyvault/keyvault-admin/src/settingsClientModels.ts @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { CommonClientOptions, OperationOptions } from "@azure/core-client"; +import type { ClientOptions, OperationOptions } from "@azure-rest/core-client"; import type { SUPPORTED_API_VERSIONS } from "./constants.js"; /** * The optional parameters accepted by the KeyVaultSettingsClient. */ -export interface SettingsClientOptions extends CommonClientOptions { +export interface SettingsClientOptions extends ClientOptions { /** * The accepted versions of the Key Vault's service API. */ diff --git a/sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts b/sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts index 9faccfcdb671..69735dd1b2ca 100644 --- a/sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts +++ b/sdk/keyvault/keyvault-admin/test/internal/serviceVersionParameter.spec.ts @@ -31,6 +31,7 @@ describe("The keyvault-admin clients should set the serviceVersion", () => { id: `${baseUrl}${path}`, startTime: new Date(), attributes: {}, + value: [], }), }; }, diff --git a/sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts b/sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts index 54adf838d76f..4c91a3e07dd1 100644 --- a/sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts +++ b/sdk/keyvault/keyvault-admin/test/internal/userAgent.spec.ts @@ -2,7 +2,6 @@ // Licensed under the MIT License. import { KeyVaultAccessControlClient, SDK_VERSION } from "../../src/index.js"; -import type { TokenCredential } from "@azure/core-auth"; import { describe, it, expect } from "vitest"; describe("Key Vault Admin's user agent", function () { @@ -10,7 +9,7 @@ describe("Key Vault Admin's user agent", function () { let userAgent: string | undefined; const client = new KeyVaultAccessControlClient( "https://myvault.vault.azure.net", - {} as TokenCredential, + { getToken: () => Promise.resolve({ token: "my-fake-token", expiresOnTimestamp: 0 }) }, { httpClient: { sendRequest: async (request) => { diff --git a/sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts b/sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts index 2e7e450845a1..0da76962ce10 100644 --- a/sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts +++ b/sdk/keyvault/keyvault-admin/test/public/accessControlClient.spec.ts @@ -287,8 +287,6 @@ describe("KeyVaultAccessControlClient", () => { 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([ @@ -296,8 +294,6 @@ describe("KeyVaultAccessControlClient", () => { "KeyVaultAccessControlClient.getRoleDefinition", "KeyVaultAccessControlClient.createRoleAssignment", "KeyVaultAccessControlClient.getRoleAssignment", - "KeyVaultAccessControlClient.listRoleAssignmentsPage", - "KeyVaultAccessControlClient.listRoleDefinitionsPage", "KeyVaultAccessControlClient.deleteRoleAssignment", "KeyVaultAccessControlClient.deleteRoleDefinition", ]); diff --git a/sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts b/sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts index c3ae42b2c4e9..2221799da796 100644 --- a/sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts +++ b/sdk/keyvault/keyvault-admin/test/public/backupClient.spec.ts @@ -133,6 +133,12 @@ describe("KeyVaultBackupClient", () => { const operationState = selectiveKeyRestorePoller.getOperationState(); expect(operationState.isCompleted).toEqual(true); + // 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); + } await keyClient.getKey(keyName); }); diff --git a/sdk/keyvault/keyvault-admin/tsp-location.yaml b/sdk/keyvault/keyvault-admin/tsp-location.yaml new file mode 100644 index 000000000000..a8369ec8eac4 --- /dev/null +++ b/sdk/keyvault/keyvault-admin/tsp-location.yaml @@ -0,0 +1,8 @@ +directory: specification/keyvault/Security.KeyVault.Administration/ +commit: cd4c57343d3f46bca0bec0c86e706132750ff8a5 +repo: azure/azure-rest-api-specs +additionalDirectories: +- specification/keyvault/Security.KeyVault.BackupRestore/ +- specification/keyvault/Security.KeyVault.Common/ +- specification/keyvault/Security.KeyVault.RBAC/ +- specification/keyvault/Security.KeyVault.Settings/