From 33d955a5f46117d9099c58277fc2cdc0892db3e6 Mon Sep 17 00:00:00 2001 From: Seth Vargo Date: Tue, 28 Apr 2020 19:19:44 -0400 Subject: [PATCH] feat(samples): add new samples (#324) --- kms/.eslintrc.yml | 3 - kms/addMemberToCryptoKeyPolicy.js | 74 --- kms/addMemberToKeyRingPolicy.js | 72 --- kms/asymmetricDecrypt.js | 68 --- kms/asymmetricEncrypt.js | 76 --- kms/asymmetricSign.js | 67 --- kms/asymmetricVerify.js | 70 --- kms/createCryptoKey.js | 46 -- kms/createCryptoKeyVersion.js | 45 -- kms/createKeyAsymmetricDecrypt.js | 66 ++ kms/createKeyAsymmetricSign.js | 66 ++ kms/createKeyHsm.js | 67 +++ kms/createKeyLabels.js | 70 +++ kms/createKeyRing.js | 58 ++ kms/createKeyRotationSchedule.js | 76 +++ kms/createKeySymmetricEncryptDecrypt.js | 66 ++ kms/createKeyVersion.js | 59 ++ kms/createKeyring.js | 39 -- kms/decrypt.js | 58 -- kms/decryptAsymmetric.js | 76 +++ kms/decryptSymmetric.js | 64 ++ kms/destroyCryptoKeyVersion.js | 47 -- kms/destroyKeyVersion.js | 67 +++ kms/disableCryptoKeyVersion.js | 53 -- kms/disableKeyVersion.js | 73 +++ kms/enableCryptoKeyVersion.js | 53 -- kms/enableKeyVersion.js | 73 +++ kms/encrypt.js | 55 -- kms/encryptAsymmetric.js | 89 +++ kms/encryptSymmetric.js | 64 ++ kms/getCryptoKey.js | 49 -- kms/getCryptoKeyIamPolicy.js | 55 -- kms/getKeyLabels.js | 62 ++ kms/getKeyVersionAttestation.js | 74 +++ kms/getKeyring.js | 40 -- kms/getKeyringIamPolicy.js | 50 -- kms/getPublicKey.js | 64 +- kms/iamAddMember.js | 82 +++ kms/iamGetPolicy.js | 74 +++ kms/iamRemoveMember.js | 89 +++ kms/listCryptoKeyVersions.js | 53 -- kms/listCryptoKeys.js | 49 -- kms/listKeyrings.js | 44 -- kms/package.json | 10 +- kms/quickstart.js | 64 +- kms/removeMemberCryptoKeyPolicy.js | 80 --- kms/removeMemberFromKeyRingPolicy.js | 71 --- kms/resources/plaintext.txt | 4 - kms/restoreCryptoKeyVersion.js | 47 -- kms/restoreKeyVersion.js | 67 +++ kms/setPrimaryCryptoKeyVersion.js | 55 -- kms/signAsymmetric.js | 85 +++ kms/system-test/kms.test.js | 467 --------------- kms/test/kms.test.js | 760 ++++++++++++++++++++++++ kms/updateKeyAddRotation.js | 75 +++ kms/updateKeyRemoveLabels.js | 66 ++ kms/updateKeyRemoveRotation.js | 66 ++ kms/updateKeySetPrimary.js | 62 ++ kms/updateKeyUpdateLabels.js | 68 +++ kms/verifyAsymmetricEc.js | 84 +++ kms/verifyAsymmetricRsa.js | 85 +++ 61 files changed, 2916 insertions(+), 1945 deletions(-) delete mode 100644 kms/.eslintrc.yml delete mode 100644 kms/addMemberToCryptoKeyPolicy.js delete mode 100644 kms/addMemberToKeyRingPolicy.js delete mode 100644 kms/asymmetricDecrypt.js delete mode 100644 kms/asymmetricEncrypt.js delete mode 100644 kms/asymmetricSign.js delete mode 100644 kms/asymmetricVerify.js delete mode 100644 kms/createCryptoKey.js delete mode 100644 kms/createCryptoKeyVersion.js create mode 100644 kms/createKeyAsymmetricDecrypt.js create mode 100644 kms/createKeyAsymmetricSign.js create mode 100644 kms/createKeyHsm.js create mode 100644 kms/createKeyLabels.js create mode 100644 kms/createKeyRing.js create mode 100644 kms/createKeyRotationSchedule.js create mode 100644 kms/createKeySymmetricEncryptDecrypt.js create mode 100644 kms/createKeyVersion.js delete mode 100644 kms/createKeyring.js delete mode 100644 kms/decrypt.js create mode 100644 kms/decryptAsymmetric.js create mode 100644 kms/decryptSymmetric.js delete mode 100644 kms/destroyCryptoKeyVersion.js create mode 100644 kms/destroyKeyVersion.js delete mode 100644 kms/disableCryptoKeyVersion.js create mode 100644 kms/disableKeyVersion.js delete mode 100644 kms/enableCryptoKeyVersion.js create mode 100644 kms/enableKeyVersion.js delete mode 100644 kms/encrypt.js create mode 100644 kms/encryptAsymmetric.js create mode 100644 kms/encryptSymmetric.js delete mode 100644 kms/getCryptoKey.js delete mode 100644 kms/getCryptoKeyIamPolicy.js create mode 100644 kms/getKeyLabels.js create mode 100644 kms/getKeyVersionAttestation.js delete mode 100644 kms/getKeyring.js delete mode 100644 kms/getKeyringIamPolicy.js create mode 100644 kms/iamAddMember.js create mode 100644 kms/iamGetPolicy.js create mode 100644 kms/iamRemoveMember.js delete mode 100644 kms/listCryptoKeyVersions.js delete mode 100644 kms/listCryptoKeys.js delete mode 100644 kms/listKeyrings.js delete mode 100644 kms/removeMemberCryptoKeyPolicy.js delete mode 100644 kms/removeMemberFromKeyRingPolicy.js delete mode 100644 kms/resources/plaintext.txt delete mode 100644 kms/restoreCryptoKeyVersion.js create mode 100644 kms/restoreKeyVersion.js delete mode 100644 kms/setPrimaryCryptoKeyVersion.js create mode 100644 kms/signAsymmetric.js delete mode 100644 kms/system-test/kms.test.js create mode 100644 kms/test/kms.test.js create mode 100644 kms/updateKeyAddRotation.js create mode 100644 kms/updateKeyRemoveLabels.js create mode 100644 kms/updateKeyRemoveRotation.js create mode 100644 kms/updateKeySetPrimary.js create mode 100644 kms/updateKeyUpdateLabels.js create mode 100644 kms/verifyAsymmetricEc.js create mode 100644 kms/verifyAsymmetricRsa.js diff --git a/kms/.eslintrc.yml b/kms/.eslintrc.yml deleted file mode 100644 index 282535f55f..0000000000 --- a/kms/.eslintrc.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- -rules: - no-console: off diff --git a/kms/addMemberToCryptoKeyPolicy.js b/kms/addMemberToCryptoKeyPolicy.js deleted file mode 100644 index 142f954ff0..0000000000 --- a/kms/addMemberToCryptoKeyPolicy.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_add_member_to_cryptokey_policy] -async function addMemberToCryptoKeyPolicy( - projectId = 'your-project-id', // Your GCP Project Id - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key - member = 'user:dev@example.com', // Member to add to the crypto key - role = 'roles/viewer' // Role to give the member -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring - const locationId = 'global'; - - // Get the full path to the crypto key - const resource = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - // Gets the IAM policy of a crypto key - const [result] = await client.getIamPolicy({resource}); - let policy = Object.assign({bindings: []}, result); - const index = policy.bindings.findIndex(binding => binding.role === role); - // Add the role/member combo to the policy - const members = []; - const binding = Object.assign({role, members}, policy.bindings[index]); - if (index === -1) { - policy.bindings.push(binding); - } - if (!binding.members.includes(member)) { - binding.members.push(member); - } - - // Adds the member/role combo to the policy of the crypto key - [policy] = await client.setIamPolicy({resource, policy}); - console.log( - `${member}/${role} combo added to policy for crypto key ${cryptoKeyId}.` - ); - if (policy.bindings) { - policy.bindings.forEach(binding => { - if (binding.members && binding.members.length) { - console.log(`${binding.role}:`); - binding.members.forEach(member => { - console.log(` ${member}`); - }); - } - }); - } else { - console.log(`Policy for crypto key ${cryptoKeyId} is empty.`); - } -} -// [END kms_add_member_to_cryptokey_policy] - -const args = process.argv.slice(2); -addMemberToCryptoKeyPolicy(...args).catch(console.error); diff --git a/kms/addMemberToKeyRingPolicy.js b/kms/addMemberToKeyRingPolicy.js deleted file mode 100644 index 4e32cdec85..0000000000 --- a/kms/addMemberToKeyRingPolicy.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_add_member_to_keyring_policy] -async function addMemberToKeyRingPolicy( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - member = 'user:dev@example.com', // Member to add to the crypto key - role = 'roles/viewer' // Role to give the member -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the keyring - const resource = client.keyRingPath(projectId, locationId, keyRingId); - - // Gets the IAM policy of a key ring - let [policy] = await client.getIamPolicy({resource}); - policy.bindings = policy.bindings || []; - - // find the index of the binding matching the requested role - const index = policy.bindings.findIndex(binding => binding.role === role); - - // Add the role/member combo to the policy - const members = []; - const binding = Object.assign({role}, {members}, policy.bindings[index]); - if (index === -1) { - policy.bindings.push(binding); - } - if (!binding.members.includes(member)) { - binding.members.push(member); - } - - // Adds the member/role combo to the policy of the key ring - [policy] = await client.setIamPolicy({resource, policy}); - console.log( - `${member}/${role} combo added to policy for key ring ${keyRingId}.` - ); - if (policy.bindings) { - policy.bindings.forEach(binding => { - if (binding.members && binding.members.length) { - console.log(`${binding.role}:`); - binding.members.forEach(member => { - console.log(` ${member}`); - }); - } - }); - } else { - console.log(`Policy for key ring ${keyRingId} is empty.`); - } -} -// [END kms_add_member_to_keyring_policy] - -const args = process.argv.slice(2); -addMemberToKeyRingPolicy(...args).catch(console.error); diff --git a/kms/asymmetricDecrypt.js b/kms/asymmetricDecrypt.js deleted file mode 100644 index 192f8d6516..0000000000 --- a/kms/asymmetricDecrypt.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_asymmetric_decrypt] -async function asymmetricDecrypt( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - cryptoKeyVersionId = '1', // Version of the crypto key to use - ciphertextBuffer = '...' // Buffer containing ciphertext to decrypt -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Construct the crypto key version ID - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - cryptoKeyVersionId - ); - - // Decrypt plaintext using Cloud KMS - // - // NOTE: The ciphertext must be properly formatted. In Node < 12, the - // crypto.publicEncrypt() function does not properly consume the OAEP padding - // and thus produces invalid ciphertext. If you are using Node to do public - // key encryption, please use version 12+. - const [result] = await client.asymmetricDecrypt({ - name: name, - ciphertext: ciphertextBuffer, - }); - const plaintext = result.plaintext.toString('utf8'); - - // Example of printing results - console.log(`Decrypted plaintext: ${plaintext}`); - - return plaintext; -} -// [END kms_asymmetric_decrypt] - -const args = process.argv.slice(2); - -// Base64-decode the ciphertext argument. The tests invoke these files via the -// shell, which doesn't support transferring a binary stream. As such, they -// encode the data first, so we need to decode it here before passing it to the -// function. -args[4] = Buffer.from(args[4], 'base64'); - -asymmetricDecrypt(...args).catch(console.error); diff --git a/kms/asymmetricEncrypt.js b/kms/asymmetricEncrypt.js deleted file mode 100644 index cf5dd4100c..0000000000 --- a/kms/asymmetricEncrypt.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_asymmetric_encrypt] -async function asymmetricEncrypt( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - cryptoKeyVersionId = '1', // Version of the crypto key to use - plaintext = 'my data to encrypt' // Plaintext data to encrypt -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Construct the crypto key version ID - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - cryptoKeyVersionId - ); - - // Get public key from Cloud KMS - const [publicKey] = await client.getPublicKey({name: name}); - - // Import and setup crypto - const crypto = require('crypto'); - const plaintextBuffer = Buffer.from(plaintext); - - // Encrypt plaintext locally using the public key. This example uses a key - // that was configured with sha256 hash with OAEP padding. Update these values - // to match the Cloud KMS key. - // - // NOTE: In Node < 12, this function does not properly consume the OAEP - // padding and thus produces invalid ciphertext. If you are using Node to do - // public key encryption, please use version 12+. - const encryptedBuffer = crypto.publicEncrypt( - { - key: publicKey.pem, - oaepHash: 'sha256', - padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, - }, - plaintextBuffer - ); - - // Example of how to display ciphertext. Because the ciphertext is in a binary - // format, you need to encode the output before printing it to a console or - // displaying it on a screen. - const encoded = encryptedBuffer.toString('base64'); - console.log(`Encrypted ciphertext: ${encoded}`); - - // Return the ciphertext buffer - return encryptedBuffer; -} -// [END kms_asymmetric_encrypt] - -const args = process.argv.slice(2); -asymmetricEncrypt(...args).catch(console.error); diff --git a/kms/asymmetricSign.js b/kms/asymmetricSign.js deleted file mode 100644 index 13fd6bcc49..0000000000 --- a/kms/asymmetricSign.js +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_asymmetric_sign] -async function asymmetricSign( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - cryptoKeyVersionId = '1', // Version of the crypto key to use - message = 'my message to sign' // Message data to sign -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Construct the crypto key version ID - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - cryptoKeyVersionId - ); - - // Create a digest of the message. The digest needs to match the digest - // configured for the Cloud KMS key. - const crypto = require('crypto'); - const digest = crypto.createHash('sha384'); - digest.update(message); - - // Sign the message with Cloud KMS - const [result] = await client.asymmetricSign({ - name: name, - digest: { - sha384: digest.digest(), - }, - }); - - // Example of how to display signature. Because the signature is in a binary - // format, you need to encode the output before printing it to a console or - // displaying it on a screen. - const encoded = result.signature.toString('base64'); - console.log(`Signature: ${encoded}`); - - // Return the signature buffer - return result.signature; -} -// [END kms_asymmetric_sign] - -const args = process.argv.slice(2); -asymmetricSign(...args).catch(console.error); diff --git a/kms/asymmetricVerify.js b/kms/asymmetricVerify.js deleted file mode 100644 index 79c02cff1e..0000000000 --- a/kms/asymmetricVerify.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_asymmetric_verify] -async function asymmetricVerify( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - cryptoKeyVersionId = '1', // Version of the crypto key to use - message = 'my message to verify', // Message data to verify - signatureBuffer = '...' // Buffer containing signature to decrypt -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Construct the crypto key version ID - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - cryptoKeyVersionId - ); - - // Get public key from Cloud KMS - const [publicKey] = await client.getPublicKey({name: name}); - - // Create the verifier. The algorithm must match the algorithm of the key. - const crypto = require('crypto'); - const verify = crypto.createVerify('SHA384'); - verify.write(message); - verify.end(); - - // Verify the signature using the public key - const verified = verify.verify(publicKey.pem, signatureBuffer); - - // Example of printing result - console.log(`Signature verified: ${verified}`); - - // Return boolean result - return verified; -} -// [END kms_asymmetric_verify] - -const args = process.argv.slice(2); - -// Base64-decode the signature argument. The tests invoke these files via the -// shell, which doesn't support transferring a binary stream. As such, they -// encode the data first, so we need to decode it here before passing it to the -// function. -args[5] = Buffer.from(args[5], 'base64'); - -asymmetricVerify(...args).catch(console.error); diff --git a/kms/createCryptoKey.js b/kms/createCryptoKey.js deleted file mode 100644 index 18fe7d2791..0000000000 --- a/kms/createCryptoKey.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_create_cryptokey] -async function createCryptoKey( - projectId = 'your-project-id', // Your GCP Project Id - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key' // Name of the crypto key -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the new crypto key's key ring, e.g. "global" - const locationId = 'global'; - - const parent = client.keyRingPath(projectId, locationId, keyRingId); - - // Creates a new key ring - const [cryptoKey] = await client.createCryptoKey({ - parent, - cryptoKeyId, - cryptoKey: { - // This will allow the API access to the key for encryption and decryption - purpose: 'ENCRYPT_DECRYPT', - }, - }); - console.log(`Key ${cryptoKey.name} created.`); -} -// [END kms_create_cryptokey] - -const args = process.argv.slice(2); -createCryptoKey(...args).catch(console.error); diff --git a/kms/createCryptoKeyVersion.js b/kms/createCryptoKeyVersion.js deleted file mode 100644 index 11369f0954..0000000000 --- a/kms/createCryptoKeyVersion.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_create_cryptokey_version] -async function createCryptoKeyVersion( - projectId = 'YOUR_PROJECT_ID', // Your Google Cloud Platform project ID - keyRingId = 'my-key-ring', // Name of the crypto key version's key ring, e.g. "my-key-ring" - cryptoKeyId = 'my-key' // Name of the version's crypto key -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key versions's key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the crypto key - const parent = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - - // Creates a new crypto key version - const [result] = await client.createCryptoKeyVersion({parent}); - console.log(`Crypto key version ${result.name} created.`); -} -// [END kms_create_cryptokey_version] - -const args = process.argv.slice(2); -createCryptoKeyVersion(...args).catch(console.error); diff --git a/kms/createKeyAsymmetricDecrypt.js b/kms/createKeyAsymmetricDecrypt.js new file mode 100644 index 0000000000..6bfaee0522 --- /dev/null +++ b/kms/createKeyAsymmetricDecrypt.js @@ -0,0 +1,66 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + id = 'my-asymmetric-decrypt-key' +) { + // [START kms_create_key_asymmetric_decrypt] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const id = 'my-asymmetric-decrypt-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent key ring name + const keyRingName = client.keyRingPath(projectId, locationId, keyRingId); + + async function createKeyAsymmetricDecrypt() { + const [key] = await client.createCryptoKey({ + parent: keyRingName, + cryptoKeyId: id, + cryptoKey: { + purpose: 'ASYMMETRIC_DECRYPT', + versionTemplate: { + algorithm: 'RSA_DECRYPT_OAEP_2048_SHA256', + }, + }, + }); + + console.log(`Created asymmetric key: ${key.name}`); + return key; + } + + return createKeyAsymmetricDecrypt(); + // [END kms_create_key_asymmetric_decrypt] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeyAsymmetricSign.js b/kms/createKeyAsymmetricSign.js new file mode 100644 index 0000000000..9d0314dc14 --- /dev/null +++ b/kms/createKeyAsymmetricSign.js @@ -0,0 +1,66 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + id = 'my-asymmetric-sign-key' +) { + // [START kms_create_key_asymmetric_sign] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const id = 'my-asymmetric-sign-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent key ring name + const keyRingName = client.keyRingPath(projectId, locationId, keyRingId); + + async function createKeyAsymmetricSign() { + const [key] = await client.createCryptoKey({ + parent: keyRingName, + cryptoKeyId: id, + cryptoKey: { + purpose: 'ASYMMETRIC_SIGN', + versionTemplate: { + algorithm: 'RSA_SIGN_PKCS1_2048_SHA256', + }, + }, + }); + + console.log(`Created asymmetric key: ${key.name}`); + return key; + } + + return createKeyAsymmetricSign(); + // [END kms_create_key_asymmetric_sign] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeyHsm.js b/kms/createKeyHsm.js new file mode 100644 index 0000000000..5ccdc94767 --- /dev/null +++ b/kms/createKeyHsm.js @@ -0,0 +1,67 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + id = 'my-hsm-encryption-key' +) { + // [START kms_create_key_hsm] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const id = 'my-hsm-encryption-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent key ring name + const keyRingName = client.keyRingPath(projectId, locationId, keyRingId); + + async function createKeyHsm() { + const [key] = await client.createCryptoKey({ + parent: keyRingName, + cryptoKeyId: id, + cryptoKey: { + purpose: 'ENCRYPT_DECRYPT', + versionTemplate: { + algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION', + protectionLevel: 'HSM', + }, + }, + }); + + console.log(`Created hsm key: ${key.name}`); + return key; + } + + return createKeyHsm(); + // [END kms_create_key_hsm] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeyLabels.js b/kms/createKeyLabels.js new file mode 100644 index 0000000000..71460cf523 --- /dev/null +++ b/kms/createKeyLabels.js @@ -0,0 +1,70 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + id = 'my-labeled-key' +) { + // [START kms_create_key_labels] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const id = 'my-labeled-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent key ring name + const keyRingName = client.keyRingPath(projectId, locationId, keyRingId); + + async function createKeyLabels() { + const [key] = await client.createCryptoKey({ + parent: keyRingName, + cryptoKeyId: id, + cryptoKey: { + purpose: 'ENCRYPT_DECRYPT', + versionTemplate: { + algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION', + }, + labels: { + team: 'alpha', + cost_center: 'cc1234', + }, + }, + }); + + console.log(`Created labeled key: ${key.name}`); + return key; + } + + return createKeyLabels(); + // [END kms_create_key_labels] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeyRing.js b/kms/createKeyRing.js new file mode 100644 index 0000000000..90820afa40 --- /dev/null +++ b/kms/createKeyRing.js @@ -0,0 +1,58 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + id = 'my-key-ring' +) { + // [START kms_create_key_ring] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const id = 'my-key-ring'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent location name + const locationName = client.locationPath(projectId, locationId); + + async function createKeyRing() { + const [keyRing] = await client.createKeyRing({ + parent: locationName, + keyRingId: id, + }); + + console.log(`Created key ring: ${keyRing.name}`); + return keyRing; + } + + return createKeyRing(); + // [END kms_create_key_ring] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeyRotationSchedule.js b/kms/createKeyRotationSchedule.js new file mode 100644 index 0000000000..93d0d04c54 --- /dev/null +++ b/kms/createKeyRotationSchedule.js @@ -0,0 +1,76 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + id = 'my-rotating-encryption-key' +) { + // [START kms_create_key_rotation_schedule] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const id = 'my-rotating-encryption-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent key ring name + const keyRingName = client.keyRingPath(projectId, locationId, keyRingId); + + async function createKeyRotationSchedule() { + const [key] = await client.createCryptoKey({ + parent: keyRingName, + cryptoKeyId: id, + cryptoKey: { + purpose: 'ENCRYPT_DECRYPT', + versionTemplate: { + algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION', + }, + + // Rotate the key every 30 days. + rotationPeriod: { + seconds: 60 * 60 * 24 * 30, + }, + + // Start the first rotation in 24 hours. + nextRotationTime: { + seconds: new Date().getTime() / 1000 + 60 * 60 * 24, + }, + }, + }); + + console.log(`Created rotating key: ${key.name}`); + return key; + } + + return createKeyRotationSchedule(); + // [END kms_create_key_rotation_schedule] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeySymmetricEncryptDecrypt.js b/kms/createKeySymmetricEncryptDecrypt.js new file mode 100644 index 0000000000..6f1ab1df00 --- /dev/null +++ b/kms/createKeySymmetricEncryptDecrypt.js @@ -0,0 +1,66 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + id = 'my-symmetric-encryption-key' +) { + // [START kms_create_key_symmetric_encrypt_decrypt] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const id = 'my-symmetric-encryption-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent key ring name + const keyRingName = client.keyRingPath(projectId, locationId, keyRingId); + + async function createKeySymmetricEncryptDecrypt() { + const [key] = await client.createCryptoKey({ + parent: keyRingName, + cryptoKeyId: id, + cryptoKey: { + purpose: 'ENCRYPT_DECRYPT', + versionTemplate: { + algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION', + }, + }, + }); + + console.log(`Created symmetric key: ${key.name}`); + return key; + } + + return createKeySymmetricEncryptDecrypt(); + // [END kms_create_key_symmetric_encrypt_decrypt] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeyVersion.js b/kms/createKeyVersion.js new file mode 100644 index 0000000000..03747cb7b0 --- /dev/null +++ b/kms/createKeyVersion.js @@ -0,0 +1,59 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key' +) { + // [START kms_create_key_version] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the parent key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function createKeyVersion() { + const [version] = await client.createCryptoKeyVersion({ + parent: keyName, + }); + + console.log(`Created key version: ${version.name}`); + return version; + } + + return createKeyVersion(); + // [END kms_create_key_version] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/createKeyring.js b/kms/createKeyring.js deleted file mode 100644 index 2b97aba3de..0000000000 --- a/kms/createKeyring.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_create_keyring] -async function createKeyRing( - projectId = 'YOUR_PROJECT_ID', // Your GCP projectId - keyRingId = 'my-new-key-ring' // Name of the new key ring -) { - // The location of the new key ring, e.g. "global" - const locationId = 'global'; - - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // Get the full path to the parent - const parent = client.locationPath(projectId, locationId); - - // Creates a new key ring - const [result] = await client.createKeyRing({parent, keyRingId}); - console.log(`Key ring ${result.name} created.`); -} -// [END kms_create_keyring] - -const args = process.argv.slice(2); -createKeyRing(...args).catch(console.error); diff --git a/kms/decrypt.js b/kms/decrypt.js deleted file mode 100644 index 9d775ef9da..0000000000 --- a/kms/decrypt.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_decrypt] -async function decrypt( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - ciphertextFileName = './path/to/plaintext.txt.encrypted', - plaintextFileName = './path/to/plaintext.txt.decrypted' -) { - const fs = require('fs'); - const {promisify} = require('util'); - - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Reads the file to be decrypted - const readFile = promisify(fs.readFile); - const ciphertext = await readFile(ciphertextFileName); - const name = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - - // Decrypts the file using the specified crypto key - const [result] = await client.decrypt({name, ciphertext}); - - // Writes the decrypted file to disk - const writeFile = promisify(fs.writeFile); - await writeFile(plaintextFileName, result.plaintext); - console.log( - `Decrypted ${ciphertextFileName}, result saved to ${plaintextFileName}.` - ); -} -// [END kms_decrypt] - -const args = process.argv.slice(2); -decrypt(...args).catch(console.error); diff --git a/kms/decryptAsymmetric.js b/kms/decryptAsymmetric.js new file mode 100644 index 0000000000..50397ba054 --- /dev/null +++ b/kms/decryptAsymmetric.js @@ -0,0 +1,76 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123', + ciphertext = Buffer.from('...') +) { + // [START kms_decrypt_asymmetric] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + // const ciphertext = Buffer.from('...'); + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function decryptAsymmetric() { + const [result] = await client.asymmetricDecrypt({ + name: versionName, + ciphertext: ciphertext, + }); + + // NOTE: The ciphertext must be properly formatted. In Node < 12, the + // crypto.publicEncrypt() function does not properly consume the OAEP + // padding and thus produces invalid ciphertext. If you are using Node to do + // public key encryption, please use version 12+. + const plaintext = result.plaintext.toString('utf8'); + + console.log(`Plaintext: ${plaintext}`); + return plaintext; + } + + return decryptAsymmetric(); + // [END kms_decrypt_asymmetric] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/decryptSymmetric.js b/kms/decryptSymmetric.js new file mode 100644 index 0000000000..1e288258e5 --- /dev/null +++ b/kms/decryptSymmetric.js @@ -0,0 +1,64 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + ciphertext = Buffer.from('...') +) { + // [START kms_decrypt_symmetric] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const ciphertext = Buffer.from('...'); + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function decryptSymmetric() { + const [result] = await client.decrypt({ + name: keyName, + ciphertext: ciphertext, + }); + + const plaintext = result.plaintext.toString('utf8'); + + console.log(`Plaintext: ${plaintext}`); + return plaintext; + } + + return decryptSymmetric(); + // [END kms_decrypt_symmetric] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/destroyCryptoKeyVersion.js b/kms/destroyCryptoKeyVersion.js deleted file mode 100644 index 49078c6271..0000000000 --- a/kms/destroyCryptoKeyVersion.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_destroy_cryptokey_version] -async function destroyCryptoKeyVersion( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key version's key ring - cryptoKeyId = 'my-key', // Name of the version's crypto key - version = 1234 // The version's id -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key versions's key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the crypto key version - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - version - ); - - // destroys a crypto key version - const [result] = await client.destroyCryptoKeyVersion({name}); - console.log(`Crypto key version ${result.name} destroyed.`); -} -// [END kms_destroy_cryptokey_version] - -const args = process.argv.slice(2); -destroyCryptoKeyVersion(...args).catch(console.error); diff --git a/kms/destroyKeyVersion.js b/kms/destroyKeyVersion.js new file mode 100644 index 0000000000..b5511cc258 --- /dev/null +++ b/kms/destroyKeyVersion.js @@ -0,0 +1,67 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123' +) { + // [START kms_destroy_key_version] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function destroyKeyVersion() { + const [version] = await client.destroyCryptoKeyVersion({ + name: versionName, + }); + + console.log(`Destroyed key version: ${version.name}`); + return version; + } + + return destroyKeyVersion(); + // [END kms_destroy_key_version] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/disableCryptoKeyVersion.js b/kms/disableCryptoKeyVersion.js deleted file mode 100644 index b11129587a..0000000000 --- a/kms/disableCryptoKeyVersion.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_disable_cryptokey_version] -async function disableCryptoKeyVersion( - projectId = 'your-project-id', // Your GCP Project ID - keyRingId = 'my-key-ring', // Name of the crypto key version's key ring - cryptoKeyId = 'my-key', // Name of the version's crypto key - version = 1234 // The version's id -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key versions's key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the crypto key - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - version - ); - - // Gets a crypto key version - const [cryptoKeyVersion] = await client.getCryptoKeyVersion({name}); - - // Disables a crypto key version - const [result] = await client.updateCryptoKeyVersion({ - cryptoKeyVersion: {state: 'DISABLED', name: cryptoKeyVersion.name}, - updateMask: ['state'], - }); - console.log(`Crypto key version ${result.name} disabled.`); -} -// [END kms_disable_cryptokey_version] - -const args = process.argv.slice(2); -disableCryptoKeyVersion(...args).catch(console.error); diff --git a/kms/disableKeyVersion.js b/kms/disableKeyVersion.js new file mode 100644 index 0000000000..976094c660 --- /dev/null +++ b/kms/disableKeyVersion.js @@ -0,0 +1,73 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123' +) { + // [START kms_disable_key_version] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function disableKeyVersion() { + const [version] = await client.updateCryptoKeyVersion({ + cryptoKeyVersion: { + name: versionName, + state: 'DISABLED', + }, + updateMask: { + paths: ['state'], + }, + }); + + console.log(`Disabled key version: ${version.name}`); + return version; + } + + return disableKeyVersion(); + // [END kms_disable_key_version] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/enableCryptoKeyVersion.js b/kms/enableCryptoKeyVersion.js deleted file mode 100644 index b311fba16a..0000000000 --- a/kms/enableCryptoKeyVersion.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_enable_cryptokey_version] -async function enableCryptoKeyVersion( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key version's key ring - cryptoKeyId = 'my-key', // Name of the version's crypto key - version = 1234 // The version's id -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key versions's key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the crypto key - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - version - ); - - // Gets a crypto key version - const [cryptoKeyVersion] = await client.getCryptoKeyVersion({name}); - - // enables a crypto key version - const [result] = await client.updateCryptoKeyVersion({ - cryptoKeyVersion: {state: 'ENABLED', name: cryptoKeyVersion.name}, - updateMask: ['state'], - }); - console.log(`Crypto key version ${result.name} enabled.`); -} -// [END kms_enable_cryptokey_version] - -const args = process.argv.slice(2); -enableCryptoKeyVersion(...args).catch(console.error); diff --git a/kms/enableKeyVersion.js b/kms/enableKeyVersion.js new file mode 100644 index 0000000000..d73ade3e4f --- /dev/null +++ b/kms/enableKeyVersion.js @@ -0,0 +1,73 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123' +) { + // [START kms_enable_key_version] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function enableKeyVersion() { + const [version] = await client.updateCryptoKeyVersion({ + cryptoKeyVersion: { + name: versionName, + state: 'ENABLED', + }, + updateMask: { + paths: ['state'], + }, + }); + + console.log(`Enabled key version: ${version.name}`); + return version; + } + + return enableKeyVersion(); + // [END kms_enable_key_version] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/encrypt.js b/kms/encrypt.js deleted file mode 100644 index 8c9080f4e1..0000000000 --- a/kms/encrypt.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_encrypt] -async function encrypt( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - plaintextFileName = './path/to/plaintext.txt', - ciphertextFileName = './path/to/plaintext.txt.encrypted' -) { - const fs = require('fs'); - const {promisify} = require('util'); - - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Reads the file to be encrypted - const readFile = promisify(fs.readFile); - const plaintext = await readFile(plaintextFileName); - const name = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - - // Encrypts the file using the specified crypto key - const [result] = await client.encrypt({name, plaintext}); - const writeFile = promisify(fs.writeFile); - await writeFile(ciphertextFileName, result.ciphertext); - console.log(`Encrypted ${plaintextFileName} using ${result.name}.`); - console.log(`Result saved to ${ciphertextFileName}.`); -} -// [END kms_encrypt] - -const args = process.argv.slice(2); -encrypt(...args).catch(console.error); diff --git a/kms/encryptAsymmetric.js b/kms/encryptAsymmetric.js new file mode 100644 index 0000000000..6544d96b38 --- /dev/null +++ b/kms/encryptAsymmetric.js @@ -0,0 +1,89 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123', + plaintextBuffer = Buffer.from('...') +) { + // [START kms_encrypt_asymmetric] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + // const plaintextBuffer = Buffer.from('...'); + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function encryptAsymmetric() { + // Get public key from Cloud KMS + const [publicKey] = await client.getPublicKey({ + name: versionName, + }); + + // Import and setup crypto + const crypto = require('crypto'); + + // Encrypt plaintext locally using the public key. This example uses a key + // that was configured with sha256 hash with OAEP padding. Update these + // values to match the Cloud KMS key. + // + // NOTE: In Node < 12, this function does not properly consume the OAEP + // padding and thus produces invalid ciphertext. If you are using Node to do + // public key encryption, please use version 12+. + const ciphertextBuffer = crypto.publicEncrypt( + { + key: publicKey.pem, + oaepHash: 'sha256', + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + }, + plaintextBuffer + ); + + console.log(`Ciphertext: ${ciphertextBuffer.toString('base64')}`); + return ciphertextBuffer; + } + + return encryptAsymmetric(); + // [END kms_encrypt_asymmetric] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/encryptSymmetric.js b/kms/encryptSymmetric.js new file mode 100644 index 0000000000..64106b6242 --- /dev/null +++ b/kms/encryptSymmetric.js @@ -0,0 +1,64 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + plaintextBuffer = Buffer.from('...') +) { + // [START kms_encrypt_symmetric] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const plaintextBuffer = Buffer.from('...'); + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function encryptSymmetric() { + const [encryptResponse] = await client.encrypt({ + name: keyName, + plaintext: plaintextBuffer, + }); + + const ciphertext = encryptResponse.ciphertext; + + console.log(`Ciphertext: ${ciphertext.toString('base64')}`); + return ciphertext; + } + + return encryptSymmetric(); + // [END kms_encrypt_symmetric] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/getCryptoKey.js b/kms/getCryptoKey.js deleted file mode 100644 index 3731ab0da5..0000000000 --- a/kms/getCryptoKey.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_get_cryptokey] -async function getCryptoKey( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key' // Name of the crypto key, e.g. "my-key" -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - const name = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - - // Gets a crypto key - const [cryptoKey] = await client.getCryptoKey({name}); - console.log(`Name: ${cryptoKey.name}:`); - console.log(`Created: ${new Date(cryptoKey.createTime)}`); - console.log(`Purpose: ${cryptoKey.purpose}`); - console.log(`Primary: ${cryptoKey.primary.name}`); - console.log(` State: ${cryptoKey.primary.state}`); - console.log(` Created: ${new Date(cryptoKey.primary.createTime)}`); -} -// [END kms_get_cryptokey] - -const args = process.argv.slice(2); -getCryptoKey(...args).catch(console.error); diff --git a/kms/getCryptoKeyIamPolicy.js b/kms/getCryptoKeyIamPolicy.js deleted file mode 100644 index 83df614ec4..0000000000 --- a/kms/getCryptoKeyIamPolicy.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_get_cryptokey_policy] -async function getCryptoKeyIamPolicy( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key' // Name of the crypto key, e.g. "my-key" -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - const resource = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - - // Gets the IAM policy of a crypto key - const [policy] = await client.getIamPolicy({resource}); - if (policy.bindings && policy.bindings.length > 0) { - policy.bindings.forEach(binding => { - if (binding.members && binding.members.length) { - console.log(`${binding.role}:`); - binding.members.forEach(member => { - console.log(` ${member}`); - }); - } - }); - } else { - console.log(`Policy for crypto key ${cryptoKeyId} is empty.`); - } -} -// [END kms_get_cryptokey_policy] - -const args = process.argv.slice(2); -getCryptoKeyIamPolicy(...args).catch(console.error); diff --git a/kms/getKeyLabels.js b/kms/getKeyLabels.js new file mode 100644 index 0000000000..728b124e2c --- /dev/null +++ b/kms/getKeyLabels.js @@ -0,0 +1,62 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key' +) { + // [START kms_get_key_labels] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function getKeyLabels() { + const [key] = await client.getCryptoKey({ + name: keyName, + }); + + for (const k in key.labels) { + console.log(`${k}: ${key.labels[k]}`); + } + + return key; + } + + return getKeyLabels(); + // [END kms_get_key_labels] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/getKeyVersionAttestation.js b/kms/getKeyVersionAttestation.js new file mode 100644 index 0000000000..dbd621e6b5 --- /dev/null +++ b/kms/getKeyVersionAttestation.js @@ -0,0 +1,74 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123' +) { + // [START kms_get_key_version_attestation] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function getKeyVersionAttestation() { + const [version] = await client.getCryptoKeyVersion({ + name: versionName, + }); + + // Only HSM keys have an attestation. For other key types, the attestion + // will be nil. + const attestation = version.attestation; + if (!attestation) { + throw new Error('no attestation'); + } + + console.log(`Attestation: ${attestation.toString('base64')}`); + return attestation.content; + } + + return getKeyVersionAttestation(); + // [END kms_get_key_version_attestation] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/getKeyring.js b/kms/getKeyring.js deleted file mode 100644 index 3d04542492..0000000000 --- a/kms/getKeyring.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_get_keyring] -async function getKeyRing( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring' // Name of the crypto key's key ring -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the keyring - const name = client.keyRingPath(projectId, locationId, keyRingId); - - // Get the keyring - const [keyRing] = await client.getKeyRing({name}); - console.log(`Name: ${keyRing.name}`); - console.log(`Created: ${new Date(keyRing.createTime.seconds * 1000)}`); -} -// [END kms_get_keyring] - -const args = process.argv.slice(2); -getKeyRing(...args).catch(console.error); diff --git a/kms/getKeyringIamPolicy.js b/kms/getKeyringIamPolicy.js deleted file mode 100644 index f89ebd75ab..0000000000 --- a/kms/getKeyringIamPolicy.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_get_keyring_policy] -async function getKeyRingIamPolicy( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring' // Name of the crypto key's key ring -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the keyring - const resource = client.keyRingPath(projectId, locationId, keyRingId); - - // Gets the IAM policy of a key ring - const [policy] = await client.getIamPolicy({resource}); - if (policy.bindings && policy.bindings.length > 0) { - policy.bindings.forEach(binding => { - if (binding.members && binding.members.length) { - console.log(`${binding.role}:`); - binding.members.forEach(member => { - console.log(` ${member}`); - }); - } - }); - } else { - console.log(`Policy for key ring ${keyRingId} is empty.`); - } -} -// [END kms_get_keyring_policy] - -const args = process.argv.slice(2); -getKeyRingIamPolicy(...args).catch(console.error); diff --git a/kms/getPublicKey.js b/kms/getPublicKey.js index 15c67b060f..3a4627256e 100644 --- a/kms/getPublicKey.js +++ b/kms/getPublicKey.js @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,36 +14,54 @@ 'use strict'; -// [START kms_get_public_key] -async function getPublicKey( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - cryptoKeyVersionId = '1' // Version of the crypto key to fetch +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123' ) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); + // [START kms_get_public_key] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); - // Construct the crypto key version ID - const name = client.cryptoKeyVersionPath( + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( projectId, locationId, keyRingId, - cryptoKeyId, - cryptoKeyVersionId + keyId, + versionId ); - // Get public key from Cloud KMS - const [publicKey] = await client.getPublicKey({name: name}); + async function getPublicKey() { + const [publicKey] = await client.getPublicKey({ + name: versionName, + }); + + console.log(`Public key pem: ${publicKey.pem}`); - // Return the public key pem - return publicKey.pem; + return publicKey; + } + + return getPublicKey(); + // [END kms_get_public_key] } -// [END kms_get_public_key] +module.exports.main = main; -const args = process.argv.slice(2); -getPublicKey(...args).catch(console.error); +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/iamAddMember.js b/kms/iamAddMember.js new file mode 100644 index 0000000000..4010167c0a --- /dev/null +++ b/kms/iamAddMember.js @@ -0,0 +1,82 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + member = 'user:foo@example.com' +) { + // [START kms_iam_add_member] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const member = 'user:foo@example.com'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the resource name + const resourceName = client.cryptoKeyPath( + projectId, + locationId, + keyRingId, + keyId + ); + + // The resource name could also be a key ring. + // const resourceName = client.keyRingPath(projectId, locationId, keyRingId); + + async function iamAddMember() { + // Get the current IAM policy. + const [policy] = await client.getIamPolicy({ + resource: resourceName, + }); + + // Add the member to the policy. + policy.bindings.push({ + role: 'roles/cloudkms.cryptoKeyEncrypterDecrypter', + members: [member], + }); + + // Save the updated policy. + const [updatedPolicy] = await client.setIamPolicy({ + resource: resourceName, + policy: policy, + }); + + console.log('Updated policy'); + return updatedPolicy; + } + + return iamAddMember(); + // [END kms_iam_add_member] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/iamGetPolicy.js b/kms/iamGetPolicy.js new file mode 100644 index 0000000000..c28bd3e2ea --- /dev/null +++ b/kms/iamGetPolicy.js @@ -0,0 +1,74 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key' +) { + // [START kms_iam_get_policy] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const member = 'user:foo@example.com'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the resource name + const resourceName = client.cryptoKeyPath( + projectId, + locationId, + keyRingId, + keyId + ); + + // The resource name could also be a key ring. + // const resourceName = client.keyRingPath(projectId, locationId, keyRingId); + + async function iamGetPolicy() { + const [policy] = await client.getIamPolicy({ + resource: resourceName, + }); + + for (const binding of policy.bindings) { + console.log(`Role: ${binding.role}`); + for (const member of binding.members) { + console.log(` - ${member}`); + } + } + + return policy; + } + + return iamGetPolicy(); + // [END kms_iam_get_policy] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/iamRemoveMember.js b/kms/iamRemoveMember.js new file mode 100644 index 0000000000..b920ef7954 --- /dev/null +++ b/kms/iamRemoveMember.js @@ -0,0 +1,89 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + member = 'user:foo@example.com' +) { + // [START kms_iam_remove_member] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const member = 'user:foo@example.com'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the resource name + const resourceName = client.cryptoKeyPath( + projectId, + locationId, + keyRingId, + keyId + ); + + // The resource name could also be a key ring. + // const resourceName = client.keyRingPath(projectId, locationId, keyRingId); + + async function iamRemoveMember() { + // Get the current IAM policy. + const [policy] = await client.getIamPolicy({ + resource: resourceName, + }); + + // Build a new list of policy bindings with the user excluded. + for (const i in policy.bindings) { + const binding = policy.bindings[i]; + if (binding.role !== 'roles/cloudkms.cryptoKeyEncrypterDecrypter') { + continue; + } + + const idx = binding.members.indexOf(member); + if (idx !== -1) { + binding.members.splice(idx, 1); + } + } + + // Save the updated IAM policy. + const [updatedPolicy] = await client.setIamPolicy({ + resource: resourceName, + policy: policy, + }); + + console.log('Updated policy'); + return updatedPolicy; + } + + return iamRemoveMember(); + // [END kms_iam_remove_member] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/listCryptoKeyVersions.js b/kms/listCryptoKeyVersions.js deleted file mode 100644 index 09f2999a1b..0000000000 --- a/kms/listCryptoKeyVersions.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_list_cryptokey_versions] -async function listCryptoKeyVersions( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // name of the crypto key's key ring - cryptoKeyId = 'my-key-ring' // name of the crypto key from which to list versions -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Get full path to crypto key - const parent = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - - // Creates a new key ring - const [versions] = await client.listCryptoKeyVersions({parent}); - if (versions.length) { - versions.forEach(version => { - console.log(`${version.name}:`); - console.log(` Created: ${new Date(version.createTime.seconds * 1000)}`); - console.log(` State: ${version.state}`); - }); - } else { - console.log('No crypto key versions found.'); - } -} -// [END kms_list_cryptokey_versions] - -const args = process.argv.slice(2); -listCryptoKeyVersions(...args).catch(console.error); diff --git a/kms/listCryptoKeys.js b/kms/listCryptoKeys.js deleted file mode 100644 index 61d4f0b72f..0000000000 --- a/kms/listCryptoKeys.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_list_cryptokeys] -async function listCryptoKeys( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring' // Name of the crypto key's key ring -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the key ring from which to list crypto keys, e.g. "global" - const locationId = 'global'; - - const parent = client.keyRingPath(projectId, locationId, keyRingId); - - // Creates a new key ring - const [cryptoKeys] = await client.listCryptoKeys({parent}); - if (cryptoKeys.length) { - cryptoKeys.forEach(cryptoKey => { - console.log(`${cryptoKey.name}:`); - console.log(` Created: ${new Date(cryptoKey.createTime)}`); - console.log(` Purpose: ${cryptoKey.purpose}`); - console.log(` Primary: ${cryptoKey.primary.name}`); - console.log(` State: ${cryptoKey.primary.state}`); - console.log(` Created: ${new Date(cryptoKey.primary.createTime)}`); - }); - } else { - console.log('No crypto keys found.'); - } -} -// [END kms_list_cryptokeys] - -const args = process.argv.slice(2); -listCryptoKeys(...args).catch(console.error); diff --git a/kms/listKeyrings.js b/kms/listKeyrings.js deleted file mode 100644 index 4c7e7a5d54..0000000000 --- a/kms/listKeyrings.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_list_keyrings] -async function listKeyRings( - projectId = 'your-project-id' // Your GCP Project ID -) { - // The location from which to list key rings, e.g. "global" - const locationId = 'global'; - - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // Lists key rings - const parent = client.locationPath(projectId, locationId); - const [keyRings] = await client.listKeyRings({parent}); - - if (keyRings.length) { - keyRings.forEach(keyRing => { - console.log(`${keyRing.name}:`); - console.log(` Created: ${new Date(keyRing.createTime.seconds * 1000)}`); - }); - } else { - console.log('No key rings found.'); - } -} -// [END kms_list_keyrings] - -const args = process.argv.slice(2); -listKeyRings(...args).catch(console.error); diff --git a/kms/package.json b/kms/package.json index 8008c6921e..6f6c2f08ca 100644 --- a/kms/package.json +++ b/kms/package.json @@ -2,24 +2,24 @@ "name": "nodejs-kms-samples", "private": true, "license": "Apache-2.0", - "author": "Google Inc.", - "repository": "googleapis/nodejs-kms", "files": [ "*.js" ], + "author": "Google LLC", + "repository": "googleapis/nodejs-kms", "engines": { "node": ">=8" }, "scripts": { - "test": "mocha system-test" + "test": "c8 mocha --recursive test/ --timeout=800000" }, "dependencies": { "@google-cloud/kms": "^2.0.0" }, "devDependencies": { + "c8": "^7.0.0", "chai": "^4.2.0", "mocha": "^7.0.0", - "uuid": "^7.0.2", - "yargs": "^15.0.0" + "uuid": "^3.3.3" } } diff --git a/kms/quickstart.js b/kms/quickstart.js index c4dce4c1ff..503a8dcddf 100644 --- a/kms/quickstart.js +++ b/kms/quickstart.js @@ -1,4 +1,4 @@ -// Copyright 2018 Google LLC +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,32 +14,42 @@ 'use strict'; -// [START kms_quickstart] -async function quickstart( - projectId = 'your-project-id' // Your GCP projectId -) { - // Imports the @google-cloud/kms client library - const kms = require('@google-cloud/kms'); - - // Instantiates an authorized client - const client = new kms.KeyManagementServiceClient(); - - // Lists keys in the "global" location. - const locationId = 'global'; - - // Lists key rings - const parent = client.locationPath(projectId, locationId); - const [keyRings] = await client.listKeyRings({parent}); - - // Display the results - if (keyRings.length) { - console.log('Key rings:'); - keyRings.forEach(keyRing => console.log(keyRing.name)); - } else { - console.log('No key rings found.'); +async function main(projectId = 'my-project', locationId = 'us-east1') { + // [START kms_quickstart] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the location name + const locationName = client.locationPath(projectId, locationId); + + async function listKeyRings() { + const [keyRings] = await client.listKeyRings({ + parent: locationName, + }); + + for (const keyRing of keyRings) { + console.log(keyRing.name); + } + + return keyRings; } + + return listKeyRings(); + // [END kms_quickstart] } -// [END kms_quickstart] +module.exports.main = main; -const args = process.argv.slice(2); -quickstart(...args).catch(console.error); +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/removeMemberCryptoKeyPolicy.js b/kms/removeMemberCryptoKeyPolicy.js deleted file mode 100644 index e7e26e98f2..0000000000 --- a/kms/removeMemberCryptoKeyPolicy.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_remove_member_from_cryptokey_policy] -async function removeMemberFromCryptoKeyPolicy( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key" - member = 'user:dev@example.com', // Member to add to the crypto key - role = 'roles/viewer' // Role to give the member -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key's key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the crypto key - const resource = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - - // Gets the IAM policy of a crypto key - const [result] = await client.getIamPolicy({resource}); - let policy = Object.assign({bindings: []}, result); - const index = policy.bindings.findIndex(binding => binding.role === role); - const members = []; - const binding = Object.assign({role, members}, policy.bindings[index]); - if (index === -1) { - return; - } - if (!binding.members.includes(member)) { - return; - } - - // Remove the role/member combo from the policy - binding.members.splice(binding.members.indexOf(member), 1); - - const request = {resource, policy}; - console.log(JSON.stringify(request, null, 2)); - - // Removes the member/role combo from the policy of the crypto key - [policy] = await client.setIamPolicy(request); - console.log( - `${member}/${role} combo removed from policy for crypto key ${cryptoKeyId}.` - ); - if (policy.bindings) { - policy.bindings.forEach(binding => { - if (binding.members && binding.members.length) { - console.log(`${binding.role}:`); - binding.members.forEach(member => { - console.log(` ${member}`); - }); - } - }); - } else { - console.log(`Policy for crypto key ${cryptoKeyId} is empty.`); - } -} -// [END kms_remove_member_from_cryptokey_policy] - -const args = process.argv.slice(2); -removeMemberFromCryptoKeyPolicy(...args).catch(console.error); diff --git a/kms/removeMemberFromKeyRingPolicy.js b/kms/removeMemberFromKeyRingPolicy.js deleted file mode 100644 index 185f1e69da..0000000000 --- a/kms/removeMemberFromKeyRingPolicy.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_remove_member_from_keyring_policy] -async function removeMemberFromKeyRingPolicy( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key's key ring - member = 'user:dev@example.com', // Member to rm from the crypto key - role = 'roles/viewer' // Role to give the member -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the key ring, e.g. "global" - const locationId = 'global'; - - // Get the path to the key ring - const resource = client.keyRingPath(projectId, locationId, keyRingId); - - // Gets the IAM policy of a key ring - const [result] = await client.getIamPolicy({resource}); - let policy = Object.assign({bindings: []}, result); - const index = policy.bindings.findIndex(binding => binding.role === role); - const members = []; - const binding = Object.assign({role, members}, policy.bindings[index]); - if (index === -1) { - return; - } - if (!binding.members.includes(member)) { - return; - } - - // Remove the role/member combo from the policy - binding.members.splice(binding.members.indexOf(member), 1); - - // Removes the role/member combo from the policy of the key ring - [policy] = await client.setIamPolicy({resource, policy}); - console.log( - `${member}/${role} combo removed from policy for key ring ${keyRingId}.` - ); - if (policy.bindings) { - policy.bindings.forEach(binding => { - if (binding.members && binding.members.length) { - console.log(`${binding.role}:`); - binding.members.forEach(member => { - console.log(` ${member}`); - }); - } - }); - } else { - console.log(`Policy for key ring ${keyRingId} is empty.`); - } -} -// [END kms_remove_member_from_keyring_policy] - -const args = process.argv.slice(2); -removeMemberFromKeyRingPolicy(...args).catch(console.error); diff --git a/kms/resources/plaintext.txt b/kms/resources/plaintext.txt deleted file mode 100644 index 2af8b3cee8..0000000000 --- a/kms/resources/plaintext.txt +++ /dev/null @@ -1,4 +0,0 @@ -So if you're lost and on your own -You can never surrender -And if your path won't lead you home -You can never surrender \ No newline at end of file diff --git a/kms/restoreCryptoKeyVersion.js b/kms/restoreCryptoKeyVersion.js deleted file mode 100644 index 45594114f5..0000000000 --- a/kms/restoreCryptoKeyVersion.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_restore_cryptokey_version] -async function restoreCryptoKeyVersion( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key version's key ring - cryptoKeyId = 'my-key', // Name of the version's crypto key - version = 1234 // The version's id -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key versions's key ring, e.g. "global" - const locationId = 'global'; - - // Get the full path to the crypto key version - const name = client.cryptoKeyVersionPath( - projectId, - locationId, - keyRingId, - cryptoKeyId, - version - ); - - // restores a crypto key version - const [result] = await client.restoreCryptoKeyVersion({name}); - console.log(`Crypto key version ${result.name} restored.`); -} -// [END kms_restore_cryptokey_version] - -const args = process.argv.slice(2); -restoreCryptoKeyVersion(...args).catch(console.error); diff --git a/kms/restoreKeyVersion.js b/kms/restoreKeyVersion.js new file mode 100644 index 0000000000..e2121f6d63 --- /dev/null +++ b/kms/restoreKeyVersion.js @@ -0,0 +1,67 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123' +) { + // [START kms_restore_key_version] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function restoreKeyVersion() { + const [version] = await client.restoreCryptoKeyVersion({ + name: versionName, + }); + + console.log(`Restored key version: ${version.name}`); + return version; + } + + return restoreKeyVersion(); + // [END kms_restore_key_version] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/setPrimaryCryptoKeyVersion.js b/kms/setPrimaryCryptoKeyVersion.js deleted file mode 100644 index a2f743d0df..0000000000 --- a/kms/setPrimaryCryptoKeyVersion.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -// [START kms_set_cryptokey_primary_version] -async function setPrimaryCryptoKeyVersion( - projectId = 'your-project-id', // Your GCP projectId - keyRingId = 'my-key-ring', // Name of the crypto key version's key ring - cryptoKeyId = 'my-key', // Name of the version's crypto key - version = 1234 // The version's id -) { - // Import the library and create a client - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - // The location of the crypto key versions's key ring, e.g. "global" - const locationId = 'global'; - - const name = client.cryptoKeyPath( - projectId, - locationId, - keyRingId, - cryptoKeyId - ); - const cryptoKeyVersionId = version; - const request = {name, cryptoKeyVersionId}; - - // Sets a crypto key's primary version - const [cryptoKey] = await client.updateCryptoKeyPrimaryVersion(request); - console.log( - `Set ${version} as primary version for crypto key ${cryptoKeyId}.\n` - ); - console.log(`Name: ${cryptoKey.name}:`); - console.log(`Created: ${new Date(cryptoKey.createTime)}`); - console.log(`Purpose: ${cryptoKey.purpose}`); - console.log(`Primary: ${cryptoKey.primary.name}`); - console.log(` State: ${cryptoKey.primary.state}`); - console.log(` Created: ${new Date(cryptoKey.primary.createTime)}`); -} -// [END kms_set_cryptokey_primary_version] - -const args = process.argv.slice(2); -setPrimaryCryptoKeyVersion(...args).catch(console.error); diff --git a/kms/signAsymmetric.js b/kms/signAsymmetric.js new file mode 100644 index 0000000000..1f6a3037dc --- /dev/null +++ b/kms/signAsymmetric.js @@ -0,0 +1,85 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +// [START kms_sign_asymmetric] +async function main( + projectId = 'your-project-id', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123', + message = Buffer.from('...') +) { + // [START kms_sign_asymmetric] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'your-project-id'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + // const message = Buffer.from('...'); + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the version name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function signAsymmetric() { + // Create a digest of the message. The digest needs to match the digest + // configured for the Cloud KMS key. + const crypto = require('crypto'); + const digest = crypto.createHash('sha256'); + digest.update(message); + + // Sign the message with Cloud KMS + const [signResponse] = await client.asymmetricSign({ + name: versionName, + digest: { + sha256: digest.digest(), + }, + }); + + // Example of how to display signature. Because the signature is in a binary + // format, you need to encode the output before printing it to a console or + // displaying it on a screen. + const encoded = signResponse.signature.toString('base64'); + console.log(`Signature: ${encoded}`); + + return signResponse.signature; + } + + return signAsymmetric(); + // [END kms_sign_asymmetric] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/system-test/kms.test.js b/kms/system-test/kms.test.js deleted file mode 100644 index 6bb0514f59..0000000000 --- a/kms/system-test/kms.test.js +++ /dev/null @@ -1,467 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const {assert} = require('chai'); -const {describe, it, before, after} = require('mocha'); -const cp = require('child_process'); -const {promisify} = require('util'); -const {v4} = require('uuid'); -const unlink = promisify(fs.unlink); - -const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'}); - -const keyRingName = `test-ring-${v4()}`; -const keyNameOne = `test-key-${v4()}`; -const member = 'allAuthenticatedUsers'; -const role = 'roles/viewer'; -const projectId = process.env.GCLOUD_PROJECT; -const plaintext = path.join(__dirname, '../resources/plaintext.txt'); -const ciphertext = path.join(__dirname, '../resources/plaintext.txt.encrypted'); -const decrypted = path.join(__dirname, '../resources/plaintext.txt.decrypted'); - -const unspecifiedKeyRingName = `projects/${projectId}/locations/global/keyRings/`; -const formattedKeyRingName = `projects/${projectId}/locations/global/keyRings/${keyRingName}`; -const formattedKeyName = `${formattedKeyRingName}/cryptoKeys/${keyNameOne}`; - -const nodeMajorVersion = parseInt(process.version.match(/v?(\d+).*/)[1]); - -describe('kms sample tests', () => { - before(async () => { - try { - await unlink(ciphertext); - await unlink(decrypted); - } catch (e) { - // ignore exceptions - } - }); - - after(async () => { - try { - await unlink(ciphertext); - await unlink(decrypted); - } catch (e) { - // ignore exceptions - } - }); - - it('should list key rings', async () => { - const output = execSync(`node quickstart.js "${projectId}"`); - assert.match(output, /Key rings:/); - assert.match(output, /\/locations\/global\/keyRings\//); - }); - - it('should create a key ring', async () => { - const output = execSync( - `node createKeyring.js "${projectId}" "${keyRingName}"` - ); - if (!output.includes(`KeyRing ${formattedKeyRingName} already exists`)) { - assert.match( - output, - new RegExp(`Key ring ${formattedKeyRingName} created.`) - ); - } - }); - - it('should list key rings', async () => { - const output = execSync(`node listKeyrings.js ${projectId}`); - assert.match(output, new RegExp(unspecifiedKeyRingName)); - }); - - it('should get a key ring', async () => { - const output = execSync(`node getKeyring ${projectId} ${keyRingName}`); - assert.match(output, new RegExp(`Name: ${formattedKeyRingName}`)); - assert.match(output, /Created: /); - }); - - it("should get a key ring's empty IAM policy", async () => { - const output = execSync( - `node getKeyringIamPolicy.js ${projectId} ${keyRingName}` - ); - assert.match( - output, - new RegExp(`Policy for key ring ${keyRingName} is empty.`) - ); - }); - - it('should grant access to a key ring', async () => { - const output = execSync( - `node addMemberToKeyRingPolicy.js ${projectId} ${keyRingName} ${member} ${role}` - ); - assert.match( - output, - new RegExp( - `${member}/${role} combo added to policy for key ring ${keyRingName}.` - ) - ); - }); - - it("should get a key ring's updated IAM policy", async () => { - const output = execSync( - `node getKeyringIamPolicy.js ${projectId} ${keyRingName}` - ); - assert.match(output, new RegExp(`${role}:`)); - assert.match(output, new RegExp(` ${member}`)); - }); - - it('should revoke access to a key ring', async () => { - const output = execSync( - `node removeMemberFromKeyRingPolicy.js ${projectId} ${keyRingName} ${member} ${role}` - ); - assert.match( - output, - new RegExp( - `${member}/${role} combo removed from policy for key ring ${keyRingName}.` - ) - ); - }); - - it('should create a key', async () => { - const output = execSync( - `node createCryptoKey.js ${projectId} ${keyRingName} ${keyNameOne}` - ); - if (!output.includes(`CryptoKey ${formattedKeyName} already exists`)) { - assert.match(output, new RegExp(`Key ${formattedKeyName} created.`)); - } - }); - - it('should list keys', async () => { - const output = execSync( - `node listCryptoKeys.js ${projectId} ${keyRingName}` - ); - assert.match(output, new RegExp(formattedKeyName)); - }); - - it('should get a key', async () => { - const output = execSync( - `node getCryptoKey.js ${projectId} ${keyRingName} ${keyNameOne}` - ); - assert.match(output, new RegExp(`Name: ${formattedKeyName}`)); - assert.match(output, new RegExp('Created: ')); - }); - - it("should set a crypto key's primary version", async () => { - const output = execSync( - `node setPrimaryCryptoKeyVersion.js ${projectId} ${keyRingName} ${keyNameOne} 1` - ); - assert.match( - output, - new RegExp(`Set 1 as primary version for crypto key ${keyNameOne}.\n`) - ); - }); - - it('should encrypt a file', async () => { - const output = execSync( - `node encrypt.js ${projectId} ${keyRingName} ${keyNameOne} "${plaintext}" "${ciphertext}"` - ); - assert.match( - output, - new RegExp( - `Encrypted ${plaintext} using ${formattedKeyName}/cryptoKeyVersions/1.` - ) - ); - assert.match(output, new RegExp(`Result saved to ${ciphertext}.`)); - }); - - it('should decrypt a file', async () => { - const output = execSync( - `node decrypt.js ${projectId} "${keyRingName}" "${keyNameOne}" "${ciphertext}" "${decrypted}"` - ); - assert.match( - output, - new RegExp(`Decrypted ${ciphertext}, result saved to ${decrypted}.`) - ); - - assert.strictEqual( - fs.readFileSync(plaintext, 'utf8'), - fs.readFileSync(decrypted, 'utf8') - ); - }); - - it('should create a crypto key version', async () => { - const output = execSync( - `node createCryptoKeyVersion ${projectId} "${keyRingName}" "${keyNameOne}"` - ); - assert.match( - output, - new RegExp(`Crypto key version ${formattedKeyName}/cryptoKeyVersions/`) - ); - assert.match(output, new RegExp(' created.')); - }); - - it('should list crypto key versions', async () => { - const output = execSync( - `node listCryptoKeyVersions.js ${projectId} "${keyRingName}" "${keyNameOne}"` - ); - assert.match(output, new RegExp(`${formattedKeyName}/cryptoKeyVersions/1`)); - }); - - it('should destroy a crypto key version', async () => { - const output = execSync( - `node destroyCryptoKeyVersion ${projectId} "${keyRingName}" "${keyNameOne}" 2` - ); - assert.match( - output, - new RegExp( - `Crypto key version ${formattedKeyName}/cryptoKeyVersions/2 destroyed.` - ) - ); - }); - - it('should restore a crypto key version', async () => { - const output = execSync( - `node restoreCryptoKeyVersion ${projectId} "${keyRingName}" "${keyNameOne}" 2` - ); - assert.match( - output, - new RegExp( - `Crypto key version ${formattedKeyName}/cryptoKeyVersions/2 restored.` - ) - ); - }); - - it('should enable a crypto key version', async () => { - const output = execSync( - `node enableCryptoKeyVersion ${projectId} "${keyRingName}" "${keyNameOne}" 2` - ); - assert.match( - output, - new RegExp( - `Crypto key version ${formattedKeyName}/cryptoKeyVersions/2 enabled.` - ) - ); - }); - - it('should disable a crypto key version', async () => { - const output = execSync( - `node disableCryptoKeyVersion ${projectId} "${keyRingName}" "${keyNameOne}" 2` - ); - assert.match( - output, - new RegExp( - `Crypto key version ${formattedKeyName}/cryptoKeyVersions/2 disabled.` - ) - ); - }); - - it("should get a crypto key's empty IAM policy", async () => { - const output = execSync( - `node getCryptoKeyIamPolicy ${projectId} "${keyRingName}" "${keyNameOne}"` - ); - assert.match( - output, - new RegExp(`Policy for crypto key ${keyNameOne} is empty.`) - ); - }); - - it('should grant access to a crypto key', async () => { - const output = execSync( - `node addMemberToCryptoKeyPolicy ${projectId} "${keyRingName}" "${keyNameOne}" "${member}" "${role}"` - ); - assert.match( - output, - new RegExp( - `${member}/${role} combo added to policy for crypto key ${keyNameOne}.` - ) - ); - }); - - it("should get a crypto key's updated IAM policy", async () => { - const output = execSync( - `node getCryptoKeyIamPolicy ${projectId} "${keyRingName}" "${keyNameOne}"` - ); - assert.match(output, new RegExp(`${role}:`)); - assert.match(output, new RegExp(` ${member}`)); - }); - - it('should revoke access to a crypto key', async () => { - const output = execSync( - `node removeMemberCryptoKeyPolicy ${projectId} "${keyRingName}" "${keyNameOne}" ${member} ${role}` - ); - assert.match( - output, - new RegExp( - `${member}/${role} combo removed from policy for crypto key ${keyNameOne}.` - ) - ); - }); - - describe('asymmetric keys', () => { - const kms = require('@google-cloud/kms'); - const client = new kms.KeyManagementServiceClient(); - - const locationId = 'global'; - const keyRingId = `test-asymmetric-ring-${v4()}`; - const keyAsymmetricDecryptName = `test-asymmetric-decrypt-${v4()}`; - - const keyAsymmetricSignName = `test-asymmetric-sign-${v4()}`; - - const dataToEncrypt = 'my data to encrypt'; - const dataToSign = 'my data to sign'; - - let decryptKeyVersionId; - let signKeyVersionId; - let ciphertext; - let signature; - - before(async function () { - this.timeout(10000); - // KMS keys can be created but still in "pending generation" state. This - // waits for the key version to reach the desired state. - const waitForState = async (name, state) => { - const sleep = w => new Promise(r => setTimeout(r, w)); - - let [version] = await client.getCryptoKeyVersion({name}); - while (version.state !== state) { - await sleep(250); - [version] = await client.getCryptoKeyVersion({name}); - } - }; - - // Create parent keyring - const parent = client.locationPath(projectId, locationId); - const [keyRing] = await client.createKeyRing({ - parent: parent, - keyRingId: keyRingId, - }); - - // Create asymmetric decryption key - this also creates the first key - // version. - const [asymDecryptKey] = await client.createCryptoKey({ - parent: keyRing.name, - cryptoKeyId: keyAsymmetricDecryptName, - cryptoKey: { - purpose: 'ASYMMETRIC_DECRYPT', - versionTemplate: { - algorithm: 'RSA_DECRYPT_OAEP_4096_SHA256', - }, - }, - }); - - // Wait for the first key to be ready. - decryptKeyVersionId = asymDecryptKey.name + '/cryptoKeyVersions/1'; - await waitForState(decryptKeyVersionId, 'ENABLED'); - - // Create asymmetric signing key - this also creates the first key - // version. - const [asymSignKey] = await client.createCryptoKey({ - parent: keyRing.name, - cryptoKeyId: keyAsymmetricSignName, - cryptoKey: { - purpose: 'ASYMMETRIC_SIGN', - versionTemplate: { - algorithm: 'EC_SIGN_P384_SHA384', - }, - }, - }); - - // Wait for the first key to be ready. - signKeyVersionId = asymSignKey.name + '/cryptoKeyVersions/1'; - await waitForState(signKeyVersionId, 'ENABLED'); - }); - - after(async function () { - this.timeout(10000); - await client.destroyCryptoKeyVersion({name: decryptKeyVersionId}); - await client.destroyCryptoKeyVersion({name: signKeyVersionId}); - }); - - it('should perform asymmetric encryption', async function () { - // Only run this test on Node 12+ - if (nodeMajorVersion < 12) { - this.skip(); - } - - const out = execSync(` - node asymmetricEncrypt.js \ - "${projectId}" \ - "${keyRingId}" \ - "${keyAsymmetricDecryptName}" \ - "1" \ - "${dataToEncrypt}" - `); - - const re = new RegExp('Encrypted ciphertext: (.+)'); - assert.match(out, re); - - const match = re.exec(out); - ciphertext = match[1]; - }); - - it('should perform asymmetric decryption', async function () { - // Only run this test on Node 12+ - if (nodeMajorVersion < 12) { - this.skip(); - } - - const out = execSync(` - node asymmetricDecrypt.js \ - "${projectId}" \ - "${keyRingId}" \ - "${keyAsymmetricDecryptName}" \ - "1" \ - "${ciphertext}" - `); - - const re = new RegExp('Decrypted plaintext: (.+)'); - assert.match(out, re); - - const match = re.exec(out); - const plaintext = match[1]; - - assert.equal(dataToEncrypt, plaintext); - }); - - it('should perform asymmetric signing', async () => { - const out = execSync(` - node asymmetricSign.js \ - "${projectId}" \ - "${keyRingId}" \ - "${keyAsymmetricSignName}" \ - "1" \ - "${dataToSign}" - `); - - const re = new RegExp('Signature: (.+)'); - assert.match(out, re); - - const match = re.exec(out); - signature = match[1]; - }); - - it('should perform asymmetric verification', async () => { - const out = execSync(` - node asymmetricVerify.js \ - "${projectId}" \ - "${keyRingId}" \ - "${keyAsymmetricSignName}" \ - "1" \ - "${dataToSign}" \ - "${signature}" - `); - - const re = new RegExp('Signature verified: (.+)'); - assert.match(out, re); - - const match = re.exec(out); - const verified = match[1]; - - // Correct plaintext - assert.equal(verified, 'true'); - }); - }); -}); diff --git a/kms/test/kms.test.js b/kms/test/kms.test.js new file mode 100644 index 0000000000..7908b7e647 --- /dev/null +++ b/kms/test/kms.test.js @@ -0,0 +1,760 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +const {describe, it, before, after, beforeEach, afterEach} = require('mocha'); +const {assert} = require('chai'); +const crypto = require('crypto'); +const uuidv4 = require('uuid/v4'); + +const {KeyManagementServiceClient} = require('@google-cloud/kms'); +const client = new KeyManagementServiceClient(); + +const projectId = process.env.GCLOUD_PROJECT; +const locationId = 'us-east1'; +const keyRingId = uuidv4(); +const asymmetricDecryptKeyId = uuidv4(); +const asymmetricSignEcKeyId = uuidv4(); +const asymmetricSignRsaKeyId = uuidv4(); +const hsmKeyId = uuidv4(); +const symmetricKeyId = uuidv4(); + +const nodeMajorVersion = parseInt(process.version.match(/v?(\d+).*/)[1]); + +const originalConsoleLog = console.log; + +const waitForState = async (name, state) => { + const sleep = w => new Promise(r => setTimeout(r, w)); + + let [version] = await client.getCryptoKeyVersion({name}); + while (version.state !== state) { + await sleep(100); + [version] = await client.getCryptoKeyVersion({name}); + } +}; + +describe('Cloud KMS samples', () => { + before(async () => { + if (!projectId) { + throw new Error('missing GCLOUD_PROJECT!'); + } + + await client.createKeyRing({ + parent: client.locationPath(projectId, locationId), + keyRingId: keyRingId, + }); + + await client.createCryptoKey({ + parent: client.keyRingPath(projectId, locationId, keyRingId), + cryptoKeyId: asymmetricDecryptKeyId, + cryptoKey: { + purpose: 'ASYMMETRIC_DECRYPT', + versionTemplate: { + algorithm: 'RSA_DECRYPT_OAEP_2048_SHA256', + }, + labels: { + foo: 'bar', + zip: 'zap', + }, + }, + }); + await waitForState( + client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricDecryptKeyId, + 1 + ), + 'ENABLED' + ); + + await client.createCryptoKey({ + parent: client.keyRingPath(projectId, locationId, keyRingId), + cryptoKeyId: asymmetricSignEcKeyId, + cryptoKey: { + purpose: 'ASYMMETRIC_SIGN', + versionTemplate: { + algorithm: 'EC_SIGN_P256_SHA256', + }, + labels: { + foo: 'bar', + zip: 'zap', + }, + }, + }); + await waitForState( + client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricSignEcKeyId, + 1 + ), + 'ENABLED' + ); + + await client.createCryptoKey({ + parent: client.keyRingPath(projectId, locationId, keyRingId), + cryptoKeyId: asymmetricSignRsaKeyId, + cryptoKey: { + purpose: 'ASYMMETRIC_SIGN', + versionTemplate: { + algorithm: 'RSA_SIGN_PSS_2048_SHA256', + }, + labels: { + foo: 'bar', + zip: 'zap', + }, + }, + }); + await waitForState( + client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricSignRsaKeyId, + 1 + ), + 'ENABLED' + ); + + await client.createCryptoKey({ + parent: client.keyRingPath(projectId, locationId, keyRingId), + cryptoKeyId: hsmKeyId, + cryptoKey: { + purpose: 'ENCRYPT_DECRYPT', + versionTemplate: { + algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION', + protectionLevel: 'HSM', + }, + labels: { + foo: 'bar', + zip: 'zap', + }, + }, + }); + await waitForState( + client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + hsmKeyId, + 1 + ), + 'ENABLED' + ); + + await client.createCryptoKey({ + parent: client.keyRingPath(projectId, locationId, keyRingId), + cryptoKeyId: symmetricKeyId, + cryptoKey: { + purpose: 'ENCRYPT_DECRYPT', + versionTemplate: { + algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION', + }, + labels: { + foo: 'bar', + zip: 'zap', + }, + }, + }); + await waitForState( + client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 1 + ), + 'ENABLED' + ); + }); + + beforeEach(async () => { + console.log = () => {}; + }); + + afterEach(async () => { + console.log = originalConsoleLog; + }); + + after(async () => { + if (!projectId) { + return; + } + + const [keys] = await client.listCryptoKeys({ + parent: client.keyRingPath(projectId, locationId, keyRingId), + }); + + keys.forEach(async key => { + if (key.rotationPeriod || key.nextRotationTime) { + // Remove the rotation period if one exists + await client.updateCryptoKey({ + cryptoKey: { + name: key.name, + rotationPeriod: null, + nextRotationTime: null, + }, + updateMask: { + paths: ['rotation_period', 'next_rotation_time'], + }, + }); + + const [versions] = await client.listCryptoKeyVersions({ + parent: key.name, + filter: 'state != DESTROYED AND state != DESTROY_SCHEDULED', + }); + + versions.forEach(async version => { + await client.destroyCryptoKeyVersion({ + name: version.name, + }); + }); + } + }); + }); + + it('creates asymmetric decryption keys', async () => { + const sample = require('../createKeyAsymmetricDecrypt'); + const key = await sample.main(projectId, locationId, keyRingId, uuidv4()); + assert.equal(key.purpose, 'ASYMMETRIC_DECRYPT'); + assert.equal(key.versionTemplate.algorithm, 'RSA_DECRYPT_OAEP_2048_SHA256'); + }); + + it('creates asymmetric signing keys', async () => { + const sample = require('../createKeyAsymmetricSign'); + const key = await sample.main(projectId, locationId, keyRingId, uuidv4()); + assert.equal(key.purpose, 'ASYMMETRIC_SIGN'); + assert.equal(key.versionTemplate.algorithm, 'RSA_SIGN_PKCS1_2048_SHA256'); + }); + + it('creates hsm keys', async () => { + const sample = require('../createKeyHsm'); + const key = await sample.main(projectId, locationId, keyRingId, uuidv4()); + assert.equal(key.versionTemplate.protectionLevel, 'HSM'); + }); + + it('creates labeled keys', async () => { + const sample = require('../createKeyLabels'); + const key = await sample.main(projectId, locationId, keyRingId, uuidv4()); + assert.equal(key.labels.team, 'alpha'); + assert.equal(key.labels.cost_center, 'cc1234'); + }); + + it('creates key rings', async () => { + const sample = require('../createKeyRing'); + const keyRing = await sample.main(projectId, locationId, uuidv4()); + assert.match(keyRing.name, new RegExp(`${locationId}`)); + }); + + it('creates rotating keys', async () => { + const sample = require('../createKeyRotationSchedule'); + const key = await sample.main(projectId, locationId, keyRingId, uuidv4()); + assert.exists(key.rotationPeriod); + assert.exists(key.nextRotationTime); + }); + + it('creates symmetric keys', async () => { + const sample = require('../createKeySymmetricEncryptDecrypt'); + const key = await sample.main(projectId, locationId, keyRingId, uuidv4()); + assert.equal(key.purpose, 'ENCRYPT_DECRYPT'); + assert.equal(key.versionTemplate.algorithm, 'GOOGLE_SYMMETRIC_ENCRYPTION'); + }); + + it('creates key versions', async () => { + const sample = require('../createKeyVersion'); + const version = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + assert.match(version.name, new RegExp(`${keyRingId}`)); + }); + + it('decrypts asymmetric data', async () => { + if (nodeMajorVersion < 12) { + return; + } + + const plaintext = 'my message'; + + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricDecryptKeyId, + 1 + ); + + const [publicKey] = await client.getPublicKey({name: versionName}); + + const ciphertextBuffer = crypto.publicEncrypt( + { + key: publicKey.pem, + oaepHash: 'sha256', + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + }, + Buffer.from(plaintext) + ); + + const sample = require('../decryptAsymmetric'); + const result = await sample.main( + projectId, + locationId, + keyRingId, + asymmetricDecryptKeyId, + 1, + ciphertextBuffer + ); + assert.equal(result, plaintext); + }); + + it('decrypts symmetric data', async () => { + const plaintext = 'my message'; + + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 1 + ); + + const [encryptResponse] = await client.encrypt({ + name: versionName, + plaintext: Buffer.from(plaintext), + }); + + const sample = require('../decryptSymmetric'); + const result = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + encryptResponse.ciphertext + ); + assert.equal(result, plaintext); + }); + + it('destroys and restores key versions', async () => { + const destroySample = require('../destroyKeyVersion'); + const destroyedVersion = await destroySample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 1 + ); + assert.equal(destroyedVersion.state, 'DESTROY_SCHEDULED'); + + const restoreSample = require('../restoreKeyVersion'); + const restoredVersion = await restoreSample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 1 + ); + // Restored keys come back as disabled + assert.equal(restoredVersion.state, 'DISABLED'); + }); + + it('disables and enables key versions', async () => { + const disableSample = require('../disableKeyVersion'); + const disabledVersion = await disableSample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 1 + ); + assert.equal(disabledVersion.state, 'DISABLED'); + + const enableSample = require('../enableKeyVersion'); + const enabledVersion = await enableSample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 1 + ); + assert.equal(enabledVersion.state, 'ENABLED'); + }); + + it('encrypts with asymmetric keys', async () => { + if (nodeMajorVersion < 12) { + return; + } + + const plaintext = 'my message'; + + const sample = require('../encryptAsymmetric'); + const ciphertextBuffer = await sample.main( + projectId, + locationId, + keyRingId, + asymmetricDecryptKeyId, + 1, + Buffer.from(plaintext) + ); + + const [decryptResponse] = await client.asymmetricDecrypt({ + name: client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricDecryptKeyId, + 1 + ), + ciphertext: ciphertextBuffer, + }); + + assert.equal(decryptResponse.plaintext.toString('utf8'), plaintext); + }); + + it('encrypts with symmetric keys', async () => { + const plaintext = 'my message'; + + const sample = require('../encryptSymmetric'); + const ciphertextBuffer = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + Buffer.from(plaintext) + ); + + const [decryptResponse] = await client.decrypt({ + name: client.cryptoKeyPath( + projectId, + locationId, + keyRingId, + symmetricKeyId + ), + ciphertext: ciphertextBuffer, + }); + + assert.equal(decryptResponse.plaintext.toString('utf8'), plaintext); + }); + + it('gets keys with labels', async () => { + const sample = require('../getKeyLabels'); + const key = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + + assert.equal(key.labels.foo, 'bar'); + assert.equal(key.labels.zip, 'zap'); + }); + + it('gets version attestations', async () => { + const sample = require('../getKeyVersionAttestation'); + const attestation = await sample.main( + projectId, + locationId, + keyRingId, + hsmKeyId, + 1 + ); + + assert.exists(attestation); + }); + + it('errors on bad attestations', async () => { + const sample = require('../getKeyVersionAttestation'); + sample + .main(projectId, locationId, keyRingId, symmetricKeyId, 1) + .then(() => { + throw new Error('expected error'); + }) + .catch(err => { + assert.match(err, new RegExp('no attestation')); + }); + }); + + it('gets public keys', async () => { + const sample = require('../getPublicKey'); + const publicKey = await sample.main( + projectId, + locationId, + keyRingId, + asymmetricDecryptKeyId, + 1 + ); + + assert.exists(publicKey); + }); + + it('adds IAM members', async () => { + const sample = require('../iamAddMember'); + const policy = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 'group:test@google.com' + ); + + let binding; + for (const b of policy.bindings) { + if (b.role === 'roles/cloudkms.cryptoKeyEncrypterDecrypter') { + binding = b; + break; + } + } + + assert.exists(binding); + assert.oneOf('group:test@google.com', binding.members); + }); + + it('get IAM policies', async () => { + const sample = require('../iamGetPolicy'); + const policy = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + + assert.exists(policy); + }); + + it('removes IAM members', async () => { + const resourceName = client.cryptoKeyPath( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + + const [policy] = await client.getIamPolicy({ + resource: resourceName, + }); + + policy.bindings.push({ + role: 'roles/cloudkms.publicKeyViewer', + members: ['group:test@google.com'], + }); + + policy.bindings.push({ + role: 'roles/cloudkms.cryptoKeyEncrypter', + members: ['group:test@google.com'], + }); + + await client.setIamPolicy({ + resource: resourceName, + policy: policy, + }); + + const sample = require('../iamRemoveMember'); + const updatedPolicy = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 'group:test@google.com' + ); + + let binding; + for (const b of updatedPolicy.bindings) { + if (b.role === 'roles/cloudkms.cryptoKeyEncrypterDecrypter') { + binding = b; + break; + } + } + + assert.notExists(binding); + }); + + it('quickstarts', async () => { + const sample = require('../quickstart'); + const keyRings = await sample.main(projectId, locationId); + + assert.isNotEmpty(keyRings); + }); + + it('signs with asymmetric keys', async () => { + if (nodeMajorVersion < 12) { + return; + } + + const message = 'my message'; + + const sample = require('../signAsymmetric'); + const signatureBuffer = await sample.main( + projectId, + locationId, + keyRingId, + asymmetricSignEcKeyId, + 1, + message + ); + + const [publicKey] = await client.getPublicKey({ + name: client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricSignEcKeyId, + 1 + ), + }); + + const verify = crypto.createVerify('SHA256'); + verify.update(message); + verify.end(); + + const verified = verify.verify(publicKey.pem, signatureBuffer); + assert.isTrue(verified); + }); + + it('adds rotation schedules', async () => { + const sample = require('../updateKeyAddRotation'); + const key = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + assert.exists(key.rotationSchedule); + assert.exists(key.nextRotationTime); + }); + + it('removes labels', async () => { + const sample = require('../updateKeyRemoveLabels'); + const key = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + assert.isEmpty(key.labels); + }); + + it('removes rotation schedules', async () => { + const sample = require('../updateKeyRemoveRotation'); + const key = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + assert.notExists(key.rotationSchedule); + assert.notExists(key.nextRotationTime); + }); + + it('sets primary version', async () => { + const sample = require('../updateKeySetPrimary'); + const key = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId, + 1 + ); + assert.exists(key.primary); + }); + + it('updates labels', async () => { + const sample = require('../updateKeyUpdateLabels'); + const key = await sample.main( + projectId, + locationId, + keyRingId, + symmetricKeyId + ); + assert.equal(key.labels.new_label, 'new_value'); + }); + + it('verifies with asymmetric EC keys', async () => { + if (nodeMajorVersion < 12) { + return; + } + + const message = 'my message'; + + const digest = crypto.createHash('sha256'); + digest.update(message); + + const [signResponse] = await client.asymmetricSign({ + name: client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricSignEcKeyId, + 1 + ), + digest: { + sha256: digest.digest(), + }, + }); + + const sample = require('../verifyAsymmetricEc'); + const verified = await sample.main( + projectId, + locationId, + keyRingId, + asymmetricSignEcKeyId, + 1, + message, + signResponse.signature + ); + + assert.isTrue(verified); + }); + + it('verifies with asymmetric RSA keys', async () => { + if (nodeMajorVersion < 12) { + return; + } + + const message = 'my message'; + + const digest = crypto.createHash('sha256'); + digest.update(message); + + const [signResponse] = await client.asymmetricSign({ + name: client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + asymmetricSignRsaKeyId, + 1 + ), + digest: { + sha256: digest.digest(), + }, + }); + + const sample = require('../verifyAsymmetricRsa'); + const verified = await sample.main( + projectId, + locationId, + keyRingId, + asymmetricSignRsaKeyId, + 1, + message, + signResponse.signature + ); + + assert.isTrue(verified); + }); +}); diff --git a/kms/updateKeyAddRotation.js b/kms/updateKeyAddRotation.js new file mode 100644 index 0000000000..d00bca8dac --- /dev/null +++ b/kms/updateKeyAddRotation.js @@ -0,0 +1,75 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key' +) { + // [START kms_update_key_add_rotation_schedule] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function updateKeyAddRotation() { + const [key] = await client.updateCryptoKey({ + cryptoKey: { + name: keyName, + + // Rotate the key every 30 days. + rotationPeriod: { + seconds: 60 * 60 * 24 * 30, + }, + + // Start the first rotation in 24 hours. + nextRotationTime: { + seconds: new Date().getTime() / 1000 + 60 * 60 * 24, + }, + }, + updateMask: { + paths: ['rotation_period', 'next_rotation_time'], + }, + }); + + console.log(`Updated rotation for: ${key.name}`); + return key; + } + + return updateKeyAddRotation(); + // [END kms_update_key_add_rotation_schedule] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/updateKeyRemoveLabels.js b/kms/updateKeyRemoveLabels.js new file mode 100644 index 0000000000..6981ea1322 --- /dev/null +++ b/kms/updateKeyRemoveLabels.js @@ -0,0 +1,66 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key' +) { + // [START kms_update_key_remove_labels] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function updateKeyRemoveLabels() { + const [key] = await client.updateCryptoKey({ + cryptoKey: { + name: keyName, + labels: null, + }, + updateMask: { + paths: ['labels'], + }, + }); + + console.log(`Removed labels from: ${key.name}`); + return key; + } + + return updateKeyRemoveLabels(); + // [END kms_update_key_remove_labels] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/updateKeyRemoveRotation.js b/kms/updateKeyRemoveRotation.js new file mode 100644 index 0000000000..fcd5ae8210 --- /dev/null +++ b/kms/updateKeyRemoveRotation.js @@ -0,0 +1,66 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key' +) { + // [START kms_update_key_remove_rotation_schedule] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function updateKeyRemoveRotation() { + const [key] = await client.updateCryptoKey({ + cryptoKey: { + name: keyName, + rotationPeriod: null, + nextRotationTime: null, + }, + updateMask: { + paths: ['rotation_period', 'next_rotation_time'], + }, + }); + + console.log(`Removed rotation for: ${key.name}`); + return key; + } + + return updateKeyRemoveRotation(); + // [END kms_update_key_remove_rotation_schedule] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/updateKeySetPrimary.js b/kms/updateKeySetPrimary.js new file mode 100644 index 0000000000..5da1768dc6 --- /dev/null +++ b/kms/updateKeySetPrimary.js @@ -0,0 +1,62 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '123' +) { + // [START kms_update_key_set_primary] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function updateKeySetPrimary() { + const [key] = await client.updateCryptoKeyPrimaryVersion({ + name: keyName, + cryptoKeyVersionId: versionId, + }); + + console.log(`Set primary to ${versionId}`); + return key; + } + + return updateKeySetPrimary(); + // [END kms_update_key_set_primary] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/updateKeyUpdateLabels.js b/kms/updateKeyUpdateLabels.js new file mode 100644 index 0000000000..2325994df3 --- /dev/null +++ b/kms/updateKeyUpdateLabels.js @@ -0,0 +1,68 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'my-project', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key' +) { + // [START kms_update_key_update_labels] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'my-project'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '123'; + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId); + + async function updateKeyUpdateLabels() { + const [key] = await client.updateCryptoKey({ + cryptoKey: { + name: keyName, + labels: { + new_label: 'new_value', + }, + }, + updateMask: { + paths: ['labels'], + }, + }); + + console.log(`Updated labels for: ${key.name}`); + return key; + } + + return updateKeyUpdateLabels(); + // [END kms_update_key_update_labels] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/verifyAsymmetricEc.js b/kms/verifyAsymmetricEc.js new file mode 100644 index 0000000000..71b6b1ae49 --- /dev/null +++ b/kms/verifyAsymmetricEc.js @@ -0,0 +1,84 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'your-project-id', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '1', + message = 'my message to verify', + signatureBuffer = Buffer.from('...') +) { + // [START kms_verify_asymmetric_signature_ec] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'your-project-id'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '1'; + // const message = 'my message to verify'; + // const signatureBuffer = Buffer.from('...'); + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function verifyAsymmetricSignatureEc() { + // Get public key + const [publicKey] = await client.getPublicKey({ + name: versionName, + }); + + // Create the verifier. The algorithm must match the algorithm of the key. + const crypto = require('crypto'); + const verify = crypto.createVerify('sha256'); + verify.update(message); + verify.end(); + + // Build the key object + const key = { + key: publicKey.pem, + }; + + // Verify the signature using the public key + const verified = verify.verify(key, signatureBuffer); + return verified; + } + + return verifyAsymmetricSignatureEc(); + // [END kms_verify_asymmetric_signature_ec] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +} diff --git a/kms/verifyAsymmetricRsa.js b/kms/verifyAsymmetricRsa.js new file mode 100644 index 0000000000..7fef55e94d --- /dev/null +++ b/kms/verifyAsymmetricRsa.js @@ -0,0 +1,85 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function main( + projectId = 'your-project-id', + locationId = 'us-east1', + keyRingId = 'my-key-ring', + keyId = 'my-key', + versionId = '1', + message = 'my message to verify', + signatureBuffer = Buffer.from('...') +) { + // [START kms_verify_asymmetric_signature_rsa] + // + // TODO(developer): Uncomment these variables before running the sample. + // + // const projectId = 'your-project-id'; + // const locationId = 'us-east1'; + // const keyRingId = 'my-key-ring'; + // const keyId = 'my-key'; + // const versionId = '1'; + // const message = 'my message to verify'; + // const signatureBuffer = Buffer.from('...'); + + // Imports the Cloud KMS library + const {KeyManagementServiceClient} = require('@google-cloud/kms'); + + // Instantiates a client + const client = new KeyManagementServiceClient(); + + // Build the key name + const versionName = client.cryptoKeyVersionPath( + projectId, + locationId, + keyRingId, + keyId, + versionId + ); + + async function verifyAsymmetricSignatureRsa() { + // Get public key + const [publicKey] = await client.getPublicKey({ + name: versionName, + }); + + // Create the verifier. The algorithm must match the algorithm of the key. + const crypto = require('crypto'); + const verify = crypto.createVerify('sha256'); + verify.update(message); + verify.end(); + + // Build the key object + const key = { + key: publicKey.pem, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + }; + + // Verify the signature using the public key + const verified = verify.verify(key, signatureBuffer); + return verified; + } + + return verifyAsymmetricSignatureRsa(); + // [END kms_verify_asymmetric_signature_rsa] +} +module.exports.main = main; + +/* c8 ignore next 4 */ +if (require.main === module) { + const args = process.argv.slice(2); + main(...args).catch(console.error); +}