Skip to content
This repository has been archived by the owner on Jul 19, 2024. It is now read-only.

Commit

Permalink
Merge pull request #2 from JosueJoshua/dev-test-josue-579-01
Browse files Browse the repository at this point in the history
Update azure Key Vault Keys, Secrets, Certificates SDK to T2
  • Loading branch information
jongio authored Oct 19, 2020
2 parents 66ff8f1 + 176abb4 commit 294f4cf
Show file tree
Hide file tree
Showing 6 changed files with 631 additions and 201 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ This sample repo includes sample code demonstrating the soft delete, recovery an
1. If you don't have it, install [node.js](https://nodejs.org)
2. Set the following environment variables using the information from your service principal.
```
export AZURE_RESOURCE_GROUP={your resource group name}
export AZURE_SUBSCRIPTION_ID={your subscription id}
export AZURE_CLIENT_ID={your client id}
export AZURE_CLIENT_SECRET={your client secret}
Expand Down
67 changes: 36 additions & 31 deletions backup_restore_sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class BackupRestoreSample extends KeyVaultSampleBase {
// Create two key vaults for sample purposes
self._firstVault = await self._createVault();
self._secondVault = await self._createVault();

// Run our individual backup and restore samples now that setup is complete
await self.backupRestoreKey();
await self.backupRestoreSecret();
Expand All @@ -31,25 +31,27 @@ class BackupRestoreSample extends KeyVaultSampleBase {
console.log(' Key backup and restore sample. ');
console.log('************************************');


var keyName = self._getName('key');
var key = await self.KeyVaultClient.createKey(self._firstVault.properties.vaultUri, keyName, 'RSA');
const sourceVaultClient = self._getKeyClient(self._firstVault.properties.vaultUri);
var key = await sourceVaultClient.createKey(keyName, 'RSA');

console.log('Created key ' + keyName);
console.log('Backing up key.');
var keyBackup = await self.KeyVaultClient.backupKey(self._firstVault.properties.vaultUri, keyName);
var keyBackup = await sourceVaultClient.backupKey(keyName);

console.log('Backed up key ' + keyName);

console.log('Restoring');
var restored = await self.KeyVaultClient.restoreKey(self._secondVault.properties.vaultUri, keyBackup.value);
const targetVaultClient = self._getKeyClient(self._secondVault.properties.vaultUri);
var restored = await targetVaultClient.restoreKeyBackup(keyBackup)

console.log('Restored key ' + keyName);
var keys = await self.KeyVaultClient.getKeys(self._secondVault.properties.vaultUri);
var keys = await targetVaultClient.listPropertiesOfKeys();

console.log('Vault ' + self._secondVault.name + ' keys:');
for(var i = 0; i < keys.length; i++) {
console.log(' kid: ' + keys[i].kid);
for await (const keyProperties of keys) {
console.log(' kid: ' + keyProperties.kid);
}
}

Expand All @@ -61,24 +63,26 @@ class BackupRestoreSample extends KeyVaultSampleBase {
console.log('************************************');

var secretName = self._getName('secret');
var secret = await self.KeyVaultClient.setSecret(self._firstVault.properties.vaultUri, secretName, 'AValue');
const sourceVaultClient = self._getSecretClient(self._firstVault.properties.vaultUri);
var secret = await sourceVaultClient.setSecret(secretName, 'AValue');

console.log('Created secret: ' + secretName);
console.log(secret);

console.log('Backing up secret');
var secretBackup = await self.KeyVaultClient.backupSecret(self._firstVault.properties.vaultUri, secretName);
var secretBackup = await sourceVaultClient.backupSecret(secretName);

console.log('Backed up secret ' + secretName);
console.log('Restoring.');
var restored = await self.KeyVaultClient.restoreSecret(self._secondVault.properties.vaultUri, secretBackup.value);
const targetVaultClient = self._getSecretClient(self._secondVault.properties.vaultUri);
var restored = await targetVaultClient.restoreSecretBackup(secretBackup);

console.log('Restored secret ' + secretName);
var secrets = await self.KeyVaultClient.getSecrets(self._secondVault.properties.vaultUri);
var secrets = await targetVaultClient.listPropertiesOfSecrets();

console.log('Vault ' + self._secondVault.name + ' secrets:');
for(var i = 0; i < secrets.length; i++) {
console.log(' Secret ID: ' + secrets[i].id);
for await (const secretProperties of secrets) {
console.log(' Secret ID: ' + secretProperties.id);
}
}

Expand All @@ -89,15 +93,13 @@ class BackupRestoreSample extends KeyVaultSampleBase {
'keyProperties': {
'keySize': 4096,
'reuseKey': false
},
'issuerParameters': {
'name': 'Self'
},
'x509CertificateProperties': {
'subject': 'CN=www.contoso.com',
'validityInMonths': 12
}
},
'issuerName': 'Self',
'subject': 'CN=www.contoso.com',
'x509CertificateProperties': {
'validityInMonths': 12
},
'certificateAttributes': {
'enabled': true
}
Expand All @@ -111,33 +113,36 @@ class BackupRestoreSample extends KeyVaultSampleBase {


var certificateName = self._getName('certificate');
const sourceVaultClient = self._getCertificateClient(self._firstVault.properties.vaultUri);
console.log('Creating certificate: ' + certificateName);
var certificate = await self.KeyVaultClient.createCertificate(self._firstVault.properties.vaultUri, certificateName, certPolicyOptions);
var certificate = await sourceVaultClient.beginCreateCertificate(certificateName, certPolicyOptions);
await certificate.pollUntilDone();
console.log('Created certificate ' + certificateName);

var certOp = await self.KeyVaultClient.getCertificateOperation(self._firstVault.properties.vaultUri, certificateName, '');
var certOp = await sourceVaultClient.getCertificateOperation(certificateName);

// wait for cert to actually be created
while( certOp.status == 'inProgress' ) {
certOp = await self.KeyVaultClient.getCertificateOperation(self._firstVault.properties.vaultUri, certificateName, '');
certOp = await sourceVaultClient.getCertificateOperation(certificateName);
await self._sleep(1000);
}

console.log('Backing up certificate.');
var certificateBackup = await self.KeyVaultClient.backupCertificate(self._firstVault.properties.vaultUri, certificateName);
var certificateBackup = await sourceVaultClient.backupCertificate(certificateName);

console.log('Backed up certificate ' + certificateName);

console.log('Restoring.');
var restored = await self.KeyVaultClient.restoreCertificate(self._secondVault.properties.vaultUri, certificateBackup.value);
const targetVaultClient = self._getCertificateClient(self._secondVault.properties.vaultUri);
var restored = await targetVaultClient.restoreCertificateBackup(certificateBackup);
console.log(restored);

console.log('Restored certificate ' + certificateName);
var certificates = await self.KeyVaultClient.getCertificates(self._secondVault.properties.vaultUri);
var certificates = await targetVaultClient.listPropertiesOfCertificates();

console.log('Vault ' + self._secondVault.name + ' certificates:');
for(var i = 0; i < certificates.length; i++) {
console.log(' ID: ' + certificates[i].id);
for await (const certificateProperties of certificates) {
console.log(' ID: ' + certificateProperties.id);
}
}
}
Expand Down
59 changes: 28 additions & 31 deletions key_vault_sample_base.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@
// --------------------------------------------------------------------------

'use strict;'

const dotenv = require("dotenv");
dotenv.config();
const util = require('util');
const msRestAzure = require('ms-rest-azure');
const ResourceManagementClient = require('azure-arm-resource').ResourceManagementClient;
const KeyVaultManagementClient = require('azure-arm-keyvault');
const KeyVault = require('azure-keyvault');
const { DefaultAzureCredential } = require('@azure/identity');
const { KeyClient } = require('@azure/keyvault-keys');
const { SecretClient } = require('@azure/keyvault-secrets');
const { CertificateClient } = require('@azure/keyvault-certificates');


const AuthenticationContext = require('adal-node').AuthenticationContext;

// Validate env variables
Expand All @@ -35,6 +41,7 @@ class ServicePrincipalAuthenticator {
this._tenantId = tenantId;
this._clientId = clientId;
this._clientSecret = clientSecret;
this._credentials = null;
}

/**
Expand All @@ -43,33 +50,12 @@ class ServicePrincipalAuthenticator {
* @param {object} challenge Authentication parameters provided by Key Vault.
* @param {function} callback Callback function on completion.
*/
getKeyVaultCredentials() {
var credentials = new KeyVault.KeyVaultCredentials( (challenge, callback) => {
var self = this;
if (!self._authContext) {
self._authContext = new AuthenticationContext(challenge.authorization);
}

// Use the context to acquire an authentication token.
self._authContext.acquireTokenWithClientCredentials(
challenge.resource,
self._clientId,
self._clientSecret,
(err, tokenResponse) => {
if (err) {
callback(err);
return;
}

// Calculate the value to be set in the request's Authorization header and resume the call.
var authorizationValue = tokenResponse.tokenType + ' ' + tokenResponse.accessToken;

callback(null, authorizationValue);
}
);
});

return credentials;
getKeyVaultCredentials(){
var self = this;
if(!self._credentials){
self._credentials = new DefaultAzureCredential();
}
return self._credentials;
}
}

Expand Down Expand Up @@ -136,12 +122,23 @@ class KeyVaultSampleBase {
self.KeyVaultManagementClient = new KeyVaultManagementClient(credentials, this._config.subscriptionId);

// Service principal auth.
var kvCredentials = self._servicePrincipalAuthenticator.getKeyVaultCredentials();
self.KeyVaultClient = new KeyVault.KeyVaultClient(kvCredentials);
self._servicePrincipalAuthenticator.getKeyVaultCredentials();
}
);
}

_getKeyClient(vaultUrl){
return new KeyClient(vaultUrl, this._servicePrincipalAuthenticator._credentials);
}

_getSecretClient(vaultUrl){
return new SecretClient(vaultUrl, this._servicePrincipalAuthenticator._credentials);
}

_getCertificateClient(vaultUrl){
return new CertificateClient(vaultUrl, this._servicePrincipalAuthenticator._credentials);
}

_prettyPrintJson(obj) {
return JSON.stringify(obj, null, 2);
}
Expand Down
Loading

0 comments on commit 294f4cf

Please sign in to comment.