Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Key Vault Admin] Convenience layer - KeyVaultBackupClient #11009

Merged
merged 13 commits into from
Sep 9, 2020
Merged
15 changes: 10 additions & 5 deletions sdk/keyvault/keyvault-admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"url": "https://github.com/Azure/azure-sdk-for-js/issues"
},
"main": "./dist/index.js",
"module": "dist-esm/src/index.js",
"module": "dist-esm/keyvault-admin/src/index.js",
"types": "./types/keyvault-admin.d.ts",
"engine": {
"node": ">=8.0.0"
Expand All @@ -29,10 +29,11 @@
"node": ">=8.0.0"
},
"files": [
"types/",
"types/keyvault-admin.d.ts",
"dist/",
"dist-browser/",
"dist-esm/src",
"dist-esm/keyvault-admin/src",
"dist-esm/keyvault-common/src",
"README.md",
"LICENSE"
],
Expand All @@ -52,13 +53,13 @@
"execute:js-samples": "echo skipped",
"execute:ts-samples": "echo skipped",
"execute:samples": "npm run build:samples && npm run execute:js-samples && npm run execute:ts-samples",
"extract-api": "echo skipped",
"extract-api": "tsc -p . && api-extractor run --local",
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"integration-test:browser": "echo skipped",
"integration-test:node": "echo skipped",
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
"lint:fix": "eslint package.json src --ext .ts --fix --fix-type [problem,suggestion]",
"lint": "eslint package.json src --ext .ts -f html -o keyvault-admin-lintReport.html",
"lint": "eslint package.json api-extractor.json src --ext .ts",
"lint:terminal": "eslint package.json src test --ext .ts",
"pack": "npm pack 2>&1",
"prebuild": "npm run clean",
Expand All @@ -72,14 +73,18 @@
},
"sideEffects": false,
"dependencies": {
"@azure/abort-controller": "^1.0.0",
"@azure/core-http": "^1.1.6",
"@azure/core-lro": "^1.0.2",
"@azure/core-paging": "^1.1.1",
"@azure/core-tracing": "1.0.0-preview.9",
"@azure/logger": "^1.0.0",
"@opentelemetry/api": "^0.10.2",
"tslib": "^2.0.0"
},
"devDependencies": {
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@microsoft/api-extractor": "7.7.11",
"@rollup/plugin-commonjs": "11.0.2",
"@rollup/plugin-json": "^4.0.0",
"@rollup/plugin-multi-entry": "^3.0.0",
Expand Down
276 changes: 276 additions & 0 deletions sdk/keyvault/keyvault-admin/src/backupClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import {
createPipelineFromOptions,
isTokenCredential,
signingPolicy,
TokenCredential
} from "@azure/core-http";
import { PollerLike, PollOperationState } from "@azure/core-lro";

import { challengeBasedAuthenticationPolicy } from "../../keyvault-common";
import { KeyVaultClient } from "./generated/keyVaultClient";
import { BackupClientOptions, BeginBackupOptions, BeginRestoreOptions } from "./backupClientModels";
import { LATEST_API_VERSION, SDK_VERSION } from "./constants";
import { logger } from "./log";
import { BackupPoller } from "./lro/backup/poller";
import { RestorePoller } from "./lro/restore/poller";
import { SelectiveRestorePoller } from "./lro/selectiveRestore/poller";

/**
* The KeyVaultBackupClient provides methods to generate backups
* and restore backups of any given Azure Key Vault instance.
* This client supports generating full backups, selective restores of specific keys
* and full restores of Key Vault instances.
*/
export class KeyVaultBackupClient {
/**
* The base URL to the vault
*/
public readonly vaultUrl: string;

/**
* @internal
* @ignore
* A reference to the auto-generated Key Vault HTTP client.
*/
private readonly client: KeyVaultClient;

/**
* Creates an instance of the KeyVaultBackupClient.
*
* Example usage:
* ```ts
* import { KeyVaultBackupClient } from "@azure/keyvault-admin";
* import { DefaultAzureCredential } from "@azure/identity";
*
* let vaultUrl = `https://<MY KEY VAULT HERE>.vault.azure.net`;
* let credentials = new DefaultAzureCredential();
*
* let client = new KeyVaultBackupClient(vaultUrl, credentials);
* ```
* @param vaultUrl the URL of the Key Vault. It should have this shape: https://${your-key-vault-name}.vault.azure.net
* @param credential An object that implements the `TokenCredential` interface used to authenticate requests to the service. Use the @azure/identity package to create a credential that suits your needs.
* @param [pipelineOptions] Pipeline options used to configure Key Vault API requests. Omit this parameter to use the default pipeline configuration.
*/
constructor(
vaultUrl: string,
credential: TokenCredential,
pipelineOptions: BackupClientOptions = {}
) {
this.vaultUrl = vaultUrl;

const libInfo = `azsdk-js-keyvault-admin/${SDK_VERSION}`;

const userAgentOptions = pipelineOptions.userAgentOptions;

pipelineOptions.userAgentOptions = {
...pipelineOptions.userAgentOptions,
userAgentPrefix:
userAgentOptions && userAgentOptions.userAgentPrefix
? `${userAgentOptions.userAgentPrefix} ${libInfo}`
: libInfo
};

const authPolicy = isTokenCredential(credential)
? challengeBasedAuthenticationPolicy(credential)
: signingPolicy(credential);

const internalPipelineOptions = {
...pipelineOptions,
...{
loggingOptions: {
logger: logger.info,
logPolicyOptions: {
allowedHeaderNames: [
"x-ms-keyvault-region",
"x-ms-keyvault-network-info",
"x-ms-keyvault-service-version"
]
}
}
}
};

const pipeline = createPipelineFromOptions(internalPipelineOptions, authPolicy);
this.client = new KeyVaultClient({
apiVersion: pipelineOptions.serviceVersion || LATEST_API_VERSION,
...pipeline
});
}

/**
* Starts generating a backup of an Azure Key Vault on the specified Storage Blob account.
*
* This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault backup is generated.
*
* Example usage:
* ```ts
* const client = new KeyVaultBackupClient(url, credentials);
*
* const blobStorageUri = "<blob-storage-uri>"; // <Blob storage URL>/<folder name>
* const sasToken = "<sas-token>";
* const poller = await client.beginBackup(blobStorageUri, sasToken);
*
* // Serializing the poller
* const serialized = poller.toString();
* // A new poller can be created with:
* // await client.beginBackup(blobStorageUri, sasToken, { resumeFrom: serialized });
*
* // Waiting until it's done
* const backupUri = await poller.pollUntilDone();
* console.log(backupUri);
* ```
* @summary Starts a full backup operation.
* @param blobStorageUri The URL of the blob storage resource, including the path to the container where the backup will end up being stored.
* @param sasToken The SAS token.
* @param [options] The optional parameters.
*/
public async beginBackup(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

python has it as begin_full_backup

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.NET guidelines specify start* but I don't see any specific guidance around naming for the other langs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In JS we favor "begin". Assuming that this prefix is fine, what I'm most concerned is of the full part.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a strong opinion here, but I opted for plain backup because there is no other backup operation to contrast with.

blobStorageUri: string,
sasToken: string,
options: BeginBackupOptions = {}
): Promise<PollerLike<PollOperationState<string>, string>> {
if (!(blobStorageUri && sasToken)) {
throw new Error(
"beginBackup requires non-empty strings for the parameters: blobStorageUri and sasToken."
);
}

const poller = new BackupPoller({
blobStorageUri,
sasToken,
client: this.client,
vaultUrl: this.vaultUrl,
intervalInMs: options.intervalInMs,
resumeFrom: options.resumeFrom,
requestOptions: options
});

// This will initialize the poller's operation (the generation of the backup).
await poller.poll();

return poller;
}

/**
* Starts restoring all key materials using the SAS token pointing to a previously stored Azure Blob storage
* backup folder.
*
* This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault restore operation is complete.
*
* Example usage:
* ```ts
* const client = new KeyVaultBackupClient(url, credentials);
*
* const blobStorageUri = "<blob-storage-uri>"; // <Blob storage URL>/<folder name>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case the folder name is a separate argument.

Suggested change
* const blobStorageUri = "<blob-storage-uri>"; // <Blob storage URL>/<folder name>
* const blobStorageUri = "<blob-storage-uri>";

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@christothes I thought the same, but my tests pass with the same parameters I'm using in the others, which satisfy: <Blob storage URL>/<folder name>. Do you have different parameters for these tests?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, you are correct, sorry!

* const sasToken = "<sas-token>";
* const folderName = "<folder-name>";
* const poller = await client.beginRestore(blobStorageUri, sasToken, folderName);
*
* // Serializing the poller
* const serialized = poller.toString();
* // A new poller can be created with:
* // await client.beginRestore(blobStorageUri, sasToken, folderName, { resumeFrom: serialized });
*
* // Waiting until it's done
* const backupUri = await poller.pollUntilDone();
* console.log(backupUri);
* ```
* @summary Starts a full restore operation.
* @param blobStorageUri The URL of the blob storage resource where the previous successful full backup was stored.
* @param sasToken The SAS token.
* @param folderName The folder name of the blob where the previous successful full backup was stored.
* @param [options] The optional parameters.
*/
public async beginRestore(
sadasant marked this conversation as resolved.
Show resolved Hide resolved
blobStorageUri: string,
sasToken: string,
folderName: string,
options: BeginRestoreOptions = {}
): Promise<PollerLike<PollOperationState<undefined>, undefined>> {
if (!(blobStorageUri && sasToken && folderName)) {
throw new Error(
"beginRestore requires non-empty strings for the parameters: blobStorageUri, sasToken and folderName."
);
}

const poller = new RestorePoller({
blobStorageUri,
sasToken,
folderName,
client: this.client,
vaultUrl: this.vaultUrl,
intervalInMs: options.intervalInMs,
resumeFrom: options.resumeFrom,
requestOptions: options
});

// This will initialize the poller's operation (the generation of the backup).
await poller.poll();

return poller;
}

/**
* Starts restoring all key versions of a given key using user supplied SAS token pointing to a previously
* stored Azure Blob storage backup folder.
*
* This function returns a Long Running Operation poller that allows you to wait indefinitely until the Key Vault selective restore is complete.
*
* Example usage:
* ```ts
* const client = new KeyVaultBackupClient(url, credentials);
*
* const keyName = "<key-name>";
* const blobStorageUri = "<blob-storage-uri>";
* const sasToken = "<sas-token>";
* const poller = await client.beginSelectiveRestore(keyName, blobStorageUri, sasToken);
*
* // Serializing the poller
* const serialized = poller.toString();
* // A new poller can be created with:
* // await client.beginSelectiveRestore(keyName, blobStorageUri, sasToken, { resumeFrom: serialized });
*
* // Waiting until it's done
* await poller.pollUntilDone();
* ```
* @summary Creates a new role assignment.
* @param keyName The name of the key that wants to be restored.
* @param blobStorageUri The URL of the blob storage resource, with the folder name of the blob where the previous successful full backup was stored.
sadasant marked this conversation as resolved.
Show resolved Hide resolved
* @param sasToken The SAS token.
* @param folderName The Folder name of the blob where the previous successful full backup was stored.
* @param [options] The optional parameters.
*/
public async beginSelectiveRestore(
keyName: string,
sadasant marked this conversation as resolved.
Show resolved Hide resolved
blobStorageUri: string,
sasToken: string,
folderName: string,
options: BeginBackupOptions = {}
): Promise<PollerLike<PollOperationState<undefined>, undefined>> {
if (!(keyName && blobStorageUri && sasToken && folderName)) {
throw new Error(
"beginSelectiveRestore requires non-empty strings for the parameters: keyName, blobStorageUri, sasToken and folderName."
);
}

const poller = new SelectiveRestorePoller({
keyName,
blobStorageUri,
sasToken,
folderName,
client: this.client,
vaultUrl: this.vaultUrl,
intervalInMs: options.intervalInMs,
resumeFrom: options.resumeFrom,
requestOptions: options
});

// This will initialize the poller's operation (the generation of the backup).
await poller.poll();

return poller;
}
}
48 changes: 48 additions & 0 deletions sdk/keyvault/keyvault-admin/src/backupClientModels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import * as coreHttp from "@azure/core-http";
import { SUPPORTED_API_VERSIONS } from "./constants";

/**
* The optional parameters accepted by the KeyVaultBackupClient
*/
export interface BackupClientOptions extends coreHttp.PipelineOptions {
/**
* The accepted versions of the Key Vault's service API.
*/
serviceVersion?: SUPPORTED_API_VERSIONS;
}

/**
* An interface representing the optional parameters that can be
* passed to {@link beginBackup}
*/
export interface BackupPollerOptions extends coreHttp.OperationOptions {
/**
* Time between each polling
*/
intervalInMs?: number;
/**
* A serialized poller, used to resume an existing operation
*/
resumeFrom?: string;
}

/**
* An interface representing the optional parameters that can be
* passed to {@link beginBackup}
*/
export interface BeginBackupOptions extends BackupPollerOptions {}

/**
* An interface representing the optional parameters that can be
* passed to {@link beginRestore}
*/
export interface BeginRestoreOptions extends BackupPollerOptions {}

/**
* An interface representing the optional parameters that can be
* passed to {@link beginSelectiveRestore}
*/
export interface BeginSelectiveRestoreOptions extends BackupPollerOptions {}
9 changes: 7 additions & 2 deletions sdk/keyvault/keyvault-admin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

export * from "./generated/keyVaultClient";
export * from "./generated/keyVaultClientContext";
export * from "./accessControlClient";
export * from "./accessControlModels";

export * from "./backupClient";
export * from "./backupClientModels";

export * from "./constants";
Loading