@webex/internal-plugin-encryption 3.0.0-beta.13 → 3.0.0-beta.15
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/README.md +1 -3
- package/dist/config.js.map +1 -1
- package/dist/encryption.js +3 -1
- package/dist/encryption.js.map +1 -1
- package/dist/ensure-buffer.browser.js +0 -2
- package/dist/ensure-buffer.browser.js.map +1 -1
- package/dist/ensure-buffer.js +5 -5
- package/dist/ensure-buffer.js.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/kms-batcher.js.map +1 -1
- package/dist/kms-certificate-validation.js +2 -2
- package/dist/kms-certificate-validation.js.map +1 -1
- package/dist/kms-dry-error-interceptor.js.map +1 -1
- package/dist/kms-errors.js.map +1 -1
- package/dist/kms.js +17 -17
- package/dist/kms.js.map +1 -1
- package/package.json +14 -14
- package/src/config.js +3 -3
- package/src/encryption.js +66 -56
- package/src/ensure-buffer.browser.js +0 -1
- package/src/ensure-buffer.js +5 -5
- package/src/index.js +120 -96
- package/src/kms-batcher.js +50 -44
- package/src/kms-certificate-validation.js +45 -47
- package/src/kms-dry-error-interceptor.js +8 -4
- package/src/kms-errors.js +19 -16
- package/src/kms.js +210 -206
- package/test/integration/spec/encryption.js +311 -230
- package/test/integration/spec/kms.js +532 -404
- package/test/integration/spec/payload-transfom.js +69 -69
- package/test/unit/spec/encryption.js +16 -13
- package/test/unit/spec/kms-certificate-validation.js +41 -32
package/README.md
CHANGED
|
@@ -21,14 +21,12 @@ npm install --save @webex/internal-plugin-encryption
|
|
|
21
21
|
## Usage
|
|
22
22
|
|
|
23
23
|
```js
|
|
24
|
-
|
|
25
24
|
import '@webex/internal-plugin-encryption';
|
|
26
25
|
|
|
27
26
|
import WebexCore from '@webex/webex-core';
|
|
28
27
|
|
|
29
28
|
const webex = new WebexCore();
|
|
30
|
-
webex.internal.encryption.WHATEVER
|
|
31
|
-
|
|
29
|
+
webex.internal.encryption.WHATEVER;
|
|
32
30
|
```
|
|
33
31
|
|
|
34
32
|
## Maintainers
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["encryption","joseOptions","compact","contentAlg","protect","kmsInitialTimeout","kmsMaxTimeout","ecdhMaxTimeout","batcherWait","batcherMaxCalls","batcherMaxWait"],"sources":["config.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nexport default {\n encryption: {\n joseOptions: {\n compact: true,\n contentAlg: 'A256GCM',\n protect: '*'
|
|
1
|
+
{"version":3,"names":["encryption","joseOptions","compact","contentAlg","protect","kmsInitialTimeout","kmsMaxTimeout","ecdhMaxTimeout","batcherWait","batcherMaxCalls","batcherMaxWait"],"sources":["config.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nexport default {\n encryption: {\n joseOptions: {\n compact: true,\n contentAlg: 'A256GCM',\n protect: '*',\n },\n\n /**\n * Initial timeout before contacting KMS with a new request\n * @type {Number}\n */\n kmsInitialTimeout: 6000,\n\n /**\n * Maximum timeout before negotiating a new ECDH key\n * and contacting KMS with a new request\n * @type {Number}\n */\n kmsMaxTimeout: 32000,\n\n /**\n * Maximum timeout after negotiating several ECDH keys\n * @type {Number}\n */\n ecdhMaxTimeout: 32000 * 3,\n\n /**\n * Debounce wait before sending a kms request\n * @type {Number}\n */\n batcherWait: 50,\n\n /**\n * Maximum queue size before sending a kms request\n * @type {Number}\n */\n batcherMaxCalls: 50,\n\n /**\n * Debounce max wait before sending a kms metric\n * @type {Number}\n */\n batcherMaxWait: 150,\n },\n};\n"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;eAEe;EACbA,UAAU,EAAE;IACVC,WAAW,EAAE;MACXC,OAAO,EAAE,IADE;MAEXC,UAAU,EAAE,SAFD;MAGXC,OAAO,EAAE;IAHE,CADH;;IAOV;AACJ;AACA;AACA;IACIC,iBAAiB,EAAE,IAXT;;IAaV;AACJ;AACA;AACA;AACA;IACIC,aAAa,EAAE,KAlBL;;IAoBV;AACJ;AACA;AACA;IACIC,cAAc,EAAE,QAAQ,CAxBd;;IA0BV;AACJ;AACA;AACA;IACIC,WAAW,EAAE,EA9BH;;IAgCV;AACJ;AACA;AACA;IACIC,eAAe,EAAE,EApCP;;IAsCV;AACJ;AACA;AACA;IACIC,cAAc,EAAE;EA1CN;AADC,C"}
|
package/dist/encryption.js
CHANGED
|
@@ -115,6 +115,7 @@ var Encryption = _webexCore.WebexPlugin.extend({
|
|
|
115
115
|
var shunt = new _events.EventEmitter();
|
|
116
116
|
|
|
117
117
|
var promise = this._fetchDownloadUrl(scr, options).then(function (uri) {
|
|
118
|
+
// eslint-disable-next-line no-shadow
|
|
118
119
|
var options = {
|
|
119
120
|
method: 'GET',
|
|
120
121
|
uri: uri,
|
|
@@ -166,6 +167,7 @@ var Encryption = _webexCore.WebexPlugin.extend({
|
|
|
166
167
|
allow: options.params.allow
|
|
167
168
|
}) : inputBody
|
|
168
169
|
}).then(function (res) {
|
|
170
|
+
// eslint-disable-next-line no-shadow
|
|
169
171
|
var url = res.body.endpoints[scr.loc];
|
|
170
172
|
|
|
171
173
|
if (!url) {
|
|
@@ -273,7 +275,7 @@ var Encryption = _webexCore.WebexPlugin.extend({
|
|
|
273
275
|
}));
|
|
274
276
|
});
|
|
275
277
|
},
|
|
276
|
-
version: "3.0.0-beta.
|
|
278
|
+
version: "3.0.0-beta.15"
|
|
277
279
|
});
|
|
278
280
|
/**
|
|
279
281
|
* JSON.stringify replacer that ensures private key data is serialized.
|
package/dist/encryption.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["Encryption","WebexPlugin","extend","children","kms","KMS","namespace","processKmsMessageEvent","event","decryptBinary","scr","buffer","ensureBuffer","then","b","length","byteLength","reject","Error","decrypt","decryptScr","key","cipherScr","options","getKey","k","SCR","fromJWE","jwk","decryptText","ciphertext","jose","JWE","createDecrypt","result","plaintext","toString","download","loc","shunt","EventEmitter","promise","_fetchDownloadUrl","uri","method","responseType","ret","request","transferEvents","res","body","proxyEvents","logger","info","process","env","NODE_ENV","includes","resolve","inputBody","endpoints","endpointUrl","url","parse","protocol","pathname","format","allow","params","warn","encryptBinary","file","create","encrypt","cdata","encryptScr","toJWE","encryptText","createEncrypt","config","joseOptions","header","alg","reference","final","onBehalfOf","asKey","storageKey","unboundedStorage","get","keyString","JSON","keyObject","catch","fetchKey","tap","put","replacer","v","json","toJSON"],"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)\n .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)\n .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)\n .then((k) => jose.JWE\n .createDecrypt(k.jwk)\n .decrypt(ciphertext)\n .then((result) => result.plaintext.toString()));\n },\n\n /**\n * Validate and initiate a Download request for requested file\n *\n * @param {Object} scr - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise}\n */\n download(scr, options) {\n /* istanbul ignore if */\n if (!scr.loc) {\n return Promise.reject(new Error('`scr.loc` is required'));\n }\n\n const shunt = new EventEmitter();\n const promise = this._fetchDownloadUrl(scr, options)\n .then((uri) => {\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 *\n * @param {Object} scr - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise} url of the downloadable file\n */\n _fetchDownloadUrl(scr, options) {\n this.logger.info('encryption: retrieving download url for encrypted file');\n\n if (process.env.NODE_ENV !== 'production' && scr.loc.includes('localhost')) {\n this.logger.info('encryption: bypassing webex files because this looks to be a test file on localhost');\n\n return Promise.resolve(scr.loc);\n }\n\n const inputBody = {\n endpoints: [scr.loc]\n };\n const endpointUrl = url.parse(scr.loc);\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: options ? {\n ...inputBody,\n allow: options.params.allow\n } : inputBody\n })\n .then((res) => {\n const url = res.body.endpoints[scr.loc];\n\n if (!url) {\n this.logger.warn('encryption: could not determine download url for `scr.loc`; attempting to download `scr.loc` directly');\n\n return scr.loc;\n }\n this.logger.info('encryption: retrieved download url for encrypted file');\n\n return url;\n });\n },\n\n encryptBinary(file) {\n return ensureBuffer(file)\n .then((buffer) => SCR.create()\n .then((scr) => scr.encrypt(buffer)\n .then(ensureBuffer)\n // eslint-disable-next-line max-nested-callbacks\n .then((cdata) => ({scr, cdata}))));\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 - 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 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)\n .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)\n .then((k) => jose.JWE\n .createEncrypt(this.config.joseOptions, {\n key: k.jwk,\n header: {\n alg: 'dir'\n },\n reference: null\n })\n .final(plaintext, 'utf8'));\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.get(storageKey)\n .then((keyString) => JSON.parse(keyString))\n .then((keyObject) => this.kms.asKey(keyObject))\n .catch(() => this.kms.fetchKey({uri, onBehalfOf})\n .then(tap((key) => this.unboundedStorage.put(storageKey, JSON.stringify(key, replacer)))));\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;;AACA;;AAEA;;AACA;;AACA;;AACA;;AAEA;;AACA;;;;;;AAEA,IAAMA,UAAU,GAAGC,sBAAA,CAAYC,MAAZ,CAAmB;EACpCC,QAAQ,EAAE;IACRC,GAAG,EAAEC;EADG,CAD0B;EAKpCC,SAAS,EAAE,YALyB;EAOpCC,sBAPoC,kCAObC,KAPa,EAON;IAC5B,OAAO,KAAKJ,GAAL,CAASG,sBAAT,CAAgCC,KAAhC,CAAP;EACD,CATmC;EAWpCC,aAXoC,yBAWtBC,GAXsB,EAWjBC,MAXiB,EAWT;IACzB,OAAO,IAAAC,qBAAA,EAAaD,MAAb,EACJE,IADI,CACC,UAACC,CAAD,EAAO;MACX;MACA,IAAIH,MAAM,CAACI,MAAP,KAAkB,CAAlB,IAAuBJ,MAAM,CAACK,UAAP,KAAsB,CAAjD,EAAoD;QAClD,OAAO,iBAAQC,MAAR,CAAe,IAAIC,KAAJ,CAAU,yCAAV,CAAf,CAAP;MACD;;MAED,OAAOR,GAAG,CAACS,OAAJ,CAAYL,CAAZ,CAAP;IACD,CARI,CAAP;EASD,CArBmC;;EAuBpC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEM,UAhCoC,sBAgCzBC,GAhCyB,EAgCpBC,SAhCoB,EAgCTC,OAhCS,EAgCA;IAClC,OAAO,KAAKC,M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AlB,EACVxE,IADU,CACL,IAAAkF,WAAA,EAAI,UAAC1E,GAAD;QAAA,OAAS,MAAI,CAACmE,gBAAL,CAAsBQ,GAAtB,CAA0BT,UAA1B,EAAsC,wBAAelE,GAAf,EAAoB4E,QAApB,CAAtC,CAAT;MAAA,CAAJ,CADK,CAAN;IAAA,CAHF,CAAP;EAKD,CAlNmC;EAAA;AAAA,CAAnB,CAAnB;AAqNA;AACA;AACA;AACA;AACA;AACA;;;AACA,SAASA,QAAT,CAAkBxE,CAAlB,EAAqByE,CAArB,EAAwB;EACtB,IAAIzE,CAAC,KAAK,KAAV,EAAiB;IACf;IACA;IACA,IAAM0E,IAAI,GAAG,KAAK1E,CAAL,EAAQ2E,MAAR,CAAe,IAAf,CAAb;IAEA,OAAOD,IAAP;EACD;;EAED,OAAOD,CAAP;AACD;;eAEclG,U"}
|
|
1
|
+
{"version":3,"names":["Encryption","WebexPlugin","extend","children","kms","KMS","namespace","processKmsMessageEvent","event","decryptBinary","scr","buffer","ensureBuffer","then","b","length","byteLength","reject","Error","decrypt","decryptScr","key","cipherScr","options","getKey","k","SCR","fromJWE","jwk","decryptText","ciphertext","jose","JWE","createDecrypt","result","plaintext","toString","download","loc","shunt","EventEmitter","promise","_fetchDownloadUrl","uri","method","responseType","ret","request","transferEvents","res","body","proxyEvents","logger","info","process","env","NODE_ENV","includes","resolve","inputBody","endpoints","endpointUrl","url","parse","protocol","pathname","format","allow","params","warn","encryptBinary","file","create","encrypt","cdata","encryptScr","toJWE","encryptText","createEncrypt","config","joseOptions","header","alg","reference","final","onBehalfOf","asKey","storageKey","unboundedStorage","get","keyString","JSON","keyObject","catch","fetchKey","tap","put","replacer","v","json","toJSON"],"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 *\n * @param {Object} scr - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise}\n */\n download(scr, options) {\n /* istanbul ignore if */\n if (!scr.loc) {\n return Promise.reject(new Error('`scr.loc` is required'));\n }\n\n const shunt = new EventEmitter();\n const promise = this._fetchDownloadUrl(scr, 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 *\n * @param {Object} scr - Plaintext\n * @param {Object} options - optional parameters to download a file\n * @returns {promise} url of the downloadable file\n */\n _fetchDownloadUrl(scr, options) {\n this.logger.info('encryption: retrieving download url for encrypted file');\n\n if (process.env.NODE_ENV !== 'production' && scr.loc.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(scr.loc);\n }\n\n const inputBody = {\n endpoints: [scr.loc],\n };\n const endpointUrl = url.parse(scr.loc);\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: options\n ? {\n ...inputBody,\n allow: options.params.allow,\n }\n : inputBody,\n }).then((res) => {\n // eslint-disable-next-line no-shadow\n const url = res.body.endpoints[scr.loc];\n\n if (!url) {\n this.logger.warn(\n 'encryption: could not determine download url for `scr.loc`; attempting to download `scr.loc` directly'\n );\n\n return scr.loc;\n }\n this.logger.info('encryption: retrieved download url for encrypted file');\n\n return url;\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 - 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 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;;AACA;;AAEA;;AACA;;AACA;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,EAAiB;IACf;IACA;IACA,IAAM0E,IAAI,GAAG,KAAK1E,CAAL,EAAQ2E,MAAR,CAAe,IAAf,CAAb;IAEA,OAAOD,IAAP;EACD;;EAED,OAAOD,CAAP;AACD;;eAEclG,U"}
|
|
@@ -18,8 +18,6 @@ var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/pr
|
|
|
18
18
|
|
|
19
19
|
/* eslint-env: browser */
|
|
20
20
|
|
|
21
|
-
/* global FileReader */
|
|
22
|
-
|
|
23
21
|
/**
|
|
24
22
|
* Ensures the provider buffer is, indeed, an ArrayBuffer; converts File and
|
|
25
23
|
* Blob objects to ArrayBuffers.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["ensureBuffer","buffer","ArrayBuffer","resolve","toArrayBuffer","reject","fr","FileReader","onload","Uint8Array","result","onerror","readAsArrayBuffer"],"sources":["ensure-buffer.browser.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\n/* eslint-env: browser */\n
|
|
1
|
+
{"version":3,"names":["ensureBuffer","buffer","ArrayBuffer","resolve","toArrayBuffer","reject","fr","FileReader","onload","Uint8Array","result","onerror","readAsArrayBuffer"],"sources":["ensure-buffer.browser.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\n/* eslint-env: browser */\n\n/**\n * Ensures the provider buffer is, indeed, an ArrayBuffer; converts File and\n * Blob objects to ArrayBuffers.\n * @param {mixed} buffer\n * @returns {Promise<ArrayBuffer>}\n */\nexport default function ensureBuffer(buffer) {\n if (buffer instanceof ArrayBuffer) {\n return Promise.resolve(buffer);\n }\n\n if (buffer.toArrayBuffer) {\n return Promise.resolve(buffer.toArrayBuffer());\n }\n\n if (buffer.buffer) {\n return Promise.resolve(buffer.buffer);\n }\n\n return new Promise((resolve, reject) => {\n const fr = new FileReader();\n\n fr.onload = function onload() {\n resolve(new Uint8Array(this.result));\n };\n\n fr.onerror = reject;\n\n fr.readAsArrayBuffer(buffer);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,YAAT,CAAsBC,MAAtB,EAA8B;EAC3C,IAAIA,MAAM,YAAYC,WAAtB,EAAmC;IACjC,OAAO,iBAAQC,OAAR,CAAgBF,MAAhB,CAAP;EACD;;EAED,IAAIA,MAAM,CAACG,aAAX,EAA0B;IACxB,OAAO,iBAAQD,OAAR,CAAgBF,MAAM,CAACG,aAAP,EAAhB,CAAP;EACD;;EAED,IAAIH,MAAM,CAACA,MAAX,EAAmB;IACjB,OAAO,iBAAQE,OAAR,CAAgBF,MAAM,CAACA,MAAvB,CAAP;EACD;;EAED,OAAO,qBAAY,UAACE,OAAD,EAAUE,MAAV,EAAqB;IACtC,IAAMC,EAAE,GAAG,IAAIC,UAAJ,EAAX;;IAEAD,EAAE,CAACE,MAAH,GAAY,SAASA,MAAT,GAAkB;MAC5BL,OAAO,CAAC,IAAIM,UAAJ,CAAe,KAAKC,MAApB,CAAD,CAAP;IACD,CAFD;;IAIAJ,EAAE,CAACK,OAAH,GAAaN,MAAb;IAEAC,EAAE,CAACM,iBAAH,CAAqBX,MAArB;EACD,CAVM,CAAP;AAWD"}
|
package/dist/ensure-buffer.js
CHANGED
|
@@ -19,11 +19,11 @@ var _common = require("@webex/common");
|
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
|
-
* Ensures the provider Buffer is, indeed, a Buffer; sometimes, they seem to be
|
|
23
|
-
* byte-arrays instead of proper Buffer objects.
|
|
24
|
-
* @param {mixed} buffer
|
|
25
|
-
* @returns {Promise<Buffer>}
|
|
26
|
-
*/
|
|
22
|
+
* Ensures the provider Buffer is, indeed, a Buffer; sometimes, they seem to be
|
|
23
|
+
* byte-arrays instead of proper Buffer objects.
|
|
24
|
+
* @param {mixed} buffer
|
|
25
|
+
* @returns {Promise<Buffer>}
|
|
26
|
+
*/
|
|
27
27
|
function ensureBuffer(buffer) {
|
|
28
28
|
/* istanbul ignore if */
|
|
29
29
|
if (!(0, _common.isBuffer)(buffer)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["ensureBuffer","buffer","isBuffer","reject","Error","resolve"],"sources":["ensure-buffer.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {isBuffer} from '@webex/common';\n\n/**\n* Ensures the provider Buffer is, indeed, a Buffer; sometimes, they seem to be\n* byte-arrays instead of proper Buffer objects.\n* @param {mixed} buffer\n* @returns {Promise<Buffer>}\n*/\nexport default function ensureBuffer(buffer) {\n /* istanbul ignore if */\n if (!isBuffer(buffer)) {\n return Promise.reject(new Error('`buffer` must be a buffer'));\n }\n\n return Promise.resolve(buffer);\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA;;AAJA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,YAAT,CAAsBC,MAAtB,EAA8B;EAC3C;EACA,IAAI,CAAC,IAAAC,gBAAA,EAASD,MAAT,CAAL,EAAuB;IACrB,OAAO,iBAAQE,MAAR,CAAe,IAAIC,KAAJ,CAAU,2BAAV,CAAf,CAAP;EACD;;EAED,OAAO,iBAAQC,OAAR,CAAgBJ,MAAhB,CAAP;AACD"}
|
|
1
|
+
{"version":3,"names":["ensureBuffer","buffer","isBuffer","reject","Error","resolve"],"sources":["ensure-buffer.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {isBuffer} from '@webex/common';\n\n/**\n * Ensures the provider Buffer is, indeed, a Buffer; sometimes, they seem to be\n * byte-arrays instead of proper Buffer objects.\n * @param {mixed} buffer\n * @returns {Promise<Buffer>}\n */\nexport default function ensureBuffer(buffer) {\n /* istanbul ignore if */\n if (!isBuffer(buffer)) {\n return Promise.reject(new Error('`buffer` must be a buffer'));\n }\n\n return Promise.resolve(buffer);\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA;;AAJA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACe,SAASA,YAAT,CAAsBC,MAAtB,EAA8B;EAC3C;EACA,IAAI,CAAC,IAAAC,gBAAA,EAASD,MAAT,CAAL,EAAuB;IACrB,OAAO,iBAAQE,MAAR,CAAe,IAAIC,KAAJ,CAAU,2BAAV,CAAf,CAAP;EACD;;EAED,OAAO,iBAAQC,OAAR,CAAgBJ,MAAhB,CAAP;AACD"}
|
package/dist/index.js
CHANGED
|
@@ -44,6 +44,10 @@ var _isObject2 = _interopRequireDefault(require("lodash/isObject"));
|
|
|
44
44
|
|
|
45
45
|
var _has2 = _interopRequireDefault(require("lodash/has"));
|
|
46
46
|
|
|
47
|
+
require("@webex/internal-plugin-device");
|
|
48
|
+
|
|
49
|
+
require("@webex/internal-plugin-mercury");
|
|
50
|
+
|
|
47
51
|
var _webexCore = require("@webex/webex-core");
|
|
48
52
|
|
|
49
53
|
var _encryption = _interopRequireDefault(require("./encryption"));
|
|
@@ -52,10 +56,6 @@ var _config = _interopRequireDefault(require("./config"));
|
|
|
52
56
|
|
|
53
57
|
var _kmsErrors = require("./kms-errors");
|
|
54
58
|
|
|
55
|
-
require("@webex/internal-plugin-device");
|
|
56
|
-
|
|
57
|
-
require("@webex/internal-plugin-mercury");
|
|
58
|
-
|
|
59
59
|
var _kmsDryErrorInterceptor = _interopRequireDefault(require("./kms-dry-error-interceptor"));
|
|
60
60
|
|
|
61
61
|
var _kms = _interopRequireDefault(require("./kms"));
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["interceptors","process","env","NODE_ENV","KmsDryErrorInterceptor","create","registerInternalPlugin","Encryption","payloadTransformer","predicates","name","direction","test","ctx","options","resolve","body","kmsMessage","keyUris","length","resourceUri","includes","uri","extract","response","reason","Boolean","errorCode","transforms","fn","object","webex","internal","encryption","kms","prepareRequest","then","req","wrapped","decryptKmsMessage","promises","errors","map","error","description","desc","push","message","all","reject","DryError","config"],"sources":["index.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\n// Note: There's a bug where if bind gets replayed because of a timeout in which\n// the original request eventually completed, there'll be an error indicating\n// the key can't be bound (because it already has been). This could be mitigated\n// by using Promise.race to resolve replays (as more requests get enqueue for a\n// specific action, accept whichever one completes first).\n\nimport {registerInternalPlugin} from '@webex/webex-core';\nimport {has, isObject, isString} from 'lodash';\n\nimport Encryption from './encryption';\nimport config from './config';\nimport {DryError} from './kms-errors';\nimport
|
|
1
|
+
{"version":3,"names":["interceptors","process","env","NODE_ENV","KmsDryErrorInterceptor","create","registerInternalPlugin","Encryption","payloadTransformer","predicates","name","direction","test","ctx","options","resolve","body","kmsMessage","keyUris","length","resourceUri","includes","uri","extract","response","reason","Boolean","errorCode","transforms","fn","object","webex","internal","encryption","kms","prepareRequest","then","req","wrapped","decryptKmsMessage","promises","errors","map","error","description","desc","push","message","all","reject","DryError","config"],"sources":["index.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\n// Note: There's a bug where if bind gets replayed because of a timeout in which\n// the original request eventually completed, there'll be an error indicating\n// the key can't be bound (because it already has been). This could be mitigated\n// by using Promise.race to resolve replays (as more requests get enqueue for a\n// specific action, accept whichever one completes first).\n\nimport '@webex/internal-plugin-device';\n\nimport '@webex/internal-plugin-mercury';\n\nimport {registerInternalPlugin} from '@webex/webex-core';\nimport {has, isObject, isString} from 'lodash';\n\nimport Encryption from './encryption';\nimport config from './config';\nimport {DryError} from './kms-errors';\n\nimport KmsDryErrorInterceptor from './kms-dry-error-interceptor';\n\nlet interceptors;\n\nif (process.env.NODE_ENV === 'test') {\n interceptors = {\n KmsDryErrorInterceptor: KmsDryErrorInterceptor.create,\n };\n}\n\nregisterInternalPlugin('encryption', Encryption, {\n payloadTransformer: {\n predicates: [\n {\n name: 'encryptKmsMessage',\n direction: 'outbound',\n // I don't see any practical way to reduce complexity here.\n // eslint-disable-next-line complexity\n test(ctx, options) {\n if (!has(options, 'body.kmsMessage')) {\n return Promise.resolve(false);\n }\n\n if (!isObject(options.body.kmsMessage)) {\n return Promise.resolve(false);\n }\n\n // If this is a template for a kms message, assume another transform\n // will fill it in later. This is a bit of a leaky abstraction, but the\n // alternative is building a complex rules engine for controlling\n // ordering of transforms\n if (options.body.kmsMessage.keyUris && options.body.kmsMessage.keyUris.length === 0) {\n return Promise.resolve(false);\n }\n if (\n options.body.kmsMessage.resourceUri &&\n (options.body.kmsMessage.resourceUri.includes('<KRO>') ||\n options.body.kmsMessage.resourceUri.includes('<KEYURL>'))\n ) {\n return Promise.resolve(false);\n }\n if (\n options.body.kmsMessage.uri &&\n (options.body.kmsMessage.uri.includes('<KRO>') ||\n options.body.kmsMessage.uri.includes('<KEYURL>'))\n ) {\n return Promise.resolve(false);\n }\n\n return Promise.resolve(true);\n },\n extract(options) {\n return Promise.resolve(options.body);\n },\n },\n {\n name: 'decryptKmsMessage',\n direction: 'inbound',\n test(ctx, response) {\n return Promise.resolve(\n has(response, 'body.kmsMessage') && isString(response.body.kmsMessage)\n );\n },\n extract(response) {\n return Promise.resolve(response.body);\n },\n },\n {\n name: 'decryptErrorResponse',\n direction: 'inbound',\n test(ctx, reason) {\n return Promise.resolve(Boolean(reason.body && reason.body.errorCode === 1900000));\n },\n extract(reason) {\n return Promise.resolve(reason);\n },\n },\n ],\n transforms: [\n {\n name: 'encryptKmsMessage',\n fn(ctx, object) {\n if (!object) {\n return Promise.resolve();\n }\n\n if (!object.kmsMessage) {\n return Promise.resolve();\n }\n\n if (isString(object.kmsMessage)) {\n return Promise.resolve();\n }\n\n return ctx.webex.internal.encryption.kms.prepareRequest(object.kmsMessage).then((req) => {\n object.kmsMessage = req.wrapped;\n });\n },\n },\n {\n name: 'decryptKmsMessage',\n fn(ctx, object) {\n return ctx.webex.internal.encryption.kms\n .decryptKmsMessage(object.kmsMessage)\n .then((kmsMessage) => {\n object.kmsMessage = kmsMessage;\n });\n },\n },\n {\n name: 'decryptErrorResponse',\n fn(ctx, reason) {\n const promises = reason.body.errors.map((error) =>\n ctx.webex.internal.encryption.kms.decryptKmsMessage(error.description).then((desc) => {\n error.description = desc;\n })\n );\n\n promises.push(\n ctx.webex.internal.encryption.kms\n .decryptKmsMessage(reason.body.message)\n .then((kmsMessage) => {\n reason.body.message = kmsMessage;\n })\n );\n\n return Promise.all(promises).then(() => Promise.reject(new DryError(reason)));\n },\n },\n ],\n },\n interceptors,\n config,\n});\n\nexport {default} from './encryption';\nexport {default as KMS} from './kms';\nexport {KmsError, DryError} from './kms-errors';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;;AAEA;;AAEA;;AAGA;;AACA;;AACA;;AAEA;;AAwIA;;AA7JA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAeA,IAAIA,YAAJ;;AAEA,IAAIC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,MAA7B,EAAqC;EACnCH,YAAY,GAAG;IACbI,sBAAsB,EAAEA,+BAAA,CAAuBC;EADlC,CAAf;AAGD;;AAED,IAAAC,iCAAA,EAAuB,YAAvB,EAAqCC,mBAArC,EAAiD;EAC/CC,kBAAkB,EAAE;IAClBC,UAAU,EAAE,CACV;MACEC,IAAI,EAAE,mBADR;MAEEC,SAAS,EAAE,UAFb;MAGE;MACA;MACAC,IALF,gBAKOC,GALP,EAKYC,OALZ,EAKqB;QACjB,IAAI,CAAC,mBAAIA,OAAJ,EAAa,iBAAb,CAAL,EAAsC;UACpC,OAAO,iBAAQC,OAAR,CAAgB,KAAhB,CAAP;QACD;;QAED,IAAI,CAAC,wBAASD,OAAO,CAACE,IAAR,CAAaC,UAAtB,CAAL,EAAwC;UACtC,OAAO,iBAAQF,OAAR,CAAgB,KAAhB,CAAP;QACD,CAPgB,CASjB;QACA;QACA;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FI,CAEC,UAACnB,UAAD,EAAgB;UACpBa,MAAM,CAACb,UAAP,GAAoBA,UAApB;QACD,CAJI,CAAP;MAKD;IARH,CArBU,EA+BV;MACEP,IAAI,EAAE,sBADR;MAEEmB,EAFF,cAEKhB,GAFL,EAEUY,MAFV,EAEkB;QACd,IAAMe,QAAQ,GAAGf,MAAM,CAACT,IAAP,CAAYyB,MAAZ,CAAmBC,GAAnB,CAAuB,UAACC,KAAD;UAAA,OACtC9B,GAAG,CAACkB,KAAJ,CAAUC,QAAV,CAAmBC,UAAnB,CAA8BC,GAA9B,CAAkCK,iBAAlC,CAAoDI,KAAK,CAACC,WAA1D,EAAuER,IAAvE,CAA4E,UAACS,IAAD,EAAU;YACpFF,KAAK,CAACC,WAAN,GAAoBC,IAApB;UACD,CAFD,CADsC;QAAA,CAAvB,CAAjB;QAMAL,QAAQ,CAACM,IAAT,CACEjC,GAAG,CAACkB,KAAJ,CAAUC,QAAV,CAAmBC,UAAnB,CAA8BC,GAA9B,CACGK,iBADH,CACqBd,MAAM,CAACT,IAAP,CAAY+B,OADjC,EAEGX,IAFH,CAEQ,UAACnB,UAAD,EAAgB;UACpBQ,MAAM,CAACT,IAAP,CAAY+B,OAAZ,GAAsB9B,UAAtB;QACD,CAJH,CADF;QAQA,OAAO,iBAAQ+B,GAAR,CAAYR,QAAZ,EAAsBJ,IAAtB,CAA2B;UAAA,OAAM,iBAAQa,MAAR,CAAe,IAAIC,mBAAJ,CAAazB,MAAb,CAAf,CAAN;QAAA,CAA3B,CAAP;MACD;IAlBH,CA/BU;EAnEM,CAD2B;EAyH/CzB,YAAY,EAAZA,YAzH+C;EA0H/CmD,MAAM,EAANA;AA1H+C,CAAjD"}
|
package/dist/kms-batcher.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["TIMEOUT_SYMBOL","KmsBatcher","Batcher","extend","namespace","processKmsMessageEvent","event","logger","info","all","encryption","kmsMessages","map","kmsMessage","resolve","process","env","NODE_ENV","body","acceptItem","prepareItem","item","getDeferredForRequest","then","defer","timeout","Error","timer","safeSetTimeout","warn","requestId","handleItemFailure","KmsTimeoutError","request","promise","clearTimeout","catch","prepareRequest","queue","webex","internal","kms","_getKMSCluster","cluster","destination","req","wrapped","submitHttpRequest","payload","length","method","service","resource","handleHttpSuccess","didItemFail","status","handleItemSuccess","getDeferredForResponse","reason","reject","KmsError","fingerprintRequest","fingerprintResponse"],"sources":["kms-batcher.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {safeSetTimeout} from '@webex/common-timers';\nimport {Batcher} from '@webex/webex-core';\n\nimport {KmsError, KmsTimeoutError} from './kms-errors';\n\nexport const TIMEOUT_SYMBOL = Symbol('TIMEOUT_SYMBOL');\n\n/**\n * @class\n */\nconst KmsBatcher = Batcher.extend({\n namespace: 'Encryption',\n\n /**\n * Accepts a kmsMessage event and passes its contents to acceptItem\n * @param {Object} event\n * @returns {Promise}\n */\n processKmsMessageEvent(event) {\n this.logger.info('kms-batcher: received kms message');\n\n return Promise.all(event.encryption.kmsMessages.map((kmsMessage)
|
|
1
|
+
{"version":3,"names":["TIMEOUT_SYMBOL","KmsBatcher","Batcher","extend","namespace","processKmsMessageEvent","event","logger","info","all","encryption","kmsMessages","map","kmsMessage","resolve","process","env","NODE_ENV","body","acceptItem","prepareItem","item","getDeferredForRequest","then","defer","timeout","Error","timer","safeSetTimeout","warn","requestId","handleItemFailure","KmsTimeoutError","request","promise","clearTimeout","catch","prepareRequest","queue","webex","internal","kms","_getKMSCluster","cluster","destination","req","wrapped","submitHttpRequest","payload","length","method","service","resource","handleHttpSuccess","didItemFail","status","handleItemSuccess","getDeferredForResponse","reason","reject","KmsError","fingerprintRequest","fingerprintResponse"],"sources":["kms-batcher.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {safeSetTimeout} from '@webex/common-timers';\nimport {Batcher} from '@webex/webex-core';\n\nimport {KmsError, KmsTimeoutError} from './kms-errors';\n\nexport const TIMEOUT_SYMBOL = Symbol('TIMEOUT_SYMBOL');\n\n/**\n * @class\n */\nconst KmsBatcher = Batcher.extend({\n namespace: 'Encryption',\n\n /**\n * Accepts a kmsMessage event and passes its contents to acceptItem\n * @param {Object} event\n * @returns {Promise}\n */\n processKmsMessageEvent(event) {\n this.logger.info('kms-batcher: received kms message');\n\n return Promise.all(\n event.encryption.kmsMessages.map(\n (kmsMessage) =>\n new Promise((resolve) => {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n this.logger.info('kms-batcher:', kmsMessage.body);\n }\n\n resolve(this.acceptItem(kmsMessage));\n })\n )\n );\n },\n\n /**\n * Attaches a timeout to the given KMS message\n * @param {Object} item\n * @returns {Promise<Object>}\n */\n prepareItem(item) {\n return this.getDeferredForRequest(item).then((defer) => {\n const timeout = item[TIMEOUT_SYMBOL];\n\n /* istanbul ignore if */\n if (!timeout) {\n throw new Error('timeout is required');\n }\n\n const timer = safeSetTimeout(() => {\n this.logger.warn(\n `kms: request timed out; request id: ${item.requestId}; timeout: ${timeout}`\n );\n this.handleItemFailure(\n item,\n new KmsTimeoutError({\n timeout,\n request: item,\n })\n );\n }, timeout);\n\n // Reminder: reassign `promise` is not a viable means of inserting into\n // the Promise chain\n defer.promise.then(() => clearTimeout(timer));\n defer.promise.catch(() => clearTimeout(timer));\n\n return item;\n });\n },\n\n /**\n * Attaches the final bits of cluster info to the payload\n * @param {Array} queue\n * @returns {Promise<Array>}\n */\n prepareRequest(queue) {\n return this.webex.internal.encryption.kms._getKMSCluster().then((cluster) => ({\n destination: cluster,\n kmsMessages: queue.map((req) => req.wrapped),\n }));\n },\n\n /**\n * @param {Object} payload\n * @returns {Promise<HttpResponseObject>}\n */\n submitHttpRequest(payload) {\n this.logger.info('kms: batched-request-length', payload.kmsMessages.length);\n\n return this.webex.request({\n method: 'POST',\n service: 'encryption',\n resource: '/kms/messages',\n body: payload,\n });\n },\n\n /**\n * Does nothing; the http response doesn't carry our response data\n * @returns {Promise}\n */\n handleHttpSuccess() {\n return Promise.resolve();\n },\n\n /**\n * @param {Object} item\n * @returns {Promise<boolean>}\n */\n didItemFail(item) {\n return Promise.resolve(item.status >= 400);\n },\n\n /**\n * @param {Object} item\n * @returns {Promise}\n */\n handleItemSuccess(item) {\n return this.getDeferredForResponse(item).then((defer) => {\n defer.resolve(item.body);\n });\n },\n\n /**\n * @param {Object} item\n * @param {KmsError} [reason]\n * @returns {Promise}\n */\n handleItemFailure(item, reason) {\n return this.getDeferredForResponse(item).then((defer) => {\n defer.reject(reason || new KmsError(item.body));\n });\n },\n\n /**\n * @param {Object} item\n * @returns {Promise}\n */\n fingerprintRequest(item) {\n return Promise.resolve(item.requestId);\n },\n\n /**\n * @param {Object} item\n * @returns {Promise}\n */\n fingerprintResponse(item) {\n return Promise.resolve(item.requestId);\n },\n});\n\nexport default KmsBatcher;\n"],"mappings":";;;;;;;;;;;;;;;;AAIA;;AACA;;AAEA;;AAPA;AACA;AACA;AAOO,IAAMA,cAAc,GAAG,qBAAO,gBAAP,CAAvB;AAEP;AACA;AACA;;;;AACA,IAAMC,UAAU,GAAGC,kBAAA,CAAQC,MAAR,CAAe;EAChCC,SAAS,EAAE,YADqB;;EAGhC;AACF;AACA;AACA;AACA;EACEC,sBARgC,kCAQTC,KARS,EAQF;IAAA;;IAC5B,KAAKC,MAAL,CAAYC,IAAZ,CAAiB,mCAAjB;IAEA,OAAO,iBAAQC,GAAR,CACLH,KAAK,CAACI,UAAN,CAAiBC,WAAjB,CAA6BC,GAA7B,CACE,UAACC,UAAD;MAAA,OACE,qBAAY,UAACC,OAAD,EAAa;QACvB;QACA,IAAIC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAA7B,EAA2C;UACzC,KAAI,CAACV,MAAL,CAAYC,IAAZ,CAAiB,cAAjB,EAAiCK,UAAU,CAACK,IAA5C;QACD;;QAEDJ,OAAO,CAAC,KAAI,C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;;EA8HhC;AACF;AACA;AACA;EACE2C,kBAlIgC,8BAkIbxC,IAlIa,EAkIP;IACvB,OAAO,iBAAQP,OAAR,CAAgBO,IAAI,CAACS,SAArB,CAAP;EACD,CApI+B;;EAsIhC;AACF;AACA;AACA;EACEgC,mBA1IgC,+BA0IZzC,IA1IY,EA0IN;IACxB,OAAO,iBAAQP,OAAR,CAAgBO,IAAI,CAACS,SAArB,CAAP;EACD;AA5I+B,CAAf,CAAnB;;eA+Ie7B,U"}
|
|
@@ -143,7 +143,7 @@ var validateKidHeader = function validateKidHeader(_ref2) {
|
|
|
143
143
|
var kid = _ref2.kid;
|
|
144
144
|
|
|
145
145
|
if (!(0, _validUrl.isUri)(kid)) {
|
|
146
|
-
throwError('
|
|
146
|
+
throwError("'kid' is not a valid URI");
|
|
147
147
|
}
|
|
148
148
|
|
|
149
149
|
if ((0, _url.parse)(kid).protocol !== VALID_KID_PROTOCOL) {
|
|
@@ -241,7 +241,7 @@ var validateCommonName = function validateCommonName(_ref3, _ref4) {
|
|
|
241
241
|
}
|
|
242
242
|
|
|
243
243
|
if (!validationSuccessful) {
|
|
244
|
-
throwError(
|
|
244
|
+
throwError("hostname of the 1st certificate does not match 'kid'");
|
|
245
245
|
}
|
|
246
246
|
};
|
|
247
247
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["setEngine","crypto","CryptoEngine","name","subtle","VALID_KTY","VALID_KID_PROTOCOL","X509_COMMON_NAME_KEY","X509_SUBJECT_ALT_NAME_KEY","KMSError","message","kmsError","Error","throwError","err","decodeCert","pem","der","Buffer","from","ber","Uint8Array","buffer","asn1","fromBER","Certificate","schema","result","validateKtyHeader","kty","validateKidHeader","kid","isUri","parseUrl","protocol","validateCommonName","certificate","kidHostname","hostname","validationSuccessful","extensions","extension","extnID","altNames","parsedValue","entry","san","value","subjectAttributes","subject","typesAndValues","attribute","type","commonName","valueBlock","validatePublicCertificate","publicExponent","e","modulus","n","encode","jose","util","base64url","publicKey","subjectPublicKeyInfo","subjectPublicKey","asn1PublicCert","valueHex","publicCert","RSAPublicKey","publicExponentHex","modulusHex","validateCertificatesSignature","certificates","caroots","certificateEngine","CertificateChainValidationEngine","trustedCerts","map","certs","verify","then","resultCode","resultMessage","validateKMS","jwt","resolve","x5c","length","promise"],"sources":["kms-certificate-validation.js"],"sourcesContent":["import {parse as parseUrl} from 'url';\n\nimport {isUri} from 'valid-url';\nimport {fromBER} from 'asn1js';\nimport {\n Certificate,\n RSAPublicKey,\n CertificateChainValidationEngine,\n CryptoEngine,\n setEngine\n} from 'pkijs';\nimport {isArray} from 'lodash';\nimport jose from 'node-jose';\nimport crypto from 'isomorphic-webcrypto';\nimport {Buffer} from 'safe-buffer';\n\nsetEngine(\n 'newEngine',\n crypto,\n new CryptoEngine({\n name: '',\n crypto,\n subtle: crypto.subtle\n })\n);\n\nconst VALID_KTY = 'RSA';\nconst VALID_KID_PROTOCOL = 'kms:';\n\nconst X509_COMMON_NAME_KEY = '2.5.4.3';\n\nconst X509_SUBJECT_ALT_NAME_KEY = '2.5.29.17';\n\n/**\n * Customize Error so the SDK knows to quit retrying and notify\n * the user\n */\nexport class KMSError extends Error {\n /**\n * add kmsError field to notify\n * @param {string} message\n */\n constructor(message) {\n super(message);\n this.kmsError = true;\n }\n}\n\nconst throwError = (err) => {\n throw new KMSError(`INVALID KMS: ${err}`);\n};\n\n/**\n * Converts the PEM string to a pkijs certificate object\n * @param {string} pem PEM representation of a certificate\n * @returns {Certificate} pkijs object of the certificate\n */\nconst decodeCert = (pem) => {\n if (typeof pem !== 'string') {\n throwError('certificate needs to be a string');\n }\n\n const der = Buffer.from(pem, 'base64');\n const ber = new Uint8Array(der).buffer;\n\n const asn1 = fromBER(ber);\n\n return new Certificate({schema: asn1.result});\n};\n\n/**\n * Validate the 'kty' property of the KMS credentials\n * @param {Object} JWT KMS credentials\n * @param {string} JWT.kty type of certificate\n * @throws {KMSError} if kty is not a valid type\n * @returns {void}\n */\nconst validateKtyHeader = ({kty}) => {\n if (kty !== VALID_KTY) {\n throwError(`'kty' header must be '${VALID_KTY}'`);\n }\n};\n\nconst validateKidHeader = ({kid}) => {\n if (!isUri(kid)) {\n throwError('\\'kid\\' is not a valid URI');\n }\n\n if (parseUrl(kid).protocol !== VALID_KID_PROTOCOL) {\n throwError(`'kid' protocol must be '${VALID_KID_PROTOCOL}'`);\n }\n};\n\n/**\n * Checks the first certificate matches the 'kid' in the JWT.\n * It first checks the Subject Alternative Name then it checks\n * the Common Name\n * @param {Certificate} certificate represents the KMS\n * @param {Object} JWT KMS credentials\n * @param {string} JWT.kid the uri of the KMS\n * @throws {KMSError} if unable to validate certificate against KMS credentials\n * @returns {void}\n */\nconst validateCommonName = ([certificate], {kid}) => {\n const kidHostname = parseUrl(kid).hostname;\n let validationSuccessful = false;\n\n if (certificate.extensions) {\n // Subject Alt Names are in here\n for (const extension of certificate.extensions) {\n if (extension.extnID === X509_SUBJECT_ALT_NAME_KEY) {\n const {altNames} = extension.parsedValue;\n\n for (const entry of altNames) {\n const san = entry.value;\n\n validationSuccessful = san === kidHostname;\n if (validationSuccessful) {\n break;\n }\n }\n\n if (validationSuccessful) {\n break;\n }\n }\n }\n }\n\n if (!validationSuccessful) {\n // Didn't match kid in the Subject Alt Names, checking the Common Name\n const subjectAttributes = certificate.subject.typesAndValues;\n\n for (const attribute of subjectAttributes) {\n if (attribute.type === X509_COMMON_NAME_KEY) {\n const commonName = attribute.value.valueBlock.value;\n\n validationSuccessful = commonName === kidHostname;\n if (validationSuccessful) {\n break;\n }\n }\n }\n }\n\n if (!validationSuccessful) {\n throwError('hostname of the 1st certificate does not match \\'kid\\'');\n }\n};\n\n/**\n * Validate the first KMS certificate against the information\n * provided in the JWT\n * @param {Certificate} certificate first certificate the identifies the KMS\n * @param {Object} JWT credentials of the KMS\n * @param {string} JWT.e Public exponent of the first certificate\n * @param {string} KWT.n Modulus of the first certificate\n * @throws {KMSError} if e or n doesn't match the first certificate\n * @returns {void}\n */\nconst validatePublicCertificate =\n ([certificate], {e: publicExponent, n: modulus}) => {\n const {encode} = jose.util.base64url;\n\n const publicKey = certificate.subjectPublicKeyInfo.subjectPublicKey;\n const asn1PublicCert = fromBER(publicKey.valueBlock.valueHex);\n const publicCert = new RSAPublicKey({schema: asn1PublicCert.result});\n const publicExponentHex = publicCert.publicExponent.valueBlock.valueHex;\n const modulusHex = publicCert.modulus.valueBlock.valueHex;\n\n if (publicExponent !== encode(publicExponentHex)) {\n throwError('Public exponent is invalid');\n }\n if (modulus !== encode(modulusHex)) {\n throwError('Modulus is invalid');\n }\n };\n\n/**\n * Validates the list of certificates against the CAs provided\n * @param {certificate[]} certificates list of certificates provided\n * by the KMS to certify itself\n * @param {string[]} [caroots=[]] list of Certificate Authorities used to\n * validate the KMS's certificates\n * @returns {Promise} rejects if unable to validate the certificates\n */\nconst validateCertificatesSignature = (certificates, caroots = []) => {\n const certificateEngine = new CertificateChainValidationEngine({\n trustedCerts: caroots.map(decodeCert),\n certs: certificates\n });\n\n return certificateEngine.verify()\n .then(({result, resultCode, resultMessage}) => {\n if (!result) {\n throwError(\n `Certificate Validation failed [${resultCode}]: ${resultMessage}`\n );\n }\n });\n};\n\n/**\n * Validates the information provided by the KMS. This is a curried function.\n * The first function takes the caroots param and returns a second function.\n * The second function takes the credentials of the KMS and validates it\n * @param {string[]} caroots PEM encoded certificates that will be used\n * as Certificate Authorities\n * @param {Object} jwt Object containing the fields necessary to\n * validate the KMS\n * @returns {Promise} when resolved will return the jwt\n */\nconst validateKMS = (caroots) => (jwt = {}) => Promise.resolve()\n .then(() => {\n validateKtyHeader(jwt);\n validateKidHeader(jwt);\n\n if (!(isArray(jwt.x5c) && jwt.x5c.length > 0)) {\n throwError('JWK does not contain a list of certificates');\n }\n const certificates = jwt.x5c.map(decodeCert);\n\n validateCommonName(certificates, jwt);\n validatePublicCertificate(certificates, jwt);\n\n // Skip validating signatures if no CA roots were provided\n const promise = caroots ?\n validateCertificatesSignature(certificates, caroots) : Promise.resolve();\n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AE,uBAAQA,GAAG,CAACE,GAAZ,KAAoBF,GAAG,CAACE,GAAJ,CAAQC,MAAR,GAAiB,CAAvC,CAAJ,EAA+C;QAC7C5E,UAAU,CAAC,6CAAD,CAAV;MACD;;MACD,IAAM6D,YAAY,GAAGY,GAAG,CAACE,GAAJ,CAAQT,GAAR,CAAYhE,UAAZ,CAArB;MAEAoB,kBAAkB,CAACuC,YAAD,EAAeY,GAAf,CAAlB;MACA/B,yBAAyB,CAACmB,YAAD,EAAeY,GAAf,CAAzB,CAVU,CAYV;;MACA,IAAMI,OAAO,GAAGf,OAAO,GACrBF,6BAA6B,CAACC,YAAD,EAAeC,OAAf,CADR,GACkC,iBAAQY,OAAR,EADzD;MAGA,OAAOG,OAAO,CACXR,IADI,CACC;QAAA,OAAMI,GAAN;MAAA,CADD,CAAP;IAED,CAnB4C,CAAd;EAAA,CAAb;AAAA,CAApB;;eAqBeD,W"}
|
|
1
|
+
{"version":3,"names":["setEngine","crypto","CryptoEngine","name","subtle","VALID_KTY","VALID_KID_PROTOCOL","X509_COMMON_NAME_KEY","X509_SUBJECT_ALT_NAME_KEY","KMSError","message","kmsError","Error","throwError","err","decodeCert","pem","der","Buffer","from","ber","Uint8Array","buffer","asn1","fromBER","Certificate","schema","result","validateKtyHeader","kty","validateKidHeader","kid","isUri","parseUrl","protocol","validateCommonName","certificate","kidHostname","hostname","validationSuccessful","extensions","extension","extnID","altNames","parsedValue","entry","san","value","subjectAttributes","subject","typesAndValues","attribute","type","commonName","valueBlock","validatePublicCertificate","publicExponent","e","modulus","n","encode","jose","util","base64url","publicKey","subjectPublicKeyInfo","subjectPublicKey","asn1PublicCert","valueHex","publicCert","RSAPublicKey","publicExponentHex","modulusHex","validateCertificatesSignature","certificates","caroots","certificateEngine","CertificateChainValidationEngine","trustedCerts","map","certs","verify","then","resultCode","resultMessage","validateKMS","jwt","resolve","x5c","length","promise"],"sources":["kms-certificate-validation.js"],"sourcesContent":["import {parse as parseUrl} from 'url';\n\nimport {isUri} from 'valid-url';\nimport {fromBER} from 'asn1js';\nimport {\n Certificate,\n RSAPublicKey,\n CertificateChainValidationEngine,\n CryptoEngine,\n setEngine,\n} from 'pkijs';\nimport {isArray} from 'lodash';\nimport jose from 'node-jose';\nimport crypto from 'isomorphic-webcrypto';\nimport {Buffer} from 'safe-buffer';\n\nsetEngine(\n 'newEngine',\n crypto,\n new CryptoEngine({\n name: '',\n crypto,\n subtle: crypto.subtle,\n })\n);\n\nconst VALID_KTY = 'RSA';\nconst VALID_KID_PROTOCOL = 'kms:';\n\nconst X509_COMMON_NAME_KEY = '2.5.4.3';\n\nconst X509_SUBJECT_ALT_NAME_KEY = '2.5.29.17';\n\n/**\n * Customize Error so the SDK knows to quit retrying and notify\n * the user\n */\nexport class KMSError extends Error {\n /**\n * add kmsError field to notify\n * @param {string} message\n */\n constructor(message) {\n super(message);\n this.kmsError = true;\n }\n}\n\nconst throwError = (err) => {\n throw new KMSError(`INVALID KMS: ${err}`);\n};\n\n/**\n * Converts the PEM string to a pkijs certificate object\n * @param {string} pem PEM representation of a certificate\n * @returns {Certificate} pkijs object of the certificate\n */\nconst decodeCert = (pem) => {\n if (typeof pem !== 'string') {\n throwError('certificate needs to be a string');\n }\n\n const der = Buffer.from(pem, 'base64');\n const ber = new Uint8Array(der).buffer;\n\n const asn1 = fromBER(ber);\n\n return new Certificate({schema: asn1.result});\n};\n\n/**\n * Validate the 'kty' property of the KMS credentials\n * @param {Object} JWT KMS credentials\n * @param {string} JWT.kty type of certificate\n * @throws {KMSError} if kty is not a valid type\n * @returns {void}\n */\nconst validateKtyHeader = ({kty}) => {\n if (kty !== VALID_KTY) {\n throwError(`'kty' header must be '${VALID_KTY}'`);\n }\n};\n\nconst validateKidHeader = ({kid}) => {\n if (!isUri(kid)) {\n throwError(\"'kid' is not a valid URI\");\n }\n\n if (parseUrl(kid).protocol !== VALID_KID_PROTOCOL) {\n throwError(`'kid' protocol must be '${VALID_KID_PROTOCOL}'`);\n }\n};\n\n/**\n * Checks the first certificate matches the 'kid' in the JWT.\n * It first checks the Subject Alternative Name then it checks\n * the Common Name\n * @param {Certificate} certificate represents the KMS\n * @param {Object} JWT KMS credentials\n * @param {string} JWT.kid the uri of the KMS\n * @throws {KMSError} if unable to validate certificate against KMS credentials\n * @returns {void}\n */\nconst validateCommonName = ([certificate], {kid}) => {\n const kidHostname = parseUrl(kid).hostname;\n let validationSuccessful = false;\n\n if (certificate.extensions) {\n // Subject Alt Names are in here\n for (const extension of certificate.extensions) {\n if (extension.extnID === X509_SUBJECT_ALT_NAME_KEY) {\n const {altNames} = extension.parsedValue;\n\n for (const entry of altNames) {\n const san = entry.value;\n\n validationSuccessful = san === kidHostname;\n if (validationSuccessful) {\n break;\n }\n }\n\n if (validationSuccessful) {\n break;\n }\n }\n }\n }\n\n if (!validationSuccessful) {\n // Didn't match kid in the Subject Alt Names, checking the Common Name\n const subjectAttributes = certificate.subject.typesAndValues;\n\n for (const attribute of subjectAttributes) {\n if (attribute.type === X509_COMMON_NAME_KEY) {\n const commonName = attribute.value.valueBlock.value;\n\n validationSuccessful = commonName === kidHostname;\n if (validationSuccessful) {\n break;\n }\n }\n }\n }\n\n if (!validationSuccessful) {\n throwError(\"hostname of the 1st certificate does not match 'kid'\");\n }\n};\n\n/**\n * Validate the first KMS certificate against the information\n * provided in the JWT\n * @param {Certificate} certificate first certificate the identifies the KMS\n * @param {Object} JWT credentials of the KMS\n * @param {string} JWT.e Public exponent of the first certificate\n * @param {string} KWT.n Modulus of the first certificate\n * @throws {KMSError} if e or n doesn't match the first certificate\n * @returns {void}\n */\nconst validatePublicCertificate = ([certificate], {e: publicExponent, n: modulus}) => {\n const {encode} = jose.util.base64url;\n\n const publicKey = certificate.subjectPublicKeyInfo.subjectPublicKey;\n const asn1PublicCert = fromBER(publicKey.valueBlock.valueHex);\n const publicCert = new RSAPublicKey({schema: asn1PublicCert.result});\n const publicExponentHex = publicCert.publicExponent.valueBlock.valueHex;\n const modulusHex = publicCert.modulus.valueBlock.valueHex;\n\n if (publicExponent !== encode(publicExponentHex)) {\n throwError('Public exponent is invalid');\n }\n if (modulus !== encode(modulusHex)) {\n throwError('Modulus is invalid');\n }\n};\n\n/**\n * Validates the list of certificates against the CAs provided\n * @param {certificate[]} certificates list of certificates provided\n * by the KMS to certify itself\n * @param {string[]} [caroots=[]] list of Certificate Authorities used to\n * validate the KMS's certificates\n * @returns {Promise} rejects if unable to validate the certificates\n */\nconst validateCertificatesSignature = (certificates, caroots = []) => {\n const certificateEngine = new CertificateChainValidationEngine({\n trustedCerts: caroots.map(decodeCert),\n certs: certificates,\n });\n\n return certificateEngine.verify().then(({result, resultCode, resultMessage}) => {\n if (!result) {\n throwError(`Certificate Validation failed [${resultCode}]: ${resultMessage}`);\n }\n });\n};\n\n/**\n * Validates the information provided by the KMS. This is a curried function.\n * The first function takes the caroots param and returns a second function.\n * The second function takes the credentials of the KMS and validates it\n * @param {string[]} caroots PEM encoded certificates that will be used\n * as Certificate Authorities\n * @param {Object} jwt Object containing the fields necessary to\n * validate the KMS\n * @returns {Promise} when resolved will return the jwt\n */\nconst validateKMS =\n (caroots) =>\n (jwt = {}) =>\n Promise.resolve().then(() => {\n validateKtyHeader(jwt);\n validateKidHeader(jwt);\n\n if (!(isArray(jwt.x5c) && jwt.x5c.length > 0)) {\n throwError('JWK does not contain a list of certificates');\n }\n const certificates = jwt.x5c.map(decodeCert);\n\n validateCommonName(certificates, jwt);\n validatePublicCertificate(certificates, jwt);\n\n // Skip validating signatures if no CA roots were provided\n const promise = caroots\n ? validateCertificatesSignature(certificates, caroots)\n : Promise.resolve();\n\n return promise.then(() => jwt);\n });\n\nexport default validateKMS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AAEA;;AACA;;AACA;;AAQA;;AACA;;AACA;;;;;;;;;;;;AAEA,IAAAA,gBAAA,EACE,WADF,EAEEC,4BAFF,EAGE,IAAIC,mBAAJ,CAAiB;EACfC,IAAI,EAAE,EADS;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YAAD,EAAeY,GAAf,CAAlB;MACA/B,yBAAyB,CAACmB,YAAD,EAAeY,GAAf,CAAzB,CAV2B,CAY3B;;MACA,IAAMI,OAAO,GAAGf,OAAO,GACnBF,6BAA6B,CAACC,YAAD,EAAeC,OAAf,CADV,GAEnB,iBAAQY,OAAR,EAFJ;MAIA,OAAOG,OAAO,CAACR,IAAR,CAAa;QAAA,OAAMI,GAAN;MAAA,CAAb,CAAP;IACD,CAlBD,CADF;EAAA,CADA;AAAA,CADF;;eAuBeD,W"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["KmsDryErrorInterceptor","options","reason","DryError","message","match","webex","logger","error","replay","reject","replayCount","config","maxAuthenticationReplays","info","request","Interceptor"],"sources":["kms-dry-error-interceptor.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {Interceptor} from '@webex/http-core';\n\nimport {DryError} from './kms-errors';\n/**\n * Interceptor (only to be used in test mode) intended to replay requests that\n * fail as a result of the test-user incompatibility in KMS.\n * @class\n */\nexport default class KmsDryErrorInterceptor extends Interceptor {\n /**\n * @returns {KmsDryErrorInterceptor}\n */\n static create() {\n return new KmsDryErrorInterceptor({webex: this});\n }\n\n /**\n * @param {Object} options\n * @param {Exception} reason\n * @returns {Promise}\n */\n onResponseError(options, reason) {\n if (reason instanceof DryError
|
|
1
|
+
{"version":3,"names":["KmsDryErrorInterceptor","options","reason","DryError","message","match","webex","logger","error","replay","reject","replayCount","config","maxAuthenticationReplays","info","request","Interceptor"],"sources":["kms-dry-error-interceptor.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {Interceptor} from '@webex/http-core';\n\nimport {DryError} from './kms-errors';\n/**\n * Interceptor (only to be used in test mode) intended to replay requests that\n * fail as a result of the test-user incompatibility in KMS.\n * @class\n */\nexport default class KmsDryErrorInterceptor extends Interceptor {\n /**\n * @returns {KmsDryErrorInterceptor}\n */\n static create() {\n return new KmsDryErrorInterceptor({webex: this});\n }\n\n /**\n * @param {Object} options\n * @param {Exception} reason\n * @returns {Promise}\n */\n onResponseError(options, reason) {\n if (\n reason instanceof DryError &&\n reason.message.match(/Failed to resolve authorization token in KmsMessage request for user/)\n ) {\n this.webex.logger.error('DRY Request Failed due to kms/test-user flakiness');\n this.webex.logger.error(reason);\n\n return this.replay(options, reason);\n }\n\n return Promise.reject(reason);\n }\n\n /**\n * Replays the request\n * @param {Object} options\n * @param {DryError} reason\n * @returns {Object}\n */\n replay(options, reason) {\n if (options.replayCount) {\n options.replayCount += 1;\n } else {\n options.replayCount = 1;\n }\n\n if (options.replayCount > this.webex.config.maxAuthenticationReplays) {\n this.webex.logger.error(\n `kms: failed after ${this.webex.config.maxAuthenticationReplays} replay attempts`\n );\n\n return Promise.reject(reason);\n }\n\n this.webex.logger.info(`kms: replaying request ${options.replayCount} time`);\n\n return this.webex.request(options);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;AAEA;;;;;;AACA;AACA;AACA;AACA;AACA;IACqBA,sB;;;;;;;;;;;;;IAQnB;AACF;AACA;AACA;AACA;IACE,yBAAgBC,OAAhB,EAAyBC,MAAzB,EAAiC;MAC/B,IACEA,MAAM,YAAYC,mBAAlB,IACAD,MAAM,CAACE,OAAP,CAAeC,KAAf,CAAqB,sEAArB,CAFF,EAGE;QACA,KAAKC,KAAL,CAAWC,MAAX,CAAkBC,KAAlB,CAAwB,mDAAxB;QACA,KAAKF,KAAL,CAAWC,MAAX,CAAkBC,KAAlB,CAAwBN,MAAxB;QAEA,OAAO,KAAKO,MAAL,CAAYR,OAAZ,EAAqBC,MAArB,CAAP;MACD;;MAED,OAAO,iBAAQQ,MAAR,CAAeR,MAAf,CAAP;IACD;IAED;AACF;AACA;AACA;AACA;AACA;;;;WACE,gBAAOD,OAAP,EAAgBC,MAAhB,EAAwB;MACtB,IAAID,OAAO,CAACU,WAAZ,EAAyB;QACvBV,OAAO,CAACU,WAAR,IAAuB,CAAvB;MACD,CAFD,MAEO;QACLV,OAAO,CAACU,WAAR,GAAsB,CAAtB;MACD;;MAED,IAAIV,OAAO,CAACU,WAAR,GAAsB,KAAKL,KAAL,CAAWM,MAAX,CAAkBC,wBAA5C,EAAsE;QACpE,KAAKP,KAAL,CAAWC,MAAX,CAAkBC,KAAlB,6BACuB,KAAKF,KAAL,CAAWM,MAAX,CAAkBC,wBADzC;QAIA,OAAO,iBAAQH,MAAR,CAAeR,MAAf,CAAP;MACD;;MAED,KAAKI,KAAL,CAAWC,MAAX,CAAkBO,IAAlB,kCAAiDb,OAAO,CAACU,WAAzD;MAEA,OAAO,KAAKL,KAAL,CAAWS,OAAX,CAAmBd,OAAnB,CAAP;IACD;;;;IAlDD;AACF;AACA;IACE,kBAAgB;MACd,OAAO,IAAID,sBAAJ,CAA2B;QAACM,KAAK,EAAE;MAAR,CAA3B,CAAP;IACD;;;EANiDU,qB"}
|
package/dist/kms-errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["KmsError","body","enumerable","value","reason","requestId","status","message","constructor","defaultMessage","Exception","KmsTimeoutError","request","timeout","method","uri","DryError","WebexHttpError","prototype","parse","_res","options","url","service","toUpperCase","resource","headers","trackingid"],"sources":["kms-errors.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {Exception} from '@webex/common';\nimport {WebexHttpError} from '@webex/webex-core';\n\n/**\n * Error class for KMS errors\n */\nexport class KmsError extends Exception {\n static defaultMessage
|
|
1
|
+
{"version":3,"names":["KmsError","body","enumerable","value","reason","requestId","status","message","constructor","defaultMessage","Exception","KmsTimeoutError","request","timeout","method","uri","DryError","WebexHttpError","prototype","parse","_res","options","url","service","toUpperCase","resource","headers","trackingid"],"sources":["kms-errors.js"],"sourcesContent":["/*!\n * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.\n */\n\nimport {Exception} from '@webex/common';\nimport {WebexHttpError} from '@webex/webex-core';\n\n/**\n * Error class for KMS errors\n */\nexport class KmsError extends Exception {\n static defaultMessage =\n 'An unknown error occurred while communicating with the kms. This implies we received an error response without a body.';\n\n /**\n * @param {HttpResponse} body\n * @returns {string}\n */\n parse(body) {\n body = body.body || body;\n\n Object.defineProperties(this, {\n body: {\n enumerable: false,\n value: body,\n },\n reason: {\n enumerable: false,\n value: body.reason,\n },\n requestId: {\n enumerable: false,\n value: body.requestId,\n },\n status: {\n enumerable: false,\n value: body.status,\n },\n });\n\n let message = typeof body === 'string' ? body : body.reason;\n\n if (!message) {\n message = this.constructor.defaultMessage;\n }\n if (body.status) {\n message += `\\nKMS_RESPONSE_STATUS: ${body.status}`;\n }\n if (body.requestId) {\n message += `\\nKMS_REQUEST_ID: ${body.requestId}`;\n }\n\n return message;\n }\n}\n\n/**\n * Thrown when an expected KMSResponse is not received in a timely manner\n */\nexport class KmsTimeoutError extends KmsError {\n /**\n * @param {KmsRequest} options.request\n * @param {KmsRequest} options.timeout\n * @returns {string}\n */\n parse({request = {}, timeout} = {}) {\n let message = `The KMS did not respond within ${\n timeout ? `${timeout} milliseconds` : 'a timely fashion'\n }`;\n\n if (request) {\n if (request.method && request.uri) {\n message += `\\nKMS_REQUEST: ${request.method} ${request.uri}`;\n }\n\n if (request.requestId) {\n message += `\\nKMS_REQUEST_ID: ${request.requestId}`;\n }\n }\n\n return message;\n }\n}\n\n/**\n * Emitted when a REST request includes an encrypter error\n */\nexport class DryError extends WebexHttpError {\n static defaultMessage = 'An unknown error was received from a service that proxies to the KMS';\n\n /**\n * @param {WebexHttpError} reason\n * @returns {string}\n */\n parse(reason) {\n Reflect.apply(WebexHttpError.prototype.parse, this, [reason._res]);\n const body = reason._res.body.message;\n\n let message = body.reason || body;\n\n if (!message) {\n message = this.constructor.defaultMessage;\n }\n if (this.options.url) {\n message += `\\n${this.options.method} ${this.options.url}`;\n } else if (this.options.uri) {\n message += `\\n${this.options.method} ${this.options.uri}`;\n } else {\n message += `\\n${this.options.method} ${this.options.service.toUpperCase()}/${\n this.options.resource\n }`;\n }\n message += `\\nWEBEX_TRACKING_ID: ${this.options.headers.trackingid}`;\n\n if (body.status) {\n message += `\\nKMS_RESPONSE_STATUS: ${body.status}`;\n }\n if (body.requestId) {\n message += `\\nKMS_REQUEST_ID: ${body.requestId}`;\n }\n\n Object.defineProperties(this, {\n reason: {\n enumerable: false,\n value: body.reason,\n },\n requestId: {\n enumerable: false,\n value: body.requestId,\n },\n status: {\n enumerable: false,\n value: body.status,\n },\n });\n\n return message;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;AACA;;;;;;AAEA;AACA;AACA;IACaA,Q;;;;;;;;;;;;;IAIX;AACF;AACA;AACA;IACE,eAAMC,IAAN,EAAY;MACVA,IAAI,GAAGA,IAAI,CAACA,IAAL,IAAaA,IAApB;MAEA,+BAAwB,IAAxB,EAA8B;QAC5BA,IAAI,EAAE;UACJC,UAAU,EAAE,KADR;UAEJC,KAAK,EAAEF;QAFH,CADsB;QAK5BG,MAAM,EAAE;UACNF,UAAU,EAAE,KADN;UAENC,KAAK,EAAEF,IAAI,CAACG;QAFN,CALoB;QAS5BC,SAAS,EAAE;UACTH,UAAU,EAAE,KADH;UAETC,KAAK,EAAEF,IAAI,CAACI;QAFH,CATiB;QAa5BC,MAAM,EAAE;UACNJ,UAAU,EAAE,KADN;UAENC,KAAK,EAAEF,IAAI,CAACK;QAFN;MAboB,CAA9B;MAmBA,IAAIC,OAAO,GAAG,OAAON,IAAP,KAAgB,QAAhB,GAA2BA,IAA3B,GAAkCA,IAAI,CAACG,MAArD;;MAEA,IAAI,CAACG,OAAL,EAAc;QACZA,OAAO,GAAG,KAAKC,WAAL,CAAiBC,cAA3B;MACD;;MACD,IAAIR,IAAI,CAACK,MAAT,EAAiB;QACfC,OAAO,qCAA8BN,IAAI,CAACK,MAAnC,CAAP;MACD;;MACD,IAAIL,IAAI,C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O,OAAL,CAAaC,GAA7C,CAAP;MACD,CAFD,MAEO,IAAI,KAAKD,OAAL,CAAaN,GAAjB,EAAsB;QAC3BR,OAAO,gBAAS,KAAKc,OAAL,CAAaP,MAAtB,cAAgC,KAAKO,OAAL,CAAaN,GAA7C,CAAP;MACD,CAFM,MAEA;QACLR,OAAO,gBAAS,KAAKc,OAAL,CAAaP,MAAtB,cAAgC,KAAKO,OAAL,CAAaE,OAAb,CAAqBC,WAArB,EAAhC,cACL,KAAKH,OAAL,CAAaI,QADR,CAAP;MAGD;;MACDlB,OAAO,mCAA4B,KAAKc,OAAL,CAAaK,OAAb,CAAqBC,UAAjD,CAAP;;MAEA,IAAI1B,IAAI,CAACK,MAAT,EAAiB;QACfC,OAAO,qCAA8BN,IAAI,CAACK,MAAnC,CAAP;MACD;;MACD,IAAIL,IAAI,CAACI,SAAT,EAAoB;QAClBE,OAAO,gCAAyBN,IAAI,CAACI,SAA9B,CAAP;MACD;;MAED,+BAAwB,IAAxB,EAA8B;QAC5BD,MAAM,EAAE;UACNF,UAAU,EAAE,KADN;UAENC,KAAK,EAAEF,IAAI,CAACG;QAFN,CADoB;QAK5BC,SAAS,EAAE;UACTH,UAAU,EAAE,KADH;UAETC,KAAK,EAAEF,IAAI,CAACI;QAFH,CALiB;QAS5BC,MAAM,EAAE;UACNJ,UAAU,EAAE,KADN;UAENC,KAAK,EAAEF,IAAI,CAACK;QAFN;MAToB,CAA9B;MAeA,OAAOC,OAAP;IACD;;;EAlD2BU,yB;;;8BAAjBD,Q,oBACa,sE"}
|
package/dist/kms.js
CHANGED
|
@@ -322,11 +322,11 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
322
322
|
},
|
|
323
323
|
|
|
324
324
|
/**
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
325
|
+
* @typedef {Object} FetchPublicKeyResponse
|
|
326
|
+
* @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)
|
|
327
|
+
* @property {UUID} requestId this is should be unique, used for debug.
|
|
328
|
+
* @property {string} publicKey
|
|
329
|
+
*/
|
|
330
330
|
|
|
331
331
|
/**
|
|
332
332
|
* get public key from kms
|
|
@@ -351,12 +351,12 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
351
351
|
},
|
|
352
352
|
|
|
353
353
|
/**
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
354
|
+
* @typedef {Object} UploadCmkResponse
|
|
355
|
+
* @property {number} status
|
|
356
|
+
* @property {UUID} requestId
|
|
357
|
+
* @property {string} uri
|
|
358
|
+
* @property {string} keysState
|
|
359
|
+
*/
|
|
360
360
|
|
|
361
361
|
/**
|
|
362
362
|
* upload master key for one org.
|
|
@@ -408,11 +408,11 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
408
408
|
},
|
|
409
409
|
|
|
410
410
|
/**
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
411
|
+
* @typedef {Object} ActivateCmkResponse
|
|
412
|
+
* @property {number} status
|
|
413
|
+
* @property {UUID} requestId
|
|
414
|
+
* @property {Array<CMK>} customerMasterKeys
|
|
415
|
+
*/
|
|
416
416
|
|
|
417
417
|
/**
|
|
418
418
|
*
|
|
@@ -931,7 +931,7 @@ var KMS = _webexCore.WebexPlugin.extend((_dec = (0, _common.oneFlight)({
|
|
|
931
931
|
context.ephemeralKey = originalContext.ephemeralKey;
|
|
932
932
|
return context;
|
|
933
933
|
},
|
|
934
|
-
version: "3.0.0-beta.
|
|
934
|
+
version: "3.0.0-beta.15"
|
|
935
935
|
}, ((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)));
|
|
936
936
|
|
|
937
937
|
var _default = KMS;
|