@webex/internal-plugin-encryption 3.8.1-web-workers-keepalive.1 → 3.9.0-multi-llms.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/constants.js +2 -1
- package/dist/constants.js.map +1 -1
- package/dist/encryption.js +17 -1
- package/dist/encryption.js.map +1 -1
- package/dist/kms.js +21 -3
- package/dist/kms.js.map +1 -1
- package/package.json +14 -14
- package/src/constants.js +1 -0
- package/src/encryption.js +17 -0
- package/src/kms.js +27 -1
- package/test/integration/spec/encryption.js +102 -0
- package/test/unit/spec/encryption.js +72 -0
- package/test/unit/spec/kms.js +144 -3
package/dist/constants.js
CHANGED
|
@@ -4,8 +4,9 @@ var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/defi
|
|
|
4
4
|
_Object$defineProperty(exports, "__esModule", {
|
|
5
5
|
value: true
|
|
6
6
|
});
|
|
7
|
-
exports.KMS_KEY_REVOKE_FAILURE = exports.KMS_KEY_REVOKE_ERROR_STATUS = exports.KMS_KEY_REVOKE_ERROR_CODES = void 0;
|
|
7
|
+
exports.KMS_KEY_REVOKE_FAILURE = exports.KMS_KEY_REVOKE_ERROR_STATUS = exports.KMS_KEY_REVOKE_ERROR_CODES = exports.KMS_KEY_REDIRECT_ERROR_CODE = void 0;
|
|
8
8
|
var KMS_KEY_REVOKE_FAILURE = exports.KMS_KEY_REVOKE_FAILURE = 'event:kms:key:revoke:encryption:failure';
|
|
9
9
|
var KMS_KEY_REVOKE_ERROR_STATUS = exports.KMS_KEY_REVOKE_ERROR_STATUS = 405;
|
|
10
10
|
var KMS_KEY_REVOKE_ERROR_CODES = exports.KMS_KEY_REVOKE_ERROR_CODES = [405005, 405006];
|
|
11
|
+
var KMS_KEY_REDIRECT_ERROR_CODE = exports.KMS_KEY_REDIRECT_ERROR_CODE = 301002;
|
|
11
12
|
//# sourceMappingURL=constants.js.map
|
package/dist/constants.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["KMS_KEY_REVOKE_FAILURE","exports","KMS_KEY_REVOKE_ERROR_STATUS","KMS_KEY_REVOKE_ERROR_CODES"],"sources":["constants.js"],"sourcesContent":["export const KMS_KEY_REVOKE_FAILURE = 'event:kms:key:revoke:encryption:failure';\nexport const KMS_KEY_REVOKE_ERROR_STATUS = 405;\nexport const KMS_KEY_REVOKE_ERROR_CODES = [405005, 405006];\n"],"mappings":";;;;;;;AAAO,IAAMA,sBAAsB,GAAAC,OAAA,CAAAD,sBAAA,GAAG,yCAAyC;AACxE,IAAME,2BAA2B,GAAAD,OAAA,CAAAC,2BAAA,GAAG,GAAG;AACvC,IAAMC,0BAA0B,GAAAF,OAAA,CAAAE,0BAAA,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC"}
|
|
1
|
+
{"version":3,"names":["KMS_KEY_REVOKE_FAILURE","exports","KMS_KEY_REVOKE_ERROR_STATUS","KMS_KEY_REVOKE_ERROR_CODES","KMS_KEY_REDIRECT_ERROR_CODE"],"sources":["constants.js"],"sourcesContent":["export const KMS_KEY_REVOKE_FAILURE = 'event:kms:key:revoke:encryption:failure';\nexport const KMS_KEY_REVOKE_ERROR_STATUS = 405;\nexport const KMS_KEY_REVOKE_ERROR_CODES = [405005, 405006];\nexport const KMS_KEY_REDIRECT_ERROR_CODE = 301002;\n"],"mappings":";;;;;;;AAAO,IAAMA,sBAAsB,GAAAC,OAAA,CAAAD,sBAAA,GAAG,yCAAyC;AACxE,IAAME,2BAA2B,GAAAD,OAAA,CAAAC,2BAAA,GAAG,GAAG;AACvC,IAAMC,0BAA0B,GAAAF,OAAA,CAAAE,0BAAA,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC;AACnD,IAAMC,2BAA2B,GAAAH,OAAA,CAAAG,2BAAA,GAAG,MAAM"}
|
package/dist/encryption.js
CHANGED
|
@@ -74,6 +74,22 @@ var Encryption = _webexCore.WebexPlugin.extend({
|
|
|
74
74
|
});
|
|
75
75
|
});
|
|
76
76
|
},
|
|
77
|
+
/**
|
|
78
|
+
* Decrypt binary data using the supplied key uri.
|
|
79
|
+
*
|
|
80
|
+
* @param {string} kmsKeyUri - The uri of a key stored in KMS
|
|
81
|
+
* @param {string} JWE - Encrypted binary data as JWE
|
|
82
|
+
* @param {Object} options
|
|
83
|
+
* @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role
|
|
84
|
+
* @returns {Buffer} Decrypted binary data as Buffer
|
|
85
|
+
*/
|
|
86
|
+
decryptBinaryData: function decryptBinaryData(kmsKeyUri, JWE, options) {
|
|
87
|
+
return this.getKey(kmsKeyUri, options).then(function (k) {
|
|
88
|
+
return _nodeJose.default.JWE.createDecrypt(k.jwk).decrypt(JWE).then(function (result) {
|
|
89
|
+
return result.payload;
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
},
|
|
77
93
|
/**
|
|
78
94
|
* Validate and initiate a Download request for requested file
|
|
79
95
|
* @param {Object} fileUrl - Plaintext
|
|
@@ -239,7 +255,7 @@ var Encryption = _webexCore.WebexPlugin.extend({
|
|
|
239
255
|
}));
|
|
240
256
|
});
|
|
241
257
|
},
|
|
242
|
-
version: "3.
|
|
258
|
+
version: "3.9.0-multi-llms.1"
|
|
243
259
|
});
|
|
244
260
|
|
|
245
261
|
/**
|
package/dist/encryption.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_events","require","_url","_interopRequireDefault","_webexCore","_common","_nodeJose","_nodeScr","_ensureBuffer","_kms","ownKeys","e","r","t","_Object$keys2","_Object$getOwnPropertySymbols","o","filter","_Object$getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","Object","forEach","_defineProperty2","default","_Object$getOwnPropertyDescriptors","_Object$defineProperties","_Object$defineProperty","Encryption","WebexPlugin","extend","children","kms","KMS","namespace","processKmsMessageEvent","event","decryptBinary","scr","buffer","ensureBuffer","then","b","byteLength","_promise","reject","Error","decrypt","decryptScr","key","cipherScr","options","getKey","k","SCR","fromJWE","jwk","decryptText","ciphertext","jose","JWE","createDecrypt","result","plaintext","toString","download","fileUrl","_this","shunt","EventEmitter","promise","_fetchDownloadUrl","useFileService","uri","method","responseType","ret","request","transferEvents","res","body","proxyEvents","_this2","logger","info","process","env","NODE_ENV","includes","resolve","startsWith","error","inputBody","endpoints","endpointUrl","url","parse","protocol","pathname","format","params","_keys","indexOf","allow","warn","catch","err","concat","encryptBinary","file","create","encrypt","cdata","encryptScr","loc","toJWE","encryptText","_this3","createEncrypt","config","joseOptions","header","alg","reference","final","_this4","_ref","undefined","onBehalfOf","asKey","storageKey","unboundedStorage","get","keyString","JSON","keyObject","fetchKey","tap","put","_stringify","replacer","version","v","json","toJSON","_default","exports"],"sources":["encryption.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {EventEmitter} from 'events';\nimport url from 'url';\n\nimport {WebexPlugin} from '@webex/webex-core';\nimport {proxyEvents, tap, transferEvents} from '@webex/common';\nimport jose from 'node-jose';\nimport SCR from 'node-scr';\n\nimport ensureBuffer from './ensure-buffer';\nimport KMS from './kms';\n\nconst Encryption = WebexPlugin.extend({\n children: {\n kms: KMS,\n },\n\n namespace: 'Encryption',\n\n processKmsMessageEvent(event) {\n return this.kms.processKmsMessageEvent(event);\n },\n\n decryptBinary(scr, buffer) {\n return ensureBuffer(buffer).then((b) => {\n /* istanbul ignore if */\n if (buffer.length === 0 || buffer.byteLength === 0) {\n return Promise.reject(new Error('Attempted to decrypt zero-length buffer'));\n }\n\n return scr.decrypt(b);\n });\n },\n\n /**\n * Decrypt a SCR (Secure Content Resource) using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {Object} cipherScr - An encrypted SCR\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {Object} Decrypted SCR\n */\n decryptScr(key, cipherScr, options) {\n return this.getKey(key, options).then((k) => SCR.fromJWE(k.jwk, cipherScr));\n },\n\n /**\n * Decrypt text using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {string} ciphertext - Encrypted text\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Decrypted plaintext\n */\n decryptText(key, ciphertext, options) {\n return this.getKey(key, options).then((k) =>\n jose.JWE.createDecrypt(k.jwk)\n .decrypt(ciphertext)\n .then((result) => result.plaintext.toString())\n );\n },\n\n /**\n * Validate and initiate a Download request for requested file\n * @param {Object} fileUrl - Plaintext\n * @param {Object} scr - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise}\n */\n download(fileUrl, scr, options) {\n /* istanbul ignore if */\n if (!fileUrl || !scr) {\n return Promise.reject(new Error('`scr` and `fileUrl` are required'));\n }\n\n const shunt = new EventEmitter();\n const promise = this._fetchDownloadUrl(fileUrl, {useFileService: true, ...options})\n .then((uri) => {\n // eslint-disable-next-line no-shadow\n const options = {\n method: 'GET',\n uri,\n responseType: 'buffer',\n };\n\n const ret = this.request(options);\n\n transferEvents('progress', options.download, shunt);\n\n return ret;\n })\n .then((res) => this.decryptBinary(scr, res.body));\n\n proxyEvents(shunt, promise);\n\n return promise;\n },\n\n /**\n * Fetch Download URL for the requested file\n * @param {Object} fileUrl - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise} url of the downloadable file\n */\n _fetchDownloadUrl(fileUrl, options) {\n this.logger.info('encryption: retrieving download url for encrypted file');\n\n if (process.env.NODE_ENV !== 'production' && fileUrl.includes('localhost')) {\n this.logger.info(\n 'encryption: bypassing webex files because this looks to be a test file on localhost'\n );\n\n return Promise.resolve(fileUrl);\n }\n\n if (options?.useFileService === false) {\n if (!fileUrl.startsWith('https://')) {\n this.logger.error('encryption: direct file URLs must use HTTPS');\n\n return Promise.reject(new Error('Direct file URLs must use HTTPS'));\n }\n\n return Promise.resolve(fileUrl);\n }\n\n const inputBody = {\n endpoints: [fileUrl],\n };\n const endpointUrl = url.parse(fileUrl);\n\n // hardcode the url to use 'https' and the file service '/v1/download/endpoints' api\n endpointUrl.protocol = 'https';\n endpointUrl.pathname = '/v1/download/endpoints';\n\n return this.request({\n method: 'POST',\n uri: url.format(endpointUrl),\n body:\n options?.params && Object.keys(options.params).indexOf('allow') > -1\n ? {\n ...inputBody,\n allow: options.params.allow,\n }\n : inputBody,\n })\n .then((res) => {\n // eslint-disable-next-line no-shadow\n const url = res.body.endpoints[fileUrl];\n\n if (!url) {\n this.logger.warn(\n 'encryption: could not determine download url for `fileUrl`; attempting to download `fileUrl` directly'\n );\n\n return fileUrl;\n }\n this.logger.info('encryption: retrieved download url for encrypted file');\n\n return url;\n })\n .catch((err) => {\n this.logger.warn(\n `encryption: ${err} could not determine download url for ${fileUrl}; attempting to download ${fileUrl} directly`\n );\n\n return fileUrl;\n });\n },\n\n encryptBinary(file) {\n return ensureBuffer(file).then((buffer) =>\n SCR.create().then((scr) =>\n scr\n .encrypt(buffer)\n .then(ensureBuffer)\n // eslint-disable-next-line max-nested-callbacks\n .then((cdata) => ({scr, cdata}))\n )\n );\n },\n\n /**\n * Encrypt a SCR (Secure Content Resource) using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {Object} scr - SCRObject\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Encrypted SCR\n */\n encryptScr(key, scr, options) {\n /* istanbul ignore if */\n if (!scr.loc) {\n return Promise.reject(new Error('Cannot encrypt `scr` without first setting `loc`'));\n }\n\n return this.getKey(key, options).then((k) => scr.toJWE(k.jwk));\n },\n\n /**\n * Encrypt plaintext using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {string} plaintext\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Encrypted text\n */\n encryptText(key, plaintext, options) {\n return this.getKey(key, options).then((k) =>\n jose.JWE.createEncrypt(this.config.joseOptions, {\n key: k.jwk,\n header: {\n alg: 'dir',\n },\n reference: null,\n }).final(plaintext, 'utf8')\n );\n },\n\n /**\n * Fetch the key associated with the supplied KMS uri.\n *\n * @param {string} uri - The uri of a key stored in KMS\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Key\n */\n getKey(uri, {onBehalfOf} = {}) {\n if (uri.jwk) {\n return this.kms.asKey(uri);\n }\n\n let storageKey = uri;\n\n if (onBehalfOf) {\n storageKey += `/onBehalfOf/${onBehalfOf}`;\n }\n\n return this.unboundedStorage\n .get(storageKey)\n .then((keyString) => JSON.parse(keyString))\n .then((keyObject) => this.kms.asKey(keyObject))\n .catch(() =>\n this.kms\n .fetchKey({uri, onBehalfOf})\n .then(tap((key) => this.unboundedStorage.put(storageKey, JSON.stringify(key, replacer))))\n );\n },\n});\n\n/**\n * JSON.stringify replacer that ensures private key data is serialized.\n * @param {string} k\n * @param {mixed} v\n * @returns {mixed}\n */\nfunction replacer(k, v) {\n if (k === 'jwk') {\n // note: this[k] and v may be different representations of the same value\n // eslint-disable-next-line no-invalid-this\n const json = this[k].toJSON(true);\n\n return json;\n }\n\n return v;\n}\n\nexport default Encryption;\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,IAAA,GAAAC,sBAAA,CAAAF,OAAA;AAEA,IAAAG,UAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,SAAA,GAAAH,sBAAA,CAAAF,OAAA;AACA,IAAAM,QAAA,GAAAJ,sBAAA,CAAAF,OAAA;AAEA,IAAAO,aAAA,GAAAL,sBAAA,CAAAF,OAA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C8F,SAAS;MAAA,OAAKV,MAAI,CAAC7F,GAAG,CAACiG,KAAK,CAACM,SAAS,CAAC;IAAA,EAAC,CAC9C9B,KAAK,CAAC;MAAA,OACLoB,MAAI,CAAC7F,GAAG,CACLwG,QAAQ,CAAC;QAAC/D,GAAG,EAAHA,GAAG;QAAEuD,UAAU,EAAVA;MAAU,CAAC,CAAC,CAC3BvF,IAAI,CAAC,IAAAgG,WAAG,EAAC,UAACxF,GAAG;QAAA,OAAK4E,MAAI,CAACM,gBAAgB,CAACO,GAAG,CAACR,UAAU,EAAE,IAAAS,UAAA,CAAAnH,OAAA,EAAeyB,GAAG,EAAE2F,QAAQ,CAAC,CAAC;MAAA,EAAC,CAAC;IAAA,CAC7F,CAAC;EACL,CAAC;EAAAC,OAAA;AACH,CAAC,CAAC;;AAEF;AACA;AACA;AACA;AACA;AACA;AACA,SAASD,QAAQA,CAACvF,CAAC,EAAEyF,CAAC,EAAE;EACtB,IAAIzF,CAAC,KAAK,KAAK,EAAE;IACf;IACA;IACA,IAAM0F,IAAI,GAAG,IAAI,CAAC1F,CAAC,CAAC,CAAC2F,MAAM,CAAC,IAAI,CAAC;IAEjC,OAAOD,IAAI;EACb;EAEA,OAAOD,CAAC;AACV;AAAC,IAAAG,QAAA,GAAAC,OAAA,CAAA1H,OAAA,GAEcI,UAAU"}
|
|
1
|
+
{"version":3,"names":["_events","require","_url","_interopRequireDefault","_webexCore","_common","_nodeJose","_nodeScr","_ensureBuffer","_kms","ownKeys","e","r","t","_Object$keys2","_Object$getOwnPropertySymbols","o","filter","_Object$getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","Object","forEach","_defineProperty2","default","_Object$getOwnPropertyDescriptors","_Object$defineProperties","_Object$defineProperty","Encryption","WebexPlugin","extend","children","kms","KMS","namespace","processKmsMessageEvent","event","decryptBinary","scr","buffer","ensureBuffer","then","b","byteLength","_promise","reject","Error","decrypt","decryptScr","key","cipherScr","options","getKey","k","SCR","fromJWE","jwk","decryptText","ciphertext","jose","JWE","createDecrypt","result","plaintext","toString","decryptBinaryData","kmsKeyUri","payload","download","fileUrl","_this","shunt","EventEmitter","promise","_fetchDownloadUrl","useFileService","uri","method","responseType","ret","request","transferEvents","res","body","proxyEvents","_this2","logger","info","process","env","NODE_ENV","includes","resolve","startsWith","error","inputBody","endpoints","endpointUrl","url","parse","protocol","pathname","format","params","_keys","indexOf","allow","warn","catch","err","concat","encryptBinary","file","create","encrypt","cdata","encryptScr","loc","toJWE","encryptText","_this3","createEncrypt","config","joseOptions","header","alg","reference","final","_this4","_ref","undefined","onBehalfOf","asKey","storageKey","unboundedStorage","get","keyString","JSON","keyObject","fetchKey","tap","put","_stringify","replacer","version","v","json","toJSON","_default","exports"],"sources":["encryption.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {EventEmitter} from 'events';\nimport url from 'url';\n\nimport {WebexPlugin} from '@webex/webex-core';\nimport {proxyEvents, tap, transferEvents} from '@webex/common';\nimport jose from 'node-jose';\nimport SCR from 'node-scr';\n\nimport ensureBuffer from './ensure-buffer';\nimport KMS from './kms';\n\nconst Encryption = WebexPlugin.extend({\n children: {\n kms: KMS,\n },\n\n namespace: 'Encryption',\n\n processKmsMessageEvent(event) {\n return this.kms.processKmsMessageEvent(event);\n },\n\n decryptBinary(scr, buffer) {\n return ensureBuffer(buffer).then((b) => {\n /* istanbul ignore if */\n if (buffer.length === 0 || buffer.byteLength === 0) {\n return Promise.reject(new Error('Attempted to decrypt zero-length buffer'));\n }\n\n return scr.decrypt(b);\n });\n },\n\n /**\n * Decrypt a SCR (Secure Content Resource) using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {Object} cipherScr - An encrypted SCR\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {Object} Decrypted SCR\n */\n decryptScr(key, cipherScr, options) {\n return this.getKey(key, options).then((k) => SCR.fromJWE(k.jwk, cipherScr));\n },\n\n /**\n * Decrypt text using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {string} ciphertext - Encrypted text\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Decrypted plaintext\n */\n decryptText(key, ciphertext, options) {\n return this.getKey(key, options).then((k) =>\n jose.JWE.createDecrypt(k.jwk)\n .decrypt(ciphertext)\n .then((result) => result.plaintext.toString())\n );\n },\n\n /**\n * Decrypt binary data using the supplied key uri.\n *\n * @param {string} kmsKeyUri - The uri of a key stored in KMS\n * @param {string} JWE - Encrypted binary data as JWE\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {Buffer} Decrypted binary data as Buffer\n */\n decryptBinaryData(kmsKeyUri, JWE, options) {\n return this.getKey(kmsKeyUri, options).then((k) =>\n jose.JWE.createDecrypt(k.jwk)\n .decrypt(JWE)\n .then((result) => result.payload)\n );\n },\n\n /**\n * Validate and initiate a Download request for requested file\n * @param {Object} fileUrl - Plaintext\n * @param {Object} scr - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise}\n */\n download(fileUrl, scr, options) {\n /* istanbul ignore if */\n if (!fileUrl || !scr) {\n return Promise.reject(new Error('`scr` and `fileUrl` are required'));\n }\n\n const shunt = new EventEmitter();\n const promise = this._fetchDownloadUrl(fileUrl, {useFileService: true, ...options})\n .then((uri) => {\n // eslint-disable-next-line no-shadow\n const options = {\n method: 'GET',\n uri,\n responseType: 'buffer',\n };\n\n const ret = this.request(options);\n\n transferEvents('progress', options.download, shunt);\n\n return ret;\n })\n .then((res) => this.decryptBinary(scr, res.body));\n\n proxyEvents(shunt, promise);\n\n return promise;\n },\n\n /**\n * Fetch Download URL for the requested file\n * @param {Object} fileUrl - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise} url of the downloadable file\n */\n _fetchDownloadUrl(fileUrl, options) {\n this.logger.info('encryption: retrieving download url for encrypted file');\n\n if (process.env.NODE_ENV !== 'production' && fileUrl.includes('localhost')) {\n this.logger.info(\n 'encryption: bypassing webex files because this looks to be a test file on localhost'\n );\n\n return Promise.resolve(fileUrl);\n }\n\n if (options?.useFileService === false) {\n if (!fileUrl.startsWith('https://')) {\n this.logger.error('encryption: direct file URLs must use HTTPS');\n\n return Promise.reject(new Error('Direct file URLs must use HTTPS'));\n }\n\n return Promise.resolve(fileUrl);\n }\n\n const inputBody = {\n endpoints: [fileUrl],\n };\n const endpointUrl = url.parse(fileUrl);\n\n // hardcode the url to use 'https' and the file service '/v1/download/endpoints' api\n endpointUrl.protocol = 'https';\n endpointUrl.pathname = '/v1/download/endpoints';\n\n return this.request({\n method: 'POST',\n uri: url.format(endpointUrl),\n body:\n options?.params && Object.keys(options.params).indexOf('allow') > -1\n ? {\n ...inputBody,\n allow: options.params.allow,\n }\n : inputBody,\n })\n .then((res) => {\n // eslint-disable-next-line no-shadow\n const url = res.body.endpoints[fileUrl];\n\n if (!url) {\n this.logger.warn(\n 'encryption: could not determine download url for `fileUrl`; attempting to download `fileUrl` directly'\n );\n\n return fileUrl;\n }\n this.logger.info('encryption: retrieved download url for encrypted file');\n\n return url;\n })\n .catch((err) => {\n this.logger.warn(\n `encryption: ${err} could not determine download url for ${fileUrl}; attempting to download ${fileUrl} directly`\n );\n\n return fileUrl;\n });\n },\n\n encryptBinary(file) {\n return ensureBuffer(file).then((buffer) =>\n SCR.create().then((scr) =>\n scr\n .encrypt(buffer)\n .then(ensureBuffer)\n // eslint-disable-next-line max-nested-callbacks\n .then((cdata) => ({scr, cdata}))\n )\n );\n },\n\n /**\n * Encrypt a SCR (Secure Content Resource) using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {Object} scr - SCRObject\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Encrypted SCR\n */\n encryptScr(key, scr, options) {\n /* istanbul ignore if */\n if (!scr.loc) {\n return Promise.reject(new Error('Cannot encrypt `scr` without first setting `loc`'));\n }\n\n return this.getKey(key, options).then((k) => scr.toJWE(k.jwk));\n },\n\n /**\n * Encrypt plaintext using the supplied key uri.\n *\n * @param {string} key - The uri of a key stored in KMS\n * @param {string} plaintext\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Encrypted text\n */\n encryptText(key, plaintext, options) {\n return this.getKey(key, options).then((k) =>\n jose.JWE.createEncrypt(this.config.joseOptions, {\n key: k.jwk,\n header: {\n alg: 'dir',\n },\n reference: null,\n }).final(plaintext, 'utf8')\n );\n },\n\n /**\n * Fetch the key associated with the supplied KMS uri.\n *\n * @param {string} uri - The uri of a key stored in KMS\n * @param {Object} options\n * @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role\n * @returns {string} Key\n */\n getKey(uri, {onBehalfOf} = {}) {\n if (uri.jwk) {\n return this.kms.asKey(uri);\n }\n\n let storageKey = uri;\n\n if (onBehalfOf) {\n storageKey += `/onBehalfOf/${onBehalfOf}`;\n }\n\n return this.unboundedStorage\n .get(storageKey)\n .then((keyString) => JSON.parse(keyString))\n .then((keyObject) => this.kms.asKey(keyObject))\n .catch(() =>\n this.kms\n .fetchKey({uri, onBehalfOf})\n .then(tap((key) => this.unboundedStorage.put(storageKey, JSON.stringify(key, replacer))))\n );\n },\n});\n\n/**\n * JSON.stringify replacer that ensures private key data is serialized.\n * @param {string} k\n * @param {mixed} v\n * @returns {mixed}\n */\nfunction replacer(k, v) {\n if (k === 'jwk') {\n // note: this[k] and v may be different representations of the same value\n // eslint-disable-next-line no-invalid-this\n const json = this[k].toJSON(true);\n\n return json;\n }\n\n return v;\n}\n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C,CAAC;;AAEF;AACA;AACA;AACA;AACA;AACA;AACA,SAASD,QAAQA,CAAC1F,CAAC,EAAE4F,CAAC,EAAE;EACtB,IAAI5F,CAAC,KAAK,KAAK,EAAE;IACf;IACA;IACA,IAAM6F,IAAI,GAAG,IAAI,CAAC7F,CAAC,CAAC,CAAC8F,MAAM,CAAC,IAAI,CAAC;IAEjC,OAAOD,IAAI;EACb;EAEA,OAAOD,CAAC;AACV;AAAC,IAAAG,QAAA,GAAAC,OAAA,CAAA7H,OAAA,GAEcI,UAAU"}
|
package/dist/kms.js
CHANGED
|
@@ -27,6 +27,7 @@ var _lodash = require("lodash");
|
|
|
27
27
|
var _uuid = _interopRequireDefault(require("uuid"));
|
|
28
28
|
var _kmsBatcher = _interopRequireWildcard(require("./kms-batcher"));
|
|
29
29
|
var _kmsCertificateValidation = _interopRequireWildcard(require("./kms-certificate-validation"));
|
|
30
|
+
var _constants = require("./constants");
|
|
30
31
|
var _dec, _obj;
|
|
31
32
|
/*!
|
|
32
33
|
* Copyright (c) 2015-2024 Cisco Systems, Inc. See LICENSE file.
|
|
@@ -298,6 +299,7 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
298
299
|
* @param {UUID} options.assignedOrgId the orgId
|
|
299
300
|
* @param {string} options.customerMasterKey the master key
|
|
300
301
|
* @param {string} options.customerMasterKeyBackup the master key backup
|
|
302
|
+
* @param {string} options.customerMasterKeyRole the optional role associated with customerMasterKey
|
|
301
303
|
* @param {boolean} options.awsKms enable amazon aws keys
|
|
302
304
|
* @returns {Promise.<UploadCmkResponse>} response of upload CMK api
|
|
303
305
|
*/
|
|
@@ -308,7 +310,9 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
308
310
|
_ref9$awsKms = _ref9.awsKms,
|
|
309
311
|
awsKms = _ref9$awsKms === void 0 ? false : _ref9$awsKms,
|
|
310
312
|
_ref9$customerMasterK = _ref9.customerMasterKeyBackup,
|
|
311
|
-
customerMasterKeyBackup = _ref9$customerMasterK === void 0 ? undefined : _ref9$customerMasterK
|
|
313
|
+
customerMasterKeyBackup = _ref9$customerMasterK === void 0 ? undefined : _ref9$customerMasterK,
|
|
314
|
+
_ref9$customerMasterK2 = _ref9.customerMasterKeyRole,
|
|
315
|
+
customerMasterKeyRole = _ref9$customerMasterK2 === void 0 ? undefined : _ref9$customerMasterK2;
|
|
312
316
|
this.logger.info('kms: upload customer master key for byok');
|
|
313
317
|
return this.request({
|
|
314
318
|
method: 'create',
|
|
@@ -316,7 +320,8 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
316
320
|
assignedOrgId: assignedOrgId,
|
|
317
321
|
customerMasterKey: customerMasterKey,
|
|
318
322
|
requestId: _uuid.default.v4(),
|
|
319
|
-
customerMasterKeyBackup: awsKms ? customerMasterKeyBackup : undefined
|
|
323
|
+
customerMasterKeyBackup: awsKms ? customerMasterKeyBackup : undefined,
|
|
324
|
+
customerMasterKeyRole: awsKms ? customerMasterKeyRole : undefined
|
|
320
325
|
}).then(function (res) {
|
|
321
326
|
_this8.logger.info('kms: finish to upload customer master key');
|
|
322
327
|
return res;
|
|
@@ -448,6 +453,19 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
448
453
|
}, {
|
|
449
454
|
onBehalfOf: onBehalfOf
|
|
450
455
|
}).then(function (res) {
|
|
456
|
+
// Handle redirect for migrated KRO, Key or Auth
|
|
457
|
+
if (res.errorCode === _constants.KMS_KEY_REDIRECT_ERROR_CODE && res.redirectUri) {
|
|
458
|
+
_this13.logger.info('kms: handling redirect for migrated resource', res.redirectUri);
|
|
459
|
+
return _this13.request({
|
|
460
|
+
method: 'retrieve',
|
|
461
|
+
uri: res.redirectUri
|
|
462
|
+
}, {
|
|
463
|
+
onBehalfOf: onBehalfOf
|
|
464
|
+
}).then(function (redirectRes) {
|
|
465
|
+
_this13.logger.info('kms: fetched key from redirect');
|
|
466
|
+
return _this13.asKey(redirectRes.key);
|
|
467
|
+
});
|
|
468
|
+
}
|
|
451
469
|
_this13.logger.info('kms: fetched key');
|
|
452
470
|
return _this13.asKey(res.key);
|
|
453
471
|
});
|
|
@@ -809,7 +827,7 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
809
827
|
context.ephemeralKey = originalContext.ephemeralKey;
|
|
810
828
|
return context;
|
|
811
829
|
},
|
|
812
|
-
version: "3.
|
|
830
|
+
version: "3.9.0-multi-llms.1"
|
|
813
831
|
}, ((0, _applyDecoratedDescriptor2.default)(_obj, "fetchKey", [_dec], (0, _getOwnPropertyDescriptor.default)(_obj, "fetchKey"), _obj), (0, _applyDecoratedDescriptor2.default)(_obj, "_getContext", [_common.oneFlight], (0, _getOwnPropertyDescriptor.default)(_obj, "_getContext"), _obj)), _obj)));
|
|
814
832
|
var _default = exports.default = KMS;
|
|
815
833
|
//# sourceMappingURL=kms.js.map
|
package/dist/kms.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_querystring","_interopRequireDefault","require","_util","_commonTimers","_common","_webexCore","_nodeKms","_nodeJose","_lodash","_uuid","_kmsBatcher","_interopRequireWildcard","_kmsCertificateValidation","_dec","_obj","_getRequireWildcardCache","e","_WeakMap2","r","t","__esModule","_typeof","default","has","get","n","__proto__","a","_Object$defineProperty","_Object$getOwnPropertyDescriptor2","u","Object","prototype","hasOwnProperty","call","i","set","contexts","_weakMap","kmsDetails","partialContexts","consoleDebug","KMS","WebexPlugin","extend","oneFlight","keyFactory","_ref","uri","onBehalfOf","concat","namespace","children","batcher","KMSBatcher","bindKey","_ref2","_this","kro","kroUri","key","keyUri","logger","info","_promise","reject","Error","request","method","resourceUri","then","res","createResource","_ref3","_this2","userIds","keyUris","keys","reduce","uris","k","push","length","resource","addAuthorization","_ref4","_this3","authIds","authorizations","listAuthorizations","_ref5","_this4","removeAuthorization","_ref6","_this5","authId","userId","querystring","stringify","createUnboundKeys","_ref7","_this6","count","all","map","asKey","fetchPublicKey","_ref8","_this7","assignedOrgId","publicKey","uploadCustomerMasterKey","_ref9","_this8","customerMasterKey","_ref9$awsKms","awsKms","_ref9$customerMasterK","customerMasterKeyBackup","undefined","requestId","uuid","v4","listAllCustomerMasterKey","_ref10","_this9","_ref10$awsKms","changeCustomerMasterKeyState","_ref11","_this10","keyId","keyState","deleteAllCustomerMasterKeys","_ref12","_this11","_ref12$awsKms","useGlobalMasterKey","_ref13","_this12","fetchKey","_ref14","_this13","ping","jose","JWK","jwk","prepareRequest","payload","_this14","isECDHRequest","includes","resolve","_getContext","context","req","Request","requestContext","_contextOnBehalfOf","wrap","serverKey","process","env","NODE_ENV","util","inspect","omit","JSON","parse","_stringify","depth","processKmsMessageEvent","event","_this15","encryption","kmsMessages","kmsMessage","index","_isECDHEMessage","isECDHMessage","Response","unwrap","catch","reason","error","stack","decryptKmsMessage","body","_getKMSStaticPubKey","kmsStaticPubKey","fields","split","header","base64url","decode","kid","_this16","_ref15","arguments","timeout","config","kmsInitialTimeout","webex","internal","mercury","connect","TIMEOUT_SYMBOL","status","statusCode","message","match","warn","KMSError","trigger","ecdhMaxTimeout","nextTimeout","kmsMaxTimeout","delete","_getAuthorization","credentials","getUserToken","token","access_token","_this17","promise","_prepareContext","expiresIn","ephemeralKey","expirationDate","_now","safeSetTimeout","_ref16","_ref17","_slicedToArray2","authorization","clientInfo","credential","bearer","_getKMSCluster","_getKMSDetails","_ref18","kmsCluster","_this18","details","service","device","rsaPublicKey","_ref19","_this19","Context","validateKMS","caroots","_ref20","_ref21","clientId","url","serverInfo","createECDHKey","localECDHKey","_ref22","_ref23","cluster","toJSON","deriveEphemeralKey","originalContext","version","_applyDecoratedDescriptor2","_getOwnPropertyDescriptor","_default","exports"],"sources":["kms.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2024 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport querystring from 'querystring';\nimport util from 'util';\n\nimport {safeSetTimeout} from '@webex/common-timers';\nimport {oneFlight} from '@webex/common';\nimport {WebexPlugin} from '@webex/webex-core';\nimport {Context, Request, Response} from 'node-kms';\nimport jose from 'node-jose';\nimport {omit} from 'lodash';\nimport uuid from 'uuid';\n\nimport KMSBatcher, {TIMEOUT_SYMBOL} from './kms-batcher';\nimport validateKMS, {KMSError} from './kms-certificate-validation';\n\nconst contexts = new WeakMap();\nconst kmsDetails = new WeakMap();\nconst partialContexts = new WeakMap();\n\nconst consoleDebug = require('debug')('kms');\n\n/**\n * @class\n */\nconst KMS = WebexPlugin.extend({\n namespace: 'Encryption',\n\n children: {\n batcher: KMSBatcher,\n },\n\n /**\n * Binds a key to a resource\n * @param {Object} options\n * @param {KMSResourceObject} options.kro\n * @param {string} options.kroUri\n * @param {Key} options.key\n * @param {string} options.keyUri\n * @returns {Promise<Key>}\n */\n bindKey({kro, kroUri, key, keyUri}) {\n kroUri = kroUri || kro.uri;\n keyUri = keyUri || key.uri;\n\n this.logger.info('kms: binding key to resource');\n\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n /* istanbul ignore if */\n if (!keyUri) {\n return Promise.reject(new Error('`key` or `keyUri` is required'));\n }\n\n return this.request({\n method: 'update',\n resourceUri: kroUri,\n uri: keyUri,\n }).then((res) => {\n this.logger.info('kms: bound key to resource');\n\n return res.key;\n });\n },\n\n /**\n * Creates a new KMS Resource\n * @param {Object} options\n * @param {Array<string>} options.userIds\n * @param {Array<string>} options.keyUris\n * @param {Key} options.key\n * @param {Array<Keys>} options.keys\n * @returns {Promise<KMSResourceObject>}\n */\n createResource({userIds, keyUris, key, keys}) {\n keyUris = keyUris || [];\n /* istanbul ignore if */\n if (keys) {\n keyUris = keys.reduce((uris, k) => {\n uris.push(k.uri);\n\n return uris;\n }, keyUris);\n }\n\n /* istanbul ignore else */\n if (key) {\n keyUris.push(key.uri);\n }\n\n /* istanbul ignore if */\n if (keyUris.length === 0) {\n return Promise.reject(new Error('Cannot create KMS Resource without at least one keyUri'));\n }\n\n this.logger.info('kms: creating resource');\n\n return this.request({\n method: 'create',\n uri: '/resources',\n userIds,\n keyUris,\n }).then((res) => {\n this.logger.info('kms: created resource');\n\n return res.resource;\n });\n },\n\n /**\n * Authorizes a user or KRO to a KRO\n * @param {Object} options\n * @param {Array<string>} options.userIds\n * @param {Array<string>} options.authIds interchangable with userIds\n * @param {KMSResourceObject} options.kro the target kro\n * @param {string} options.kroUri\n * @returns {Promise<KMSAuthorizationObject>}\n */\n addAuthorization({userIds, authIds, kro, kroUri}) {\n userIds = userIds || [];\n kroUri = kroUri || kro.uri;\n\n if (authIds) {\n userIds = userIds.concat(authIds);\n }\n\n /* istanbul ignore if */\n if (userIds.length === 0) {\n return Promise.reject(new Error('Cannot add authorization without userIds or authIds'));\n }\n\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n this.logger.info('kms: adding authorization to kms resource');\n\n return this.request({\n method: 'create',\n uri: '/authorizations',\n resourceUri: kroUri,\n userIds,\n }).then((res) => {\n this.logger.info('kms: added authorization');\n\n return res.authorizations;\n });\n },\n\n /**\n * Retrieve a list of users that have been authorized to the KRO\n * @param {Object} options\n * @param {KMSResourceObject} options.kro the target kro\n * @param {string} options.kroUri\n * @returns {Array<authId>}\n */\n listAuthorizations({kro, kroUri}) {\n kroUri = kroUri || kro.uri;\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n return this.request({\n method: 'retrieve',\n uri: `${kroUri}/authorizations`,\n }).then((res) => {\n this.logger.info('kms: retrieved authorization list');\n\n return res.authorizations;\n });\n },\n\n /**\n * Deauthorizes a user or KRO from a KRO\n * @param {Object} options\n * @param {string} options.userId\n * @param {string} options.authId interchangable with userIds\n * @param {KMSResourceObject} options.kro the target kro\n * @param {string} options.kroUri\n * @returns {Promise<KMSAuthorizationObject>}\n */\n removeAuthorization({authId, userId, kro, kroUri}) {\n authId = authId || userId;\n kroUri = kroUri || kro.uri;\n\n /* istanbul ignore if */\n if (!authId) {\n return Promise.reject(new Error('Cannot remove authorization without authId'));\n }\n\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n this.logger.info('kms: removing authorization from kms resource');\n\n return this.request({\n method: 'delete',\n uri: `${kroUri}/authorizations?${querystring.stringify({authId})}`,\n }).then((res) => {\n this.logger.info('kms: removed authorization');\n\n return res.authorizations;\n });\n },\n\n /**\n * Requests `count` unbound keys from the kms\n * @param {Object} options\n * @param {Number} options.count\n * @returns {Array<Key>}\n */\n createUnboundKeys({count}) {\n this.logger.info(`kms: request ${count} unbound keys`);\n\n /* istanbul ignore if */\n if (!count) {\n return Promise.reject(new Error('`options.count` is required'));\n }\n\n return this.request({\n method: 'create',\n uri: '/keys',\n count,\n }).then((res) => {\n this.logger.info('kms: received unbound keys');\n\n return Promise.all(res.keys.map(this.asKey));\n });\n },\n\n /**\n * @typedef {Object} FetchPublicKeyResponse\n * @property {number} status 200,400(Bad Request: Request payload missing info),404(Not Found: HSM Public Key not found),501(Not Implemented: This KMS does not support BYOK),502(Bad Gateway: KMS could not communicate with HSM)\n * @property {UUID} requestId this is should be unique, used for debug.\n * @property {string} publicKey\n */\n /**\n * get public key from kms\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @returns {Promise.<FetchPublicKeyResponse>} response of get public key api\n */\n fetchPublicKey({assignedOrgId}) {\n this.logger.info('kms: fetch public key for byok');\n\n return this.request({\n method: 'retrieve',\n uri: '/publicKey',\n assignedOrgId,\n }).then((res) => {\n this.logger.info('kms: received public key');\n\n return res.publicKey;\n });\n },\n\n /**\n * @typedef {Object} UploadCmkResponse\n * @property {number} status\n * @property {UUID} requestId\n * @property {string} uri\n * @property {string} keysState\n */\n /**\n * upload master key for one org.\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @param {string} options.customerMasterKey the master key\n * @param {string} options.customerMasterKeyBackup the master key backup\n * @param {boolean} options.awsKms enable amazon aws keys\n * @returns {Promise.<UploadCmkResponse>} response of upload CMK api\n */\n uploadCustomerMasterKey({assignedOrgId, customerMasterKey, awsKms = false, customerMasterKeyBackup = undefined}) {\n this.logger.info('kms: upload customer master key for byok');\n\n return this.request({\n method: 'create',\n uri: awsKms ? '/awsKmsCmk' : '/cmk',\n assignedOrgId,\n customerMasterKey,\n requestId: uuid.v4(),\n customerMasterKeyBackup: awsKms ? customerMasterKeyBackup : undefined,\n }).then((res) => {\n this.logger.info('kms: finish to upload customer master key');\n\n return res;\n });\n },\n\n /**\n * get all customer master keys for one org.\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @param {boolean} options.awsKms enable amazon aws keys\n * @returns {Promise.<ActivateCmkResponse>} response of list CMKs api\n */\n listAllCustomerMasterKey({assignedOrgId, awsKms = false}) {\n this.logger.info('kms: get all customer master keys for byok');\n\n return this.request({\n method: 'retrieve',\n uri: awsKms ? '/awsKmsCmk' : '/cmk',\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to get all customer master keys');\n\n return res;\n });\n },\n\n /**\n * @typedef {Object} ActivateCmkResponse\n * @property {number} status\n * @property {UUID} requestId\n * @property {Array<CMK>} customerMasterKeys\n */\n /**\n *\n * @typedef {Object} CMK\n * @property {string} usageState\n * @property {UUID} assignedOrgId\n * @property {string} uri\n * @property {string} source\n * @property {Date | undefined} stateUpdatedOn\n * @property {Date | undefined} rotation\n */\n /**\n * change one customer master key state for one org.\n * delete pending key, then the keyState should be 'removedclean';\n * active pending key, then the keyState should be 'active';\n *\n * @param {Object} options\n * @param {string} options.keyId the id of one customer master key, it should be a url\n * @param {string} options.keyState one of the following: PENDING, RECOVERING,ACTIVE,REVOKED,DEACTIVATED,REENCRYPTING,RETIRED,DELETED,DISABLED,REMOVEDCLEAN,REMOVEDDIRTY;\n * @param {UUID} options.assignedOrgId the orgId\n * @returns {Promise.<ActivateCmkResponse>} response of list CMKs api\n */\n changeCustomerMasterKeyState({keyId, keyState, assignedOrgId}) {\n this.logger.info('kms: change one customer master key state for byok');\n\n return this.request({\n method: 'update',\n uri: keyId,\n keyState,\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to change the customer master key state to {}', keyState);\n\n return res;\n });\n },\n\n /**\n * this is for test case. it will delete all CMKs, no matter what their status is. This is mainly for test purpose\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @param {boolean} options.awsKms enable amazon aws keys\n * @returns {Promise.<{status, requestId}>}\n */\n deleteAllCustomerMasterKeys({assignedOrgId, awsKms = false}) {\n this.logger.info('kms: delete all customer master keys at the same time');\n\n return this.request({\n method: 'delete',\n uri: awsKms ? '/awsKmsCmk' : '/cmk',\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to delete all customer master keys');\n\n return res;\n });\n },\n\n /**\n * return to use global master key for one org.\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @returns {Promise.<ActivateCmkResponse>} response of activate CMK api\n */\n useGlobalMasterKey({assignedOrgId}) {\n this.logger.info('kms: return to use global master key');\n\n return this.request({\n method: 'update',\n uri: 'default',\n keyState: 'ACTIVE',\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to return to global master key');\n\n return res;\n });\n },\n\n /**\n * Fetches the specified key from the kms\n * @param {Object} options\n * @param {string} options.uri\n * @param {string} options.onBehalfOf The id of a user, upon whose behalf, the key is to be retrieved or undefined if retrieval is for the active user\n * @returns {Promise<Key>}\n */\n // Ideally, this would be done via the kms batcher, but other than request id,\n // there isn't any other userful key in a kms response to match it to a\n // request. as such, we need the batcher to group requests, but one flight to\n // make sure we don't make the same request multiple times.\n @oneFlight({\n keyFactory: ({uri, onBehalfOf}) => `${uri}/${onBehalfOf}`,\n })\n fetchKey({uri, onBehalfOf}) {\n /* istanbul ignore if */\n if (!uri) {\n return Promise.reject(new Error('`options.uri` is required'));\n }\n\n this.logger.info('kms: fetching key');\n\n return this.request(\n {\n method: 'retrieve',\n uri,\n },\n {onBehalfOf}\n ).then((res) => {\n this.logger.info('kms: fetched key');\n\n return this.asKey(res.key);\n });\n },\n\n /**\n * Pings the kms. Mostly for testing\n * @returns {Promise}\n */\n ping() {\n return this.request({\n method: 'update',\n uri: '/ping',\n });\n },\n\n /**\n * Ensures a key obect is Key instance\n * @param {Object} key\n * @returns {Promise<Key>}\n */\n asKey(key) {\n return jose.JWK.asKey(key.jwk).then((jwk) => {\n key.jwk = jwk;\n\n return key;\n });\n },\n\n /**\n * Adds appropriate metadata to the KMS request\n * @param {Object} payload\n * @param {Object} onBehalfOf Optional parameter to prepare the request on behalf of another user\n * @returns {Promise<KMS.Request>}\n */\n prepareRequest(payload, onBehalfOf) {\n const isECDHRequest = payload.method === 'create' && payload.uri.includes('/ecdhe');\n\n return Promise.resolve(isECDHRequest ? partialContexts.get(this) : this._getContext()).then(\n (context) => {\n this.logger.info(`kms: wrapping ${isECDHRequest ? 'ephemeral key' : 'kms'} request`);\n const req = new Request(payload);\n let requestContext = context;\n\n if (onBehalfOf) {\n requestContext = this._contextOnBehalfOf(context, onBehalfOf);\n }\n\n return req.wrap(requestContext, {serverKey: isECDHRequest}).then(() => {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n this.logger.info(\n 'kms: request payload',\n util.inspect(omit(JSON.parse(JSON.stringify(req)), 'wrapped'), {depth: null})\n );\n }\n\n return req;\n });\n }\n );\n },\n\n /**\n * Accepts a kms message event, decrypts it, and passes it to the batcher\n * @param {Object} event\n * @returns {Promise<Object>}\n */\n processKmsMessageEvent(event) {\n this.logger.info('kms: received kms message');\n\n return Promise.all(\n event.encryption.kmsMessages.map((kmsMessage, index) =>\n this._isECDHEMessage(kmsMessage).then((isECDHMessage) => {\n this.logger.info(`kms: received ${isECDHMessage ? 'ecdhe' : 'normal'} message`);\n const res = new Response(kmsMessage);\n\n return (\n Promise.resolve(isECDHMessage ? partialContexts.get(this) : contexts.get(this))\n // eslint-disable-next-line max-nested-callbacks\n .then((context) => res.unwrap(context))\n // eslint-disable-next-line max-nested-callbacks\n .then(() => {\n if (process.env.NODE_ENV !== 'production') {\n this.logger.info(\n 'kms: response payload',\n util.inspect(omit(JSON.parse(JSON.stringify(res)), 'wrapped'), {depth: null})\n );\n }\n })\n // eslint-disable-next-line max-nested-callbacks\n .then(() => {\n event.encryption.kmsMessages[index] = res;\n })\n // eslint-disable-next-line max-nested-callbacks\n .then(() => res)\n );\n })\n )\n )\n .then(() => this.batcher.processKmsMessageEvent(event))\n .catch((reason) => {\n this.logger.error('kms: decrypt failed', reason.stack);\n\n return Promise.reject(reason);\n })\n .then(() => event);\n },\n\n /**\n * Decrypts a kms message\n * @param {Object} kmsMessage\n * @returns {Promise<Object>}\n */\n decryptKmsMessage(kmsMessage) {\n const res = new Response(kmsMessage);\n\n return contexts\n .get(this)\n .then((context) => res.unwrap(context))\n .then(() => res.body);\n },\n\n /**\n * Determines if the kms message is an ecdhe message or a normal message\n * @param {Object} kmsMessage\n * @returns {Promise<boolean>}\n */\n _isECDHEMessage(kmsMessage) {\n return this._getKMSStaticPubKey().then((kmsStaticPubKey) => {\n const fields = kmsMessage.split('.');\n\n if (fields.length !== 3) {\n return false;\n }\n\n const header = JSON.parse(jose.util.base64url.decode(fields[0]));\n\n return header.kid === kmsStaticPubKey.kid;\n });\n },\n\n /**\n * Sends a request to the kms\n * @param {Object} payload\n * @param {Object} options\n * @param {Number} options.timeout (internal)\n * @param {string} options.onBehalfOf Run the request on behalf of another user (UUID), used in compliance scenarios\n * @returns {Promise<Object>}\n */\n request(payload, {timeout, onBehalfOf} = {}) {\n timeout = timeout || this.config.kmsInitialTimeout;\n\n // Note: this should only happen when we're using the async kms batcher;\n // once we implement the sync batcher, this'll need to be smarter.\n return (\n this.webex.internal.mercury\n .connect()\n .then(() => this.prepareRequest(payload, onBehalfOf))\n .then((req) => {\n req[TIMEOUT_SYMBOL] = timeout;\n\n return this.batcher.request(req);\n })\n // High complexity is due to attempt at test mode resiliency\n // eslint-disable-next-line complexity\n .catch((reason) => {\n if (\n process.env.NODE_ENV === 'test' &&\n (reason.status === 403 || reason.statusCode === 403) &&\n reason.message.match(\n /Failed to resolve authorization token in KmsMessage request for user/\n )\n ) {\n this.logger.warn('kms: rerequested key due to test-mode kms auth failure');\n\n return this.request(payload, {onBehalfOf});\n }\n\n // KMS Error. Notify the user\n if (reason instanceof KMSError) {\n this.webex.trigger('client:InvalidRequestError');\n\n return Promise.reject(reason);\n }\n\n // Ideally, most or all of the code below would go in kms-batcher, but\n // but batching needs at least one more round of refactoring for that to\n // work.\n if (!reason.statusCode && !reason.status) {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n /* istanbul ignore next: reason.stack vs stack difficult to control in test */\n this.logger.info('kms: request error', reason.stack || reason);\n }\n\n consoleDebug(`timeout ${timeout}`);\n timeout *= 2;\n\n if (timeout >= this.config.ecdhMaxTimeout) {\n this.logger.info('kms: exceeded maximum KMS request retries');\n\n return Promise.reject(reason);\n }\n\n // Peek ahead to make sure we don't reset the timeout if the next timeout\n // will exceed the maximum timeout for renegotiating ECDH keys.\n const nextTimeout = timeout * 2;\n\n if (timeout >= this.config.kmsMaxTimeout && nextTimeout < this.config.ecdhMaxTimeout) {\n this.logger.info(\n 'kms: exceeded maximum KMS request retries; negotiating new ecdh key'\n );\n\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n this.logger.info('kms: timeout/maxtimeout', timeout, this.config.kmsMaxTimeout);\n }\n\n contexts.delete(this);\n timeout = 0;\n }\n\n return this.request(payload, {timeout, onBehalfOf});\n }\n\n return Promise.reject(reason);\n })\n );\n },\n\n /**\n * @private\n * @returns {Promise<string>}\n */\n _getAuthorization() {\n return this.webex.credentials.getUserToken('spark:kms').then((token) => token.access_token);\n },\n\n @oneFlight\n /**\n * @private\n * @param {String} onBehalfOf create context on behalf of another user, undefined when this is not necessary\n * @returns {Promise<Object>}\n */\n _getContext() {\n let promise = contexts.get(this);\n\n if (!promise) {\n promise = this._prepareContext();\n contexts.set(this, promise);\n promise.then((context) => {\n const expiresIn = context.ephemeralKey.expirationDate - Date.now() - 30000;\n\n safeSetTimeout(() => contexts.delete(this), expiresIn);\n });\n }\n\n return Promise.all([promise, this._getAuthorization()]).then(([context, authorization]) => {\n context.clientInfo.credential.bearer = authorization;\n\n return context;\n });\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _getKMSCluster() {\n this.logger.info('kms: retrieving KMS cluster');\n\n return this._getKMSDetails().then(({kmsCluster}) => kmsCluster);\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _getKMSDetails() {\n let details = kmsDetails.get(this);\n\n if (!details) {\n this.logger.info('kms: fetching KMS details');\n details = this.webex\n .request({\n service: 'encryption',\n resource: `/kms/${this.webex.internal.device.userId}`,\n })\n .then((res) => {\n this.logger.info('kms: fetched KMS details');\n const {body} = res;\n\n body.rsaPublicKey = JSON.parse(body.rsaPublicKey);\n\n return body;\n })\n .catch((reason) => {\n this.logger.error('kms: failed to fetch KMS details', reason);\n\n return Promise.reject(reason);\n });\n\n kmsDetails.set(this, details);\n }\n\n return details;\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _getKMSStaticPubKey() {\n this.logger.info('kms: retrieving KMS static public key');\n\n return this._getKMSDetails().then(({rsaPublicKey}) => rsaPublicKey);\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _prepareContext() {\n this.logger.info('kms: creating context');\n const context = new Context();\n\n return Promise.all([\n this._getKMSStaticPubKey().then(validateKMS(this.config.caroots)),\n this._getAuthorization(),\n ])\n .then(([kmsStaticPubKey, authorization]) => {\n context.clientInfo = {\n clientId: this.webex.internal.device.url,\n credential: {\n userId: this.webex.internal.device.userId,\n bearer: authorization,\n },\n };\n\n context.serverInfo = {\n key: kmsStaticPubKey,\n };\n\n this.logger.info('kms: creating local ephemeral key');\n\n return context.createECDHKey();\n })\n .then((localECDHKey) => {\n context.ephemeralKey = localECDHKey;\n partialContexts.set(this, context);\n\n return Promise.all([localECDHKey.asKey(), this._getKMSCluster()]);\n })\n .then(([localECDHKey, cluster]) => {\n this.logger.info('kms: submitting ephemeral key request');\n\n return this.request({\n uri: `${cluster}/ecdhe`,\n method: 'create',\n jwk: localECDHKey.toJSON(),\n });\n })\n .then((res) => {\n this.logger.info('kms: deriving final ephemeral key');\n\n return context.deriveEphemeralKey(res.key);\n })\n .then((key) => {\n context.ephemeralKey = key;\n partialContexts.delete(this);\n this.logger.info('kms: derived final ephemeral key');\n\n return context;\n })\n .catch((reason) => {\n this.logger.error('kms: failed to negotiate ephemeral key', reason);\n\n return Promise.reject(reason);\n });\n },\n\n /**\n * KMS 'retrieve' requests can be made on behalf of another user. This is useful\n * for scenarios such as eDiscovery. i.e. Where an authorized compliance officer is\n * entitled to retrieve content generated by any organisational user.\n * As the KMSContext is cached, updating it will affect separate requests. Hence when\n * making a request onBehalfOf another user create a new context for just this request.\n * However this context will be 'light' as it only needs to change one field.\n * @param {Object} originalContext - The base context to 'copy'\n * @param {String} onBehalfOf - The user specified in the new context\n * @returns {Context} A 'copy' of the existing context with a new user specified\n * @private\n */\n _contextOnBehalfOf(originalContext, onBehalfOf) {\n const context = new Context();\n\n context.clientInfo = context.clientInfo = {\n clientId: originalContext.clientInfo.clientId,\n credential: {\n userId: onBehalfOf,\n onBehalfOf, // Supports running onBehalfOf self. i.e. A CO which calls onBehalfOf with CO.id.\n bearer: originalContext.clientInfo.credential.bearer,\n },\n };\n context.serverInfo = originalContext.serverInfo;\n context.ephemeralKey = originalContext.ephemeralKey;\n\n return context;\n },\n});\n\nexport default KMS;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,KAAA,GAAAF,sBAAA,CAAAC,OAAA;AAEA,IAAAE,aAAA,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AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEzB,kBAAkB,WAAAA,mBAAC0G,eAAe,EAAEtN,UAAU,EAAE;IAC9C,IAAMwG,OAAO,GAAG,IAAI+F,gBAAO,CAAC,CAAC;IAE7B/F,OAAO,CAACiF,UAAU,GAAGjF,OAAO,CAACiF,UAAU,GAAG;MACxCmB,QAAQ,EAAEU,eAAe,CAAC7B,UAAU,CAACmB,QAAQ;MAC7ClB,UAAU,EAAE;QACV3I,MAAM,EAAE/C,UAAU;QAClBA,UAAU,EAAVA,UAAU;QAAE;QACZ2L,MAAM,EAAE2B,eAAe,CAAC7B,UAAU,CAACC,UAAU,CAACC;MAChD;IACF,CAAC;IACDnF,OAAO,CAACsG,UAAU,GAAGQ,eAAe,CAACR,UAAU;IAC/CtG,OAAO,CAACyE,YAAY,GAAGqC,eAAe,CAACrC,YAAY;IAEnD,OAAOzE,OAAO;EAChB,CAAC;EAAA+G,OAAA;AACH,CAAC,OAAAC,0BAAA,CAAAnP,OAAA,EAAAR,IAAA,eAAAD,IAAA,OAAA6P,yBAAA,CAAApP,OAAA,EAAAR,IAAA,eAAAA,IAAA,OAAA2P,0BAAA,CAAAnP,OAAA,EAAAR,IAAA,kBA3KE+B,iBAAS,OAAA6N,yBAAA,CAAApP,OAAA,EAAAR,IAAA,kBAAAA,IAAA,IAAAA,IAAA,EA2KX,CAAC;AAAC,IAAA6P,QAAA,GAAAC,OAAA,CAAAtP,OAAA,GAEYoB,GAAG"}
|
|
1
|
+
{"version":3,"names":["_querystring","_interopRequireDefault","require","_util","_commonTimers","_common","_webexCore","_nodeKms","_nodeJose","_lodash","_uuid","_kmsBatcher","_interopRequireWildcard","_kmsCertificateValidation","_constants","_dec","_obj","_getRequireWildcardCache","e","_WeakMap2","r","t","__esModule","_typeof","default","has","get","n","__proto__","a","_Object$defineProperty","_Object$getOwnPropertyDescriptor2","u","Object","prototype","hasOwnProperty","call","i","set","contexts","_weakMap","kmsDetails","partialContexts","consoleDebug","KMS","WebexPlugin","extend","oneFlight","keyFactory","_ref","uri","onBehalfOf","concat","namespace","children","batcher","KMSBatcher","bindKey","_ref2","_this","kro","kroUri","key","keyUri","logger","info","_promise","reject","Error","request","method","resourceUri","then","res","createResource","_ref3","_this2","userIds","keyUris","keys","reduce","uris","k","push","length","resource","addAuthorization","_ref4","_this3","authIds","authorizations","listAuthorizations","_ref5","_this4","removeAuthorization","_ref6","_this5","authId","userId","querystring","stringify","createUnboundKeys","_ref7","_this6","count","all","map","asKey","fetchPublicKey","_ref8","_this7","assignedOrgId","publicKey","uploadCustomerMasterKey","_ref9","_this8","customerMasterKey","_ref9$awsKms","awsKms","_ref9$customerMasterK","customerMasterKeyBackup","undefined","_ref9$customerMasterK2","customerMasterKeyRole","requestId","uuid","v4","listAllCustomerMasterKey","_ref10","_this9","_ref10$awsKms","changeCustomerMasterKeyState","_ref11","_this10","keyId","keyState","deleteAllCustomerMasterKeys","_ref12","_this11","_ref12$awsKms","useGlobalMasterKey","_ref13","_this12","fetchKey","_ref14","_this13","errorCode","KMS_KEY_REDIRECT_ERROR_CODE","redirectUri","redirectRes","ping","jose","JWK","jwk","prepareRequest","payload","_this14","isECDHRequest","includes","resolve","_getContext","context","req","Request","requestContext","_contextOnBehalfOf","wrap","serverKey","process","env","NODE_ENV","util","inspect","omit","JSON","parse","_stringify","depth","processKmsMessageEvent","event","_this15","encryption","kmsMessages","kmsMessage","index","_isECDHEMessage","isECDHMessage","Response","unwrap","catch","reason","error","stack","decryptKmsMessage","body","_getKMSStaticPubKey","kmsStaticPubKey","fields","split","header","base64url","decode","kid","_this16","_ref15","arguments","timeout","config","kmsInitialTimeout","webex","internal","mercury","connect","TIMEOUT_SYMBOL","status","statusCode","message","match","warn","KMSError","trigger","ecdhMaxTimeout","nextTimeout","kmsMaxTimeout","delete","_getAuthorization","credentials","getUserToken","token","access_token","_this17","promise","_prepareContext","expiresIn","ephemeralKey","expirationDate","_now","safeSetTimeout","_ref16","_ref17","_slicedToArray2","authorization","clientInfo","credential","bearer","_getKMSCluster","_getKMSDetails","_ref18","kmsCluster","_this18","details","service","device","rsaPublicKey","_ref19","_this19","Context","validateKMS","caroots","_ref20","_ref21","clientId","url","serverInfo","createECDHKey","localECDHKey","_ref22","_ref23","cluster","toJSON","deriveEphemeralKey","originalContext","version","_applyDecoratedDescriptor2","_getOwnPropertyDescriptor","_default","exports"],"sources":["kms.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2024 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport querystring from 'querystring';\nimport util from 'util';\n\nimport {safeSetTimeout} from '@webex/common-timers';\nimport {oneFlight} from '@webex/common';\nimport {WebexPlugin} from '@webex/webex-core';\nimport {Context, Request, Response} from 'node-kms';\nimport jose from 'node-jose';\nimport {omit} from 'lodash';\nimport uuid from 'uuid';\n\nimport KMSBatcher, {TIMEOUT_SYMBOL} from './kms-batcher';\nimport validateKMS, {KMSError} from './kms-certificate-validation';\nimport {KMS_KEY_REDIRECT_ERROR_CODE} from './constants';\n\nconst contexts = new WeakMap();\nconst kmsDetails = new WeakMap();\nconst partialContexts = new WeakMap();\n\nconst consoleDebug = require('debug')('kms');\n\n/**\n * @class\n */\nconst KMS = WebexPlugin.extend({\n namespace: 'Encryption',\n\n children: {\n batcher: KMSBatcher,\n },\n\n /**\n * Binds a key to a resource\n * @param {Object} options\n * @param {KMSResourceObject} options.kro\n * @param {string} options.kroUri\n * @param {Key} options.key\n * @param {string} options.keyUri\n * @returns {Promise<Key>}\n */\n bindKey({kro, kroUri, key, keyUri}) {\n kroUri = kroUri || kro.uri;\n keyUri = keyUri || key.uri;\n\n this.logger.info('kms: binding key to resource');\n\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n /* istanbul ignore if */\n if (!keyUri) {\n return Promise.reject(new Error('`key` or `keyUri` is required'));\n }\n\n return this.request({\n method: 'update',\n resourceUri: kroUri,\n uri: keyUri,\n }).then((res) => {\n this.logger.info('kms: bound key to resource');\n\n return res.key;\n });\n },\n\n /**\n * Creates a new KMS Resource\n * @param {Object} options\n * @param {Array<string>} options.userIds\n * @param {Array<string>} options.keyUris\n * @param {Key} options.key\n * @param {Array<Keys>} options.keys\n * @returns {Promise<KMSResourceObject>}\n */\n createResource({userIds, keyUris, key, keys}) {\n keyUris = keyUris || [];\n /* istanbul ignore if */\n if (keys) {\n keyUris = keys.reduce((uris, k) => {\n uris.push(k.uri);\n\n return uris;\n }, keyUris);\n }\n\n /* istanbul ignore else */\n if (key) {\n keyUris.push(key.uri);\n }\n\n /* istanbul ignore if */\n if (keyUris.length === 0) {\n return Promise.reject(new Error('Cannot create KMS Resource without at least one keyUri'));\n }\n\n this.logger.info('kms: creating resource');\n\n return this.request({\n method: 'create',\n uri: '/resources',\n userIds,\n keyUris,\n }).then((res) => {\n this.logger.info('kms: created resource');\n\n return res.resource;\n });\n },\n\n /**\n * Authorizes a user or KRO to a KRO\n * @param {Object} options\n * @param {Array<string>} options.userIds\n * @param {Array<string>} options.authIds interchangable with userIds\n * @param {KMSResourceObject} options.kro the target kro\n * @param {string} options.kroUri\n * @returns {Promise<KMSAuthorizationObject>}\n */\n addAuthorization({userIds, authIds, kro, kroUri}) {\n userIds = userIds || [];\n kroUri = kroUri || kro.uri;\n\n if (authIds) {\n userIds = userIds.concat(authIds);\n }\n\n /* istanbul ignore if */\n if (userIds.length === 0) {\n return Promise.reject(new Error('Cannot add authorization without userIds or authIds'));\n }\n\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n this.logger.info('kms: adding authorization to kms resource');\n\n return this.request({\n method: 'create',\n uri: '/authorizations',\n resourceUri: kroUri,\n userIds,\n }).then((res) => {\n this.logger.info('kms: added authorization');\n\n return res.authorizations;\n });\n },\n\n /**\n * Retrieve a list of users that have been authorized to the KRO\n * @param {Object} options\n * @param {KMSResourceObject} options.kro the target kro\n * @param {string} options.kroUri\n * @returns {Array<authId>}\n */\n listAuthorizations({kro, kroUri}) {\n kroUri = kroUri || kro.uri;\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n return this.request({\n method: 'retrieve',\n uri: `${kroUri}/authorizations`,\n }).then((res) => {\n this.logger.info('kms: retrieved authorization list');\n\n return res.authorizations;\n });\n },\n\n /**\n * Deauthorizes a user or KRO from a KRO\n * @param {Object} options\n * @param {string} options.userId\n * @param {string} options.authId interchangable with userIds\n * @param {KMSResourceObject} options.kro the target kro\n * @param {string} options.kroUri\n * @returns {Promise<KMSAuthorizationObject>}\n */\n removeAuthorization({authId, userId, kro, kroUri}) {\n authId = authId || userId;\n kroUri = kroUri || kro.uri;\n\n /* istanbul ignore if */\n if (!authId) {\n return Promise.reject(new Error('Cannot remove authorization without authId'));\n }\n\n /* istanbul ignore if */\n if (!kroUri) {\n return Promise.reject(new Error('`kro` or `kroUri` is required'));\n }\n\n this.logger.info('kms: removing authorization from kms resource');\n\n return this.request({\n method: 'delete',\n uri: `${kroUri}/authorizations?${querystring.stringify({authId})}`,\n }).then((res) => {\n this.logger.info('kms: removed authorization');\n\n return res.authorizations;\n });\n },\n\n /**\n * Requests `count` unbound keys from the kms\n * @param {Object} options\n * @param {Number} options.count\n * @returns {Array<Key>}\n */\n createUnboundKeys({count}) {\n this.logger.info(`kms: request ${count} unbound keys`);\n\n /* istanbul ignore if */\n if (!count) {\n return Promise.reject(new Error('`options.count` is required'));\n }\n\n return this.request({\n method: 'create',\n uri: '/keys',\n count,\n }).then((res) => {\n this.logger.info('kms: received unbound keys');\n\n return Promise.all(res.keys.map(this.asKey));\n });\n },\n\n /**\n * @typedef {Object} FetchPublicKeyResponse\n * @property {number} status 200,400(Bad Request: Request payload missing info),404(Not Found: HSM Public Key not found),501(Not Implemented: This KMS does not support BYOK),502(Bad Gateway: KMS could not communicate with HSM)\n * @property {UUID} requestId this is should be unique, used for debug.\n * @property {string} publicKey\n */\n /**\n * get public key from kms\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @returns {Promise.<FetchPublicKeyResponse>} response of get public key api\n */\n fetchPublicKey({assignedOrgId}) {\n this.logger.info('kms: fetch public key for byok');\n\n return this.request({\n method: 'retrieve',\n uri: '/publicKey',\n assignedOrgId,\n }).then((res) => {\n this.logger.info('kms: received public key');\n\n return res.publicKey;\n });\n },\n\n /**\n * @typedef {Object} UploadCmkResponse\n * @property {number} status\n * @property {UUID} requestId\n * @property {string} uri\n * @property {string} keysState\n */\n /**\n * upload master key for one org.\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @param {string} options.customerMasterKey the master key\n * @param {string} options.customerMasterKeyBackup the master key backup\n * @param {string} options.customerMasterKeyRole the optional role associated with customerMasterKey\n * @param {boolean} options.awsKms enable amazon aws keys\n * @returns {Promise.<UploadCmkResponse>} response of upload CMK api\n */\n uploadCustomerMasterKey({\n assignedOrgId,\n customerMasterKey,\n awsKms = false,\n customerMasterKeyBackup = undefined,\n customerMasterKeyRole = undefined,\n }) {\n this.logger.info('kms: upload customer master key for byok');\n\n return this.request({\n method: 'create',\n uri: awsKms ? '/awsKmsCmk' : '/cmk',\n assignedOrgId,\n customerMasterKey,\n requestId: uuid.v4(),\n customerMasterKeyBackup: awsKms ? customerMasterKeyBackup : undefined,\n customerMasterKeyRole: awsKms ? customerMasterKeyRole : undefined,\n }).then((res) => {\n this.logger.info('kms: finish to upload customer master key');\n\n return res;\n });\n },\n\n /**\n * get all customer master keys for one org.\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @param {boolean} options.awsKms enable amazon aws keys\n * @returns {Promise.<ActivateCmkResponse>} response of list CMKs api\n */\n listAllCustomerMasterKey({assignedOrgId, awsKms = false}) {\n this.logger.info('kms: get all customer master keys for byok');\n\n return this.request({\n method: 'retrieve',\n uri: awsKms ? '/awsKmsCmk' : '/cmk',\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to get all customer master keys');\n\n return res;\n });\n },\n\n /**\n * @typedef {Object} ActivateCmkResponse\n * @property {number} status\n * @property {UUID} requestId\n * @property {Array<CMK>} customerMasterKeys\n */\n /**\n *\n * @typedef {Object} CMK\n * @property {string} usageState\n * @property {UUID} assignedOrgId\n * @property {string} uri\n * @property {string} source\n * @property {Date | undefined} stateUpdatedOn\n * @property {Date | undefined} rotation\n */\n /**\n * change one customer master key state for one org.\n * delete pending key, then the keyState should be 'removedclean';\n * active pending key, then the keyState should be 'active';\n *\n * @param {Object} options\n * @param {string} options.keyId the id of one customer master key, it should be a url\n * @param {string} options.keyState one of the following: PENDING, RECOVERING,ACTIVE,REVOKED,DEACTIVATED,REENCRYPTING,RETIRED,DELETED,DISABLED,REMOVEDCLEAN,REMOVEDDIRTY;\n * @param {UUID} options.assignedOrgId the orgId\n * @returns {Promise.<ActivateCmkResponse>} response of list CMKs api\n */\n changeCustomerMasterKeyState({keyId, keyState, assignedOrgId}) {\n this.logger.info('kms: change one customer master key state for byok');\n\n return this.request({\n method: 'update',\n uri: keyId,\n keyState,\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to change the customer master key state to {}', keyState);\n\n return res;\n });\n },\n\n /**\n * this is for test case. it will delete all CMKs, no matter what their status is. This is mainly for test purpose\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @param {boolean} options.awsKms enable amazon aws keys\n * @returns {Promise.<{status, requestId}>}\n */\n deleteAllCustomerMasterKeys({assignedOrgId, awsKms = false}) {\n this.logger.info('kms: delete all customer master keys at the same time');\n\n return this.request({\n method: 'delete',\n uri: awsKms ? '/awsKmsCmk' : '/cmk',\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to delete all customer master keys');\n\n return res;\n });\n },\n\n /**\n * return to use global master key for one org.\n * @param {Object} options\n * @param {UUID} options.assignedOrgId the orgId\n * @returns {Promise.<ActivateCmkResponse>} response of activate CMK api\n */\n useGlobalMasterKey({assignedOrgId}) {\n this.logger.info('kms: return to use global master key');\n\n return this.request({\n method: 'update',\n uri: 'default',\n keyState: 'ACTIVE',\n assignedOrgId,\n requestId: uuid.v4(),\n }).then((res) => {\n this.logger.info('kms: finish to return to global master key');\n\n return res;\n });\n },\n\n /**\n * Fetches the specified key from the kms\n * @param {Object} options\n * @param {string} options.uri\n * @param {string} options.onBehalfOf The id of a user, upon whose behalf, the key is to be retrieved or undefined if retrieval is for the active user\n * @returns {Promise<Key>}\n */\n // Ideally, this would be done via the kms batcher, but other than request id,\n // there isn't any other userful key in a kms response to match it to a\n // request. as such, we need the batcher to group requests, but one flight to\n // make sure we don't make the same request multiple times.\n @oneFlight({\n keyFactory: ({uri, onBehalfOf}) => `${uri}/${onBehalfOf}`,\n })\n fetchKey({uri, onBehalfOf}) {\n /* istanbul ignore if */\n if (!uri) {\n return Promise.reject(new Error('`options.uri` is required'));\n }\n\n this.logger.info('kms: fetching key');\n\n return this.request(\n {\n method: 'retrieve',\n uri,\n },\n {onBehalfOf}\n ).then((res) => {\n // Handle redirect for migrated KRO, Key or Auth\n if (res.errorCode === KMS_KEY_REDIRECT_ERROR_CODE && res.redirectUri) {\n this.logger.info('kms: handling redirect for migrated resource', res.redirectUri);\n\n return this.request(\n {\n method: 'retrieve',\n uri: res.redirectUri,\n },\n {onBehalfOf}\n ).then((redirectRes) => {\n this.logger.info('kms: fetched key from redirect');\n\n return this.asKey(redirectRes.key);\n });\n }\n\n this.logger.info('kms: fetched key');\n\n return this.asKey(res.key);\n });\n },\n\n /**\n * Pings the kms. Mostly for testing\n * @returns {Promise}\n */\n ping() {\n return this.request({\n method: 'update',\n uri: '/ping',\n });\n },\n\n /**\n * Ensures a key obect is Key instance\n * @param {Object} key\n * @returns {Promise<Key>}\n */\n asKey(key) {\n return jose.JWK.asKey(key.jwk).then((jwk) => {\n key.jwk = jwk;\n\n return key;\n });\n },\n\n /**\n * Adds appropriate metadata to the KMS request\n * @param {Object} payload\n * @param {Object} onBehalfOf Optional parameter to prepare the request on behalf of another user\n * @returns {Promise<KMS.Request>}\n */\n prepareRequest(payload, onBehalfOf) {\n const isECDHRequest = payload.method === 'create' && payload.uri.includes('/ecdhe');\n\n return Promise.resolve(isECDHRequest ? partialContexts.get(this) : this._getContext()).then(\n (context) => {\n this.logger.info(`kms: wrapping ${isECDHRequest ? 'ephemeral key' : 'kms'} request`);\n const req = new Request(payload);\n let requestContext = context;\n\n if (onBehalfOf) {\n requestContext = this._contextOnBehalfOf(context, onBehalfOf);\n }\n\n return req.wrap(requestContext, {serverKey: isECDHRequest}).then(() => {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n this.logger.info(\n 'kms: request payload',\n util.inspect(omit(JSON.parse(JSON.stringify(req)), 'wrapped'), {depth: null})\n );\n }\n\n return req;\n });\n }\n );\n },\n\n /**\n * Accepts a kms message event, decrypts it, and passes it to the batcher\n * @param {Object} event\n * @returns {Promise<Object>}\n */\n processKmsMessageEvent(event) {\n this.logger.info('kms: received kms message');\n\n return Promise.all(\n event.encryption.kmsMessages.map((kmsMessage, index) =>\n this._isECDHEMessage(kmsMessage).then((isECDHMessage) => {\n this.logger.info(`kms: received ${isECDHMessage ? 'ecdhe' : 'normal'} message`);\n const res = new Response(kmsMessage);\n\n return (\n Promise.resolve(isECDHMessage ? partialContexts.get(this) : contexts.get(this))\n // eslint-disable-next-line max-nested-callbacks\n .then((context) => res.unwrap(context))\n // eslint-disable-next-line max-nested-callbacks\n .then(() => {\n if (process.env.NODE_ENV !== 'production') {\n this.logger.info(\n 'kms: response payload',\n util.inspect(omit(JSON.parse(JSON.stringify(res)), 'wrapped'), {depth: null})\n );\n }\n })\n // eslint-disable-next-line max-nested-callbacks\n .then(() => {\n event.encryption.kmsMessages[index] = res;\n })\n // eslint-disable-next-line max-nested-callbacks\n .then(() => res)\n );\n })\n )\n )\n .then(() => this.batcher.processKmsMessageEvent(event))\n .catch((reason) => {\n this.logger.error('kms: decrypt failed', reason.stack);\n\n return Promise.reject(reason);\n })\n .then(() => event);\n },\n\n /**\n * Decrypts a kms message\n * @param {Object} kmsMessage\n * @returns {Promise<Object>}\n */\n decryptKmsMessage(kmsMessage) {\n const res = new Response(kmsMessage);\n\n return contexts\n .get(this)\n .then((context) => res.unwrap(context))\n .then(() => res.body);\n },\n\n /**\n * Determines if the kms message is an ecdhe message or a normal message\n * @param {Object} kmsMessage\n * @returns {Promise<boolean>}\n */\n _isECDHEMessage(kmsMessage) {\n return this._getKMSStaticPubKey().then((kmsStaticPubKey) => {\n const fields = kmsMessage.split('.');\n\n if (fields.length !== 3) {\n return false;\n }\n\n const header = JSON.parse(jose.util.base64url.decode(fields[0]));\n\n return header.kid === kmsStaticPubKey.kid;\n });\n },\n\n /**\n * Sends a request to the kms\n * @param {Object} payload\n * @param {Object} options\n * @param {Number} options.timeout (internal)\n * @param {string} options.onBehalfOf Run the request on behalf of another user (UUID), used in compliance scenarios\n * @returns {Promise<Object>}\n */\n request(payload, {timeout, onBehalfOf} = {}) {\n timeout = timeout || this.config.kmsInitialTimeout;\n\n // Note: this should only happen when we're using the async kms batcher;\n // once we implement the sync batcher, this'll need to be smarter.\n return (\n this.webex.internal.mercury\n .connect()\n .then(() => this.prepareRequest(payload, onBehalfOf))\n .then((req) => {\n req[TIMEOUT_SYMBOL] = timeout;\n\n return this.batcher.request(req);\n })\n // High complexity is due to attempt at test mode resiliency\n // eslint-disable-next-line complexity\n .catch((reason) => {\n if (\n process.env.NODE_ENV === 'test' &&\n (reason.status === 403 || reason.statusCode === 403) &&\n reason.message.match(\n /Failed to resolve authorization token in KmsMessage request for user/\n )\n ) {\n this.logger.warn('kms: rerequested key due to test-mode kms auth failure');\n\n return this.request(payload, {onBehalfOf});\n }\n\n // KMS Error. Notify the user\n if (reason instanceof KMSError) {\n this.webex.trigger('client:InvalidRequestError');\n\n return Promise.reject(reason);\n }\n\n // Ideally, most or all of the code below would go in kms-batcher, but\n // but batching needs at least one more round of refactoring for that to\n // work.\n if (!reason.statusCode && !reason.status) {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n /* istanbul ignore next: reason.stack vs stack difficult to control in test */\n this.logger.info('kms: request error', reason.stack || reason);\n }\n\n consoleDebug(`timeout ${timeout}`);\n timeout *= 2;\n\n if (timeout >= this.config.ecdhMaxTimeout) {\n this.logger.info('kms: exceeded maximum KMS request retries');\n\n return Promise.reject(reason);\n }\n\n // Peek ahead to make sure we don't reset the timeout if the next timeout\n // will exceed the maximum timeout for renegotiating ECDH keys.\n const nextTimeout = timeout * 2;\n\n if (timeout >= this.config.kmsMaxTimeout && nextTimeout < this.config.ecdhMaxTimeout) {\n this.logger.info(\n 'kms: exceeded maximum KMS request retries; negotiating new ecdh key'\n );\n\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n this.logger.info('kms: timeout/maxtimeout', timeout, this.config.kmsMaxTimeout);\n }\n\n contexts.delete(this);\n timeout = 0;\n }\n\n return this.request(payload, {timeout, onBehalfOf});\n }\n\n return Promise.reject(reason);\n })\n );\n },\n\n /**\n * @private\n * @returns {Promise<string>}\n */\n _getAuthorization() {\n return this.webex.credentials.getUserToken('spark:kms').then((token) => token.access_token);\n },\n\n @oneFlight\n /**\n * @private\n * @param {String} onBehalfOf create context on behalf of another user, undefined when this is not necessary\n * @returns {Promise<Object>}\n */\n _getContext() {\n let promise = contexts.get(this);\n\n if (!promise) {\n promise = this._prepareContext();\n contexts.set(this, promise);\n promise.then((context) => {\n const expiresIn = context.ephemeralKey.expirationDate - Date.now() - 30000;\n\n safeSetTimeout(() => contexts.delete(this), expiresIn);\n });\n }\n\n return Promise.all([promise, this._getAuthorization()]).then(([context, authorization]) => {\n context.clientInfo.credential.bearer = authorization;\n\n return context;\n });\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _getKMSCluster() {\n this.logger.info('kms: retrieving KMS cluster');\n\n return this._getKMSDetails().then(({kmsCluster}) => kmsCluster);\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _getKMSDetails() {\n let details = kmsDetails.get(this);\n\n if (!details) {\n this.logger.info('kms: fetching KMS details');\n details = this.webex\n .request({\n service: 'encryption',\n resource: `/kms/${this.webex.internal.device.userId}`,\n })\n .then((res) => {\n this.logger.info('kms: fetched KMS details');\n const {body} = res;\n\n body.rsaPublicKey = JSON.parse(body.rsaPublicKey);\n\n return body;\n })\n .catch((reason) => {\n this.logger.error('kms: failed to fetch KMS details', reason);\n\n return Promise.reject(reason);\n });\n\n kmsDetails.set(this, details);\n }\n\n return details;\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _getKMSStaticPubKey() {\n this.logger.info('kms: retrieving KMS static public key');\n\n return this._getKMSDetails().then(({rsaPublicKey}) => rsaPublicKey);\n },\n\n /**\n * @private\n * @returns {Promise<Object>}\n */\n _prepareContext() {\n this.logger.info('kms: creating context');\n const context = new Context();\n\n return Promise.all([\n this._getKMSStaticPubKey().then(validateKMS(this.config.caroots)),\n this._getAuthorization(),\n ])\n .then(([kmsStaticPubKey, authorization]) => {\n context.clientInfo = {\n clientId: this.webex.internal.device.url,\n credential: {\n userId: this.webex.internal.device.userId,\n bearer: authorization,\n },\n };\n\n context.serverInfo = {\n key: kmsStaticPubKey,\n };\n\n this.logger.info('kms: creating local ephemeral key');\n\n return context.createECDHKey();\n })\n .then((localECDHKey) => {\n context.ephemeralKey = localECDHKey;\n partialContexts.set(this, context);\n\n return Promise.all([localECDHKey.asKey(), this._getKMSCluster()]);\n })\n .then(([localECDHKey, cluster]) => {\n this.logger.info('kms: submitting ephemeral key request');\n\n return this.request({\n uri: `${cluster}/ecdhe`,\n method: 'create',\n jwk: localECDHKey.toJSON(),\n });\n })\n .then((res) => {\n this.logger.info('kms: deriving final ephemeral key');\n\n return context.deriveEphemeralKey(res.key);\n })\n .then((key) => {\n context.ephemeralKey = key;\n partialContexts.delete(this);\n this.logger.info('kms: derived final ephemeral key');\n\n return context;\n })\n .catch((reason) => {\n this.logger.error('kms: failed to negotiate ephemeral key', reason);\n\n return Promise.reject(reason);\n });\n },\n\n /**\n * KMS 'retrieve' requests can be made on behalf of another user. This is useful\n * for scenarios such as eDiscovery. i.e. Where an authorized compliance officer is\n * entitled to retrieve content generated by any organisational user.\n * As the KMSContext is cached, updating it will affect separate requests. Hence when\n * making a request onBehalfOf another user create a new context for just this request.\n * However this context will be 'light' as it only needs to change one field.\n * @param {Object} originalContext - The base context to 'copy'\n * @param {String} onBehalfOf - The user specified in the new context\n * @returns {Context} A 'copy' of the existing context with a new user specified\n * @private\n */\n _contextOnBehalfOf(originalContext, onBehalfOf) {\n const context = new Context();\n\n context.clientInfo = context.clientInfo = {\n clientId: originalContext.clientInfo.clientId,\n credential: {\n userId: onBehalfOf,\n onBehalfOf, // Supports running onBehalfOf self. i.e. A CO which calls onBehalfOf with CO.id.\n bearer: originalContext.clientInfo.credential.bearer,\n },\n };\n context.serverInfo = originalContext.serverInfo;\n context.ephemeralKey = originalContext.ephemeralKey;\n\n return context;\n },\n});\n\nexport default KMS;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,KAAA,GAAAF,sBAAA,CAAAC,OAAA;AAEA,IAAAE,aAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,UAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AACA,IAAAM,SAAA,GAAAP,sBAAA,CAAAC,OAAA;AACA,IAAAO,OAAA,GAAAP,OAAA;AACA,IAAAQ,KAAA,GAAAT,sBAAA,CAAAC,OAAA;AAEA,IAAAS,WAAA,GAAAC,uBAAA,CAAAV,OAAA;AACA,IAAAW,yBAAA,GAAAD,uBAAA,CAAAV,OAAA;AACA,IAAAY,UAAA,GAAAZ,OAAA;AAAwD,IAAAa,IAAA,EAAAC,IAAA;AAjBxD;AACA;AACA;AAFA,SAAAC,yBAAAC,CAAA,6BAAAC,SAAA,mBAAAC,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
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"directory": "packages/@webex/internal-plugin-encryption"
|
|
11
11
|
},
|
|
12
12
|
"engines": {
|
|
13
|
-
"node": ">=
|
|
13
|
+
"node": ">=18"
|
|
14
14
|
},
|
|
15
15
|
"browser": {
|
|
16
16
|
"./dist/ensure-buffer.js": "./dist/ensure-buffer.browser.js",
|
|
@@ -28,23 +28,23 @@
|
|
|
28
28
|
"@webex/eslint-config-legacy": "0.0.0",
|
|
29
29
|
"@webex/jest-config-legacy": "0.0.0",
|
|
30
30
|
"@webex/legacy-tools": "0.0.0",
|
|
31
|
-
"@webex/test-helper-chai": "3.
|
|
32
|
-
"@webex/test-helper-make-local-url": "3.
|
|
33
|
-
"@webex/test-helper-mocha": "3.
|
|
34
|
-
"@webex/test-helper-mock-webex": "3.
|
|
35
|
-
"@webex/test-helper-test-users": "3.
|
|
31
|
+
"@webex/test-helper-chai": "3.9.0-multi-llms.0",
|
|
32
|
+
"@webex/test-helper-make-local-url": "3.9.0-multi-llms.0",
|
|
33
|
+
"@webex/test-helper-mocha": "3.9.0-multi-llms.0",
|
|
34
|
+
"@webex/test-helper-mock-webex": "3.9.0-multi-llms.0",
|
|
35
|
+
"@webex/test-helper-test-users": "3.9.0-multi-llms.0",
|
|
36
36
|
"eslint": "^8.24.0",
|
|
37
37
|
"prettier": "^2.7.1",
|
|
38
38
|
"sinon": "^9.2.4"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@webex/common": "3.
|
|
42
|
-
"@webex/common-timers": "3.
|
|
43
|
-
"@webex/http-core": "3.
|
|
44
|
-
"@webex/internal-plugin-device": "3.
|
|
45
|
-
"@webex/internal-plugin-mercury": "3.
|
|
46
|
-
"@webex/test-helper-file": "3.
|
|
47
|
-
"@webex/webex-core": "3.
|
|
41
|
+
"@webex/common": "3.9.0-multi-llms.0",
|
|
42
|
+
"@webex/common-timers": "3.9.0-multi-llms.0",
|
|
43
|
+
"@webex/http-core": "3.9.0-multi-llms.0",
|
|
44
|
+
"@webex/internal-plugin-device": "3.9.0-multi-llms.1",
|
|
45
|
+
"@webex/internal-plugin-mercury": "3.9.0-multi-llms.1",
|
|
46
|
+
"@webex/test-helper-file": "3.9.0-multi-llms.0",
|
|
47
|
+
"@webex/webex-core": "3.9.0-multi-llms.1",
|
|
48
48
|
"asn1js": "^2.0.26",
|
|
49
49
|
"debug": "^4.3.4",
|
|
50
50
|
"isomorphic-webcrypto": "^2.3.8",
|
|
@@ -67,5 +67,5 @@
|
|
|
67
67
|
"test:style": "eslint ./src/**/*.*",
|
|
68
68
|
"test:unit": "webex-legacy-tools test --unit --runner jest"
|
|
69
69
|
},
|
|
70
|
-
"version": "3.
|
|
70
|
+
"version": "3.9.0-multi-llms.1"
|
|
71
71
|
}
|
package/src/constants.js
CHANGED
package/src/encryption.js
CHANGED
|
@@ -65,6 +65,23 @@ const Encryption = WebexPlugin.extend({
|
|
|
65
65
|
);
|
|
66
66
|
},
|
|
67
67
|
|
|
68
|
+
/**
|
|
69
|
+
* Decrypt binary data using the supplied key uri.
|
|
70
|
+
*
|
|
71
|
+
* @param {string} kmsKeyUri - The uri of a key stored in KMS
|
|
72
|
+
* @param {string} JWE - Encrypted binary data as JWE
|
|
73
|
+
* @param {Object} options
|
|
74
|
+
* @param {string} options.onBehalfOf - Fetch the KMS key on behalf of another user (using the user's UUID), active user requires the 'spark.kms_orgagent' role
|
|
75
|
+
* @returns {Buffer} Decrypted binary data as Buffer
|
|
76
|
+
*/
|
|
77
|
+
decryptBinaryData(kmsKeyUri, JWE, options) {
|
|
78
|
+
return this.getKey(kmsKeyUri, options).then((k) =>
|
|
79
|
+
jose.JWE.createDecrypt(k.jwk)
|
|
80
|
+
.decrypt(JWE)
|
|
81
|
+
.then((result) => result.payload)
|
|
82
|
+
);
|
|
83
|
+
},
|
|
84
|
+
|
|
68
85
|
/**
|
|
69
86
|
* Validate and initiate a Download request for requested file
|
|
70
87
|
* @param {Object} fileUrl - Plaintext
|
package/src/kms.js
CHANGED
|
@@ -15,6 +15,7 @@ import uuid from 'uuid';
|
|
|
15
15
|
|
|
16
16
|
import KMSBatcher, {TIMEOUT_SYMBOL} from './kms-batcher';
|
|
17
17
|
import validateKMS, {KMSError} from './kms-certificate-validation';
|
|
18
|
+
import {KMS_KEY_REDIRECT_ERROR_CODE} from './constants';
|
|
18
19
|
|
|
19
20
|
const contexts = new WeakMap();
|
|
20
21
|
const kmsDetails = new WeakMap();
|
|
@@ -276,10 +277,17 @@ const KMS = WebexPlugin.extend({
|
|
|
276
277
|
* @param {UUID} options.assignedOrgId the orgId
|
|
277
278
|
* @param {string} options.customerMasterKey the master key
|
|
278
279
|
* @param {string} options.customerMasterKeyBackup the master key backup
|
|
280
|
+
* @param {string} options.customerMasterKeyRole the optional role associated with customerMasterKey
|
|
279
281
|
* @param {boolean} options.awsKms enable amazon aws keys
|
|
280
282
|
* @returns {Promise.<UploadCmkResponse>} response of upload CMK api
|
|
281
283
|
*/
|
|
282
|
-
uploadCustomerMasterKey({
|
|
284
|
+
uploadCustomerMasterKey({
|
|
285
|
+
assignedOrgId,
|
|
286
|
+
customerMasterKey,
|
|
287
|
+
awsKms = false,
|
|
288
|
+
customerMasterKeyBackup = undefined,
|
|
289
|
+
customerMasterKeyRole = undefined,
|
|
290
|
+
}) {
|
|
283
291
|
this.logger.info('kms: upload customer master key for byok');
|
|
284
292
|
|
|
285
293
|
return this.request({
|
|
@@ -289,6 +297,7 @@ const KMS = WebexPlugin.extend({
|
|
|
289
297
|
customerMasterKey,
|
|
290
298
|
requestId: uuid.v4(),
|
|
291
299
|
customerMasterKeyBackup: awsKms ? customerMasterKeyBackup : undefined,
|
|
300
|
+
customerMasterKeyRole: awsKms ? customerMasterKeyRole : undefined,
|
|
292
301
|
}).then((res) => {
|
|
293
302
|
this.logger.info('kms: finish to upload customer master key');
|
|
294
303
|
|
|
@@ -434,6 +443,23 @@ const KMS = WebexPlugin.extend({
|
|
|
434
443
|
},
|
|
435
444
|
{onBehalfOf}
|
|
436
445
|
).then((res) => {
|
|
446
|
+
// Handle redirect for migrated KRO, Key or Auth
|
|
447
|
+
if (res.errorCode === KMS_KEY_REDIRECT_ERROR_CODE && res.redirectUri) {
|
|
448
|
+
this.logger.info('kms: handling redirect for migrated resource', res.redirectUri);
|
|
449
|
+
|
|
450
|
+
return this.request(
|
|
451
|
+
{
|
|
452
|
+
method: 'retrieve',
|
|
453
|
+
uri: res.redirectUri,
|
|
454
|
+
},
|
|
455
|
+
{onBehalfOf}
|
|
456
|
+
).then((redirectRes) => {
|
|
457
|
+
this.logger.info('kms: fetched key from redirect');
|
|
458
|
+
|
|
459
|
+
return this.asKey(redirectRes.key);
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
437
463
|
this.logger.info('kms: fetched key');
|
|
438
464
|
|
|
439
465
|
return this.asKey(res.key);
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import '@webex/internal-plugin-metrics';
|
|
5
6
|
import '@webex/internal-plugin-encryption';
|
|
6
7
|
|
|
7
8
|
import {isBuffer} from '@webex/common';
|
|
@@ -93,6 +94,89 @@ describe('Encryption', function () {
|
|
|
93
94
|
.then((plaintext) => assert.equal(plaintext, PLAINTEXT)));
|
|
94
95
|
});
|
|
95
96
|
|
|
97
|
+
describe('#decryptBinaryData()', () => {
|
|
98
|
+
it('decrypts binary data', () =>
|
|
99
|
+
webex.internal.encryption
|
|
100
|
+
.encryptText(key, FILE.toString('base64'))
|
|
101
|
+
.then((ciphertext) => {
|
|
102
|
+
assert.notEqual(ciphertext, FILE.toString('base64'));
|
|
103
|
+
|
|
104
|
+
return webex.internal.encryption.decryptBinaryData(key, ciphertext);
|
|
105
|
+
})
|
|
106
|
+
.then((decryptedData) => {
|
|
107
|
+
assert.isTrue(isBuffer(decryptedData));
|
|
108
|
+
assert.equal(decryptedData.toString('base64'), FILE.toString('base64'));
|
|
109
|
+
}));
|
|
110
|
+
|
|
111
|
+
it('decrypts binary data with Buffer input', () => {
|
|
112
|
+
const binaryData = Buffer.from('test binary data', 'utf8');
|
|
113
|
+
|
|
114
|
+
return webex.internal.encryption
|
|
115
|
+
.encryptText(key, binaryData.toString('base64'))
|
|
116
|
+
.then((ciphertext) => {
|
|
117
|
+
assert.notEqual(ciphertext, binaryData.toString('base64'));
|
|
118
|
+
|
|
119
|
+
return webex.internal.encryption.decryptBinaryData(key, ciphertext);
|
|
120
|
+
})
|
|
121
|
+
.then((decryptedData) => {
|
|
122
|
+
assert.isTrue(isBuffer(decryptedData));
|
|
123
|
+
assert.equal(decryptedData.toString('utf8'), 'test binary data');
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('decrypts binary data with options parameter', () => {
|
|
128
|
+
const binaryData = Buffer.from('test binary data with options', 'utf8');
|
|
129
|
+
|
|
130
|
+
return webex.internal.encryption
|
|
131
|
+
.encryptText(key, binaryData.toString('base64'))
|
|
132
|
+
.then((ciphertext) => {
|
|
133
|
+
assert.notEqual(ciphertext, binaryData.toString('base64'));
|
|
134
|
+
|
|
135
|
+
return webex.internal.encryption.decryptBinaryData(key, ciphertext, {});
|
|
136
|
+
})
|
|
137
|
+
.then((decryptedData) => {
|
|
138
|
+
assert.isTrue(isBuffer(decryptedData));
|
|
139
|
+
assert.equal(decryptedData.toString('utf8'), 'test binary data with options');
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('decrypts binary data with dynamically generated 3000 character string', () => {
|
|
144
|
+
// Generate a 3000-character string dynamically using different character sets
|
|
145
|
+
const generateLargeString = (length) => {
|
|
146
|
+
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';
|
|
147
|
+
let result = '';
|
|
148
|
+
const charsLength = chars.length;
|
|
149
|
+
|
|
150
|
+
for (let i = 0; i < length; i++) {
|
|
151
|
+
// Use modulo to cycle through different patterns for variety
|
|
152
|
+
const index = (i * 7 + Math.floor(i / 100) * 3) % charsLength;
|
|
153
|
+
result += chars.charAt(index);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return result;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const largeString = generateLargeString(3000);
|
|
160
|
+
const binaryData = Buffer.from(largeString, 'utf8');
|
|
161
|
+
|
|
162
|
+
// Verify the string is exactly 3000 characters
|
|
163
|
+
assert.equal(largeString.length, 3000);
|
|
164
|
+
|
|
165
|
+
return webex.internal.encryption
|
|
166
|
+
.encryptText(key, binaryData.toString('base64'))
|
|
167
|
+
.then((ciphertext) => {
|
|
168
|
+
assert.notEqual(ciphertext, binaryData.toString('base64'));
|
|
169
|
+
|
|
170
|
+
return webex.internal.encryption.decryptBinaryData(key, ciphertext);
|
|
171
|
+
})
|
|
172
|
+
.then((decryptedData) => {
|
|
173
|
+
assert.isTrue(isBuffer(decryptedData));
|
|
174
|
+
assert.equal(decryptedData.toString('utf8'), largeString);
|
|
175
|
+
assert.equal(decryptedData.toString('utf8').length, 3000);
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
|
|
96
180
|
describe('#getKey()', () => {
|
|
97
181
|
let fetchKeySpy, otherWebex, otherUser, storageGetSpy;
|
|
98
182
|
|
|
@@ -361,6 +445,24 @@ describe('Encryption', function () {
|
|
|
361
445
|
})
|
|
362
446
|
.then((plaintext) => assert.equal(plaintext, PLAINTEXT)));
|
|
363
447
|
|
|
448
|
+
it('decrypt binary data', () => {
|
|
449
|
+
const binaryData = Buffer.from('compliance test binary data', 'utf8');
|
|
450
|
+
|
|
451
|
+
return webex.internal.encryption
|
|
452
|
+
.encryptText(key, binaryData.toString('base64'))
|
|
453
|
+
.then((ciphertext) => {
|
|
454
|
+
assert.notEqual(ciphertext, binaryData.toString('base64'));
|
|
455
|
+
|
|
456
|
+
return complianceUser.webex.internal.encryption.decryptBinaryData(key, ciphertext, {
|
|
457
|
+
onBehalfOf: user.id,
|
|
458
|
+
});
|
|
459
|
+
})
|
|
460
|
+
.then((decryptedData) => {
|
|
461
|
+
assert.isTrue(isBuffer(decryptedData));
|
|
462
|
+
assert.equal(decryptedData.toString('utf8'), 'compliance test binary data');
|
|
463
|
+
});
|
|
464
|
+
});
|
|
465
|
+
|
|
364
466
|
it('encrypt and decrypt text', () =>
|
|
365
467
|
complianceUser.webex.internal.encryption
|
|
366
468
|
.encryptText(key, PLAINTEXT, {onBehalfOf: user.id})
|
|
@@ -82,4 +82,76 @@ describe('internal-plugin-encryption', () => {
|
|
|
82
82
|
});
|
|
83
83
|
});
|
|
84
84
|
});
|
|
85
|
+
|
|
86
|
+
describe('decryptBinaryData', () => {
|
|
87
|
+
let webex;
|
|
88
|
+
|
|
89
|
+
beforeEach(() => {
|
|
90
|
+
webex = new MockWebex({
|
|
91
|
+
children: {
|
|
92
|
+
encryption: Encryption,
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe('check decryptBinaryData()', () => {
|
|
98
|
+
const testKey = 'https://kms.example.com/keys/test-key-id';
|
|
99
|
+
const testJWE = 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..test.encrypted.data';
|
|
100
|
+
const testOptions = {onBehalfOf: 'test-user-uuid'};
|
|
101
|
+
const mockJwk = {kty: 'oct', k: 'test-key-material'};
|
|
102
|
+
const mockKey = {jwk: mockJwk};
|
|
103
|
+
const mockDecryptedResult = {payload: Buffer.from('decrypted binary data')};
|
|
104
|
+
let getKeyStub;
|
|
105
|
+
let joseDecryptStub;
|
|
106
|
+
|
|
107
|
+
beforeEach(() => {
|
|
108
|
+
getKeyStub = sinon.stub(webex.internal.encryption, 'getKey').resolves(mockKey);
|
|
109
|
+
|
|
110
|
+
// Mock the jose.JWE.createDecrypt chain
|
|
111
|
+
const mockDecryptor = {
|
|
112
|
+
decrypt: sinon.stub().resolves(mockDecryptedResult)
|
|
113
|
+
};
|
|
114
|
+
joseDecryptStub = sinon.stub(require('node-jose').JWE, 'createDecrypt').returns(mockDecryptor);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('should call getKey and jose.JWE.createDecrypt with correct parameters', async () => {
|
|
118
|
+
await webex.internal.encryption.decryptBinaryData(testKey, testJWE, testOptions);
|
|
119
|
+
|
|
120
|
+
assert.equal(getKeyStub.calledOnce, true);
|
|
121
|
+
assert.equal(getKeyStub.args[0][0], testKey);
|
|
122
|
+
assert.deepEqual(getKeyStub.args[0][1], testOptions);
|
|
123
|
+
|
|
124
|
+
assert.equal(joseDecryptStub.calledOnce, true);
|
|
125
|
+
assert.equal(joseDecryptStub.args[0][0], mockJwk);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('should call decrypt with ciphertext', async () => {
|
|
129
|
+
await webex.internal.encryption.decryptBinaryData(testKey, testJWE, testOptions);
|
|
130
|
+
|
|
131
|
+
const mockDecryptor = joseDecryptStub.returnValues[0];
|
|
132
|
+
assert.equal(mockDecryptor.decrypt.calledOnce, true);
|
|
133
|
+
assert.equal(mockDecryptor.decrypt.args[0][0], testJWE);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('should return the payload buffer', async () => {
|
|
137
|
+
const result = await webex.internal.encryption.decryptBinaryData(testKey, testJWE, testOptions);
|
|
138
|
+
|
|
139
|
+
assert.equal(result, mockDecryptedResult.payload);
|
|
140
|
+
assert.equal(Buffer.isBuffer(result), true);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('should work without options parameter', async () => {
|
|
144
|
+
await webex.internal.encryption.decryptBinaryData(testKey, testJWE);
|
|
145
|
+
|
|
146
|
+
assert.equal(getKeyStub.calledOnce, true);
|
|
147
|
+
assert.equal(getKeyStub.args[0][0], testKey);
|
|
148
|
+
assert.equal(getKeyStub.args[0][1], undefined);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
afterEach(() => {
|
|
152
|
+
getKeyStub.restore();
|
|
153
|
+
joseDecryptStub.restore();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
});
|
|
85
157
|
});
|
package/test/unit/spec/kms.js
CHANGED
|
@@ -60,6 +60,14 @@ describe('internal-plugin-encryption', () => {
|
|
|
60
60
|
awsKms: true,
|
|
61
61
|
});
|
|
62
62
|
|
|
63
|
+
// Upload aws cmk and role
|
|
64
|
+
await webex.internal.encryption.kms.uploadCustomerMasterKey({
|
|
65
|
+
assignedOrgId: 'xx-sds-assdf',
|
|
66
|
+
customerMasterKey: 'masterKey',
|
|
67
|
+
awsKms: true,
|
|
68
|
+
customerMasterKeyRole: 'role',
|
|
69
|
+
});
|
|
70
|
+
|
|
63
71
|
// Upload backup cmk for aws
|
|
64
72
|
await webex.internal.encryption.kms.uploadCustomerMasterKey({
|
|
65
73
|
assignedOrgId: 'xx-sds-assdf',
|
|
@@ -79,9 +87,11 @@ describe('internal-plugin-encryption', () => {
|
|
|
79
87
|
assert.equal(spyStub.args[1][0].uri, '/awsKmsCmk');
|
|
80
88
|
assert.equal(spyStub.args[1][0].customerMasterKeyBackup, undefined);
|
|
81
89
|
assert.equal(spyStub.args[2][0].uri, '/awsKmsCmk');
|
|
82
|
-
assert.equal(spyStub.args[2][0].
|
|
83
|
-
assert.equal(spyStub.args[3][0].uri, '/
|
|
84
|
-
assert.equal(spyStub.args[3][0].customerMasterKeyBackup,
|
|
90
|
+
assert.equal(spyStub.args[2][0].customerMasterKeyRole, 'role');
|
|
91
|
+
assert.equal(spyStub.args[3][0].uri, '/awsKmsCmk');
|
|
92
|
+
assert.equal(spyStub.args[3][0].customerMasterKeyBackup, 'masterKeyBackup');
|
|
93
|
+
assert.equal(spyStub.args[4][0].uri, '/cmk');
|
|
94
|
+
assert.equal(spyStub.args[4][0].customerMasterKeyBackup, undefined);
|
|
85
95
|
});
|
|
86
96
|
|
|
87
97
|
it('deleteAllCustomerMasterKeys', async () => {
|
|
@@ -98,6 +108,137 @@ describe('internal-plugin-encryption', () => {
|
|
|
98
108
|
assert.equal(spyStub.args[0][0].uri, '/cmk');
|
|
99
109
|
assert.equal(spyStub.args[1][0].uri, '/awsKmsCmk');
|
|
100
110
|
});
|
|
111
|
+
|
|
112
|
+
describe('fetchKey', () => {
|
|
113
|
+
let asKeyStub;
|
|
114
|
+
|
|
115
|
+
beforeEach(() => {
|
|
116
|
+
asKeyStub = sinon.stub(webex.internal.encryption.kms, 'asKey').resolves({
|
|
117
|
+
jwk: {mockKey: 'data'},
|
|
118
|
+
uri: 'test-key-uri',
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
afterEach(() => {
|
|
123
|
+
asKeyStub.restore();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('should fetch key normally when no redirect is needed', async () => {
|
|
127
|
+
const mockResponse = {
|
|
128
|
+
key: {jwk: {mockKey: 'data'}},
|
|
129
|
+
uri: 'test-key-uri',
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
spyStub.resolves(mockResponse);
|
|
133
|
+
|
|
134
|
+
const result = await webex.internal.encryption.kms.fetchKey({
|
|
135
|
+
uri: 'kms://test-kms.com/keys/test-key',
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
assert.calledOnce(spyStub);
|
|
139
|
+
assert.calledWith(spyStub, {
|
|
140
|
+
method: 'retrieve',
|
|
141
|
+
uri: 'kms://test-kms.com/keys/test-key',
|
|
142
|
+
});
|
|
143
|
+
assert.calledOnce(asKeyStub);
|
|
144
|
+
assert.equal(result.jwk.mockKey, 'data');
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('should handle redirect when errorCode is 301002', async () => {
|
|
148
|
+
const redirectResponse = {
|
|
149
|
+
errorCode: 301002,
|
|
150
|
+
status: 301,
|
|
151
|
+
requestId: '7ffba0b0-a5e8-497a-b856-e2b70e2eb92c',
|
|
152
|
+
reason: 'KRO, Key or Auth has been migrated. Use redirectUri for future requests',
|
|
153
|
+
redirectUri: 'kms://kms-afra.wbx2.com/keys/ce1ff0b8-fa2e-40bb-9a7f-bb36044ce1f4',
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const finalResponse = {
|
|
157
|
+
key: {jwk: {redirectedKey: 'data'}},
|
|
158
|
+
uri: 'kms://kms-afra.wbx2.com/keys/ce1ff0b8-fa2e-40bb-9a7f-bb36044ce1f4',
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
spyStub.onFirstCall().resolves(redirectResponse);
|
|
162
|
+
spyStub.onSecondCall().resolves(finalResponse);
|
|
163
|
+
|
|
164
|
+
const result = await webex.internal.encryption.kms.fetchKey({
|
|
165
|
+
uri: 'kms://test-kms.com/keys/old-key',
|
|
166
|
+
onBehalfOf: 'user123',
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
assert.calledTwice(spyStub);
|
|
170
|
+
|
|
171
|
+
// First call - original request
|
|
172
|
+
assert.calledWith(
|
|
173
|
+
spyStub.firstCall,
|
|
174
|
+
{
|
|
175
|
+
method: 'retrieve',
|
|
176
|
+
uri: 'kms://test-kms.com/keys/old-key',
|
|
177
|
+
},
|
|
178
|
+
{onBehalfOf: 'user123'}
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
// Second call - redirect request
|
|
182
|
+
assert.calledWith(
|
|
183
|
+
spyStub.secondCall,
|
|
184
|
+
{
|
|
185
|
+
method: 'retrieve',
|
|
186
|
+
uri: 'kms://kms-afra.wbx2.com/keys/ce1ff0b8-fa2e-40bb-9a7f-bb36044ce1f4',
|
|
187
|
+
},
|
|
188
|
+
{onBehalfOf: 'user123'}
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
assert.calledOnce(asKeyStub);
|
|
192
|
+
assert.equal(result.jwk.mockKey, 'data');
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('should not redirect when errorCode is not 301002', async () => {
|
|
196
|
+
const mockResponse = {
|
|
197
|
+
errorCode: 400001,
|
|
198
|
+
status: 400,
|
|
199
|
+
key: {jwk: {mockKey: 'data'}},
|
|
200
|
+
uri: 'test-key-uri',
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
spyStub.resolves(mockResponse);
|
|
204
|
+
|
|
205
|
+
const result = await webex.internal.encryption.kms.fetchKey({
|
|
206
|
+
uri: 'kms://test-kms.com/keys/test-key',
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
assert.calledOnce(spyStub);
|
|
210
|
+
assert.calledOnce(asKeyStub);
|
|
211
|
+
assert.equal(result.jwk.mockKey, 'data');
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('should not redirect when redirectUri is missing', async () => {
|
|
215
|
+
const mockResponse = {
|
|
216
|
+
errorCode: 301002,
|
|
217
|
+
status: 301,
|
|
218
|
+
key: {jwk: {mockKey: 'data'}},
|
|
219
|
+
uri: 'test-key-uri',
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
spyStub.resolves(mockResponse);
|
|
223
|
+
|
|
224
|
+
const result = await webex.internal.encryption.kms.fetchKey({
|
|
225
|
+
uri: 'kms://test-kms.com/keys/test-key',
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
assert.calledOnce(spyStub);
|
|
229
|
+
assert.calledOnce(asKeyStub);
|
|
230
|
+
assert.equal(result.jwk.mockKey, 'data');
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it('should reject when uri is not provided', async () => {
|
|
234
|
+
try {
|
|
235
|
+
await webex.internal.encryption.kms.fetchKey({});
|
|
236
|
+
assert.fail('Should have thrown an error');
|
|
237
|
+
} catch (error) {
|
|
238
|
+
assert.equal(error.message, '`options.uri` is required');
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
});
|
|
101
242
|
});
|
|
102
243
|
|
|
103
244
|
describe('KMS error', () => {
|