diff --git a/.gitignore b/.gitignore index 0b4faf023..1a973068c 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ build node_modules package-lock.json +package.json.decrypt # VSCode .vscode @@ -21,10 +22,12 @@ coverage # symlink to test vectors /modules/integration-node/fixtures +/modules/integration-browser/fixtures # Lerna /lerna-debug.log # TypeScript config is built by ./util/bootstrap_tsconfig /tsconfig.json +/tsconfig.module.json package.json.decrypt diff --git a/lerna.json b/lerna.json index 44b1f911d..6c00df122 100644 --- a/lerna.json +++ b/lerna.json @@ -1,5 +1,5 @@ { - "lerna": "2.11.0", + "lerna": "3.13.3", "packages": [ "modules/*" ], diff --git a/modules/integration-browser/LICENSE b/modules/integration-browser/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/modules/integration-browser/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/modules/integration-browser/NOTICE b/modules/integration-browser/NOTICE new file mode 100644 index 000000000..88f7bea1e --- /dev/null +++ b/modules/integration-browser/NOTICE @@ -0,0 +1,2 @@ +AWS Encryption SDK for Javascript +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/modules/integration-browser/Readme.md b/modules/integration-browser/Readme.md new file mode 100644 index 000000000..38df692f9 --- /dev/null +++ b/modules/integration-browser/Readme.md @@ -0,0 +1,11 @@ +# AWS Encryption SDK for Javascript Browser Integration + +This repository is for compatibility tests with the other versions of the AWS Encryption SDK's. +It's purpose is to facilitate testing the set of test vectors the AWS Encryption SDK. +The test vectors can be found at git@github.com:awslabs/aws-encryption-sdk-test-vectors.git + +# To test browser compatibility + +1. Get a manifest zip file from aws-encryption-sdk-test-vectors or a supported format. +1. Use `npm run build_fixtures -- -v path/to/zip` to extract the fixtures from the zip file +1. Run `npm run karma` execute the extracted tests diff --git a/modules/integration-browser/build_fixtures b/modules/integration-browser/build_fixtures new file mode 100755 index 000000000..f32202284 --- /dev/null +++ b/modules/integration-browser/build_fixtures @@ -0,0 +1,129 @@ +#!/usr/bin/env node +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +const argv = require('yargs') + .option('vectorFile', { + alias: 'v', + describe: 'a vector zip file from aws-encryption-sdk-test-vectors', + demandOption: true, + type: 'string' + }) + .option('testName', { + alias: 't', + describe: 'an optional test name to execute', + type: 'string' + }) + .option('slice', { + alias: 's', + describe: 'an optional range start:end e.g. 100:200', + type: 'string' + }) + .options('karma', { + alias: 'k', + describe: 'start karma and run the tests', + type: 'boolean' + }) + .argv + +const { vectorFile, testName, slice, karma } = argv +const {Open} = require('unzipper') +const streamToPromise = require('stream-to-promise') +const fs = require('fs') +const path = require('path') +const { spawnSync } = require('child_process') +const fixtures = path.join(__dirname, './fixtures') + +const [start=0, end=9999] = (slice || '').split(':').map(n => parseInt(n, 10)) + +if (!fs.existsSync(fixtures)){ + fs.mkdirSync(fixtures) +} + +;(async () => { + const centralDirectory = await Open.file(vectorFile) + const filesMap = new Map(centralDirectory.files.map(file => [file.path, file])) + + const readUriOnce = (() => { + const cache = new Map() + return async (uri) => { + const has = cache.get(uri) + if (has) return has + const fileInfo = filesMap.get(testUri2Path(uri)) + if (!fileInfo) throw new Error(`${uri} does not exist`) + const buffer = await fileInfo.buffer() + cache.set(uri, buffer) + return buffer + } + })() + + const manifestBuffer = await readUriOnce('manifest.json') + const { keys: keysFile, tests } = JSON.parse(manifestBuffer.toString('utf8')) + const keysBuffer = await readUriOnce(keysFile) + const { keys } = JSON.parse(keysBuffer.toString('utf8')) + const testNames = [] + let count = 0 + + for (const [name, testInfo] of Object.entries(tests)) { + count += 1 + + if (testName) { + if (name !== testName) continue + } + + if (slice) { + if (start >= count) continue + if (count > end) continue + } + + testNames.push(name) + + const { plaintext: plaintextFile, ciphertext, 'master-keys': masterKeys } = testInfo + const plainTextInfo = filesMap.get(testUri2Path(plaintextFile)) + const cipherInfo = filesMap.get(testUri2Path(ciphertext)) + if (!cipherInfo || !plainTextInfo) throw new Error(`no file for ${name}: ${ciphertext} | ${plaintextFile}`) + + const cipherText = await streamToPromise(cipherInfo.stream()) + const plainText = await readUriOnce(plainTextInfo.path) + const keysInfo = masterKeys.map(keyInfo => { + const key = keys[keyInfo.key] + if (!key) throw new Error(`no key for ${name}`) + return [keyInfo, key] + }) + + const test = JSON.stringify({ + name, + keysInfo, + cipherFile: cipherInfo.path, + cipherText: cipherText.toString('base64'), + plainText: plainText.toString('base64') + }) + + fs.writeFileSync(`${fixtures}/${name}.json`, test) + } + + fs.writeFileSync(`${fixtures}/tests.json`, JSON.stringify(testNames)) + + if (karma) { + spawnSync('npm', ['run', 'karma'], { + cwd: __dirname, + stdio: 'inherit' + }) + } +})() + +function testUri2Path (uri) { + return uri.replace('file://', '') +} diff --git a/modules/integration-browser/karma.conf.js b/modules/integration-browser/karma.conf.js new file mode 100644 index 000000000..37e49ef5b --- /dev/null +++ b/modules/integration-browser/karma.conf.js @@ -0,0 +1,62 @@ +// Karma configuration +process.env.CHROME_BIN = require('puppeteer').executablePath() + +module.exports = function(config) { + config.set({ + basePath: '', + frameworks: ['jasmine'], + files: [ + 'fixtures/tests.json', + {pattern: 'fixtures/*.json', included: false, served: true, watched: false, nocache: true}, + 'src/integration.test.ts' + ], + preprocessors: { + './src/*.test.ts': ['webpack', 'credentials'], + './fixtures/tests.json': ['json_fixtures'] + }, + webpack: { + resolve: { + extensions: [ '.ts', '.js' ] + }, + mode: 'development', + module: { + rules: [ + { + test: /\.tsx?$/, + use: 'ts-loader', + exclude: /node_modules/ + } + ] + }, + stats: { + colors: true, + modules: true, + reasons: true, + errorDetails: true + }, + devtool: 'inline-source-map', + }, + plugins: [ + '@aws-sdk/karma-credential-loader', + 'karma-webpack', + 'karma-json-fixtures-preprocessor', + 'karma-chrome-launcher', + 'karma-jasmine' + ], + reporters: ['progress'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: false, + browsers: ['ChromeHeadlessDisableCors'], + customLaunchers: { + ChromeHeadlessDisableCors: { + base: 'ChromeHeadless', + flags: ['--disable-web-security'] + } + }, + singleRun: true, + concurrency: Infinity, + exclude: ['**/*.d.ts'] + }) +} diff --git a/modules/integration-browser/package.json b/modules/integration-browser/package.json new file mode 100644 index 000000000..e91c1716e --- /dev/null +++ b/modules/integration-browser/package.json @@ -0,0 +1,79 @@ +{ + "name": "@aws-crypto/integration-browser", + "private": true, + "version": "0.1.0", + "scripts": { + "build": "tsc -b tsconfig.json", + "lint": "standard src/*.ts test/**/*.ts", + "karma": "karma start karma.conf.js", + "build_fixtures": "npx .", + "test": "npm run lint && npm run karma" + }, + "author": { + "name": "AWS Crypto Tools Team", + "email": "aws-cryptools@amazon.com", + "url": "https://aws.amazon.com/javascript/" + }, + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/decrypt-browser": "^0.0.1", + "@aws-crypto/encrypt-browser": "^0.0.1", + "@aws-crypto/kms-keyring-browser": "^0.0.1", + "@aws-crypto/material-management-browser": "^0.0.1", + "@aws-crypto/raw-aes-keyring-browser": "^0.0.1", + "@aws-crypto/raw-rsa-keyring-browser": "^0.0.1", + "@aws-sdk/util-base64-browser": "0.1.0-preview.1", + "@trust/keyto": "^0.3.7", + "@types/unzipper": "^0.9.1", + "@types/yargs": "^13.0.0", + "stream-to-promise": "^2.2.0", + "tslib": "^1.9.3", + "unzipper": "^0.9.11", + "yargs": "^13.2.2" + }, + "devDependencies": { + "@aws-sdk/karma-credential-loader": "0.1.0-preview.2", + "@types/chai": "^4.1.4", + "@types/chai-as-promised": "^7.1.0", + "@types/mocha": "^5.2.5", + "@types/node": "^11.11.4", + "@typescript-eslint/eslint-plugin": "^1.4.2", + "@typescript-eslint/parser": "^1.4.2", + "chai": "^4.1.2", + "chai-as-promised": "^7.1.1", + "jasmine-core": "^3.4.0", + "karma": "^4.1.0", + "karma-chai": "^0.1.0", + "karma-chrome-launcher": "^2.2.0", + "karma-coverage": "^1.1.2", + "karma-jasmine": "^2.0.1", + "karma-json-fixtures-preprocessor": "0.0.6", + "karma-mocha": "^1.3.0", + "karma-typescript": "^4.0.0", + "karma-webpack": "^3.0.5", + "mocha": "^5.2.0", + "mocha-loader": "^2.0.1", + "nyc": "^14.0.0", + "puppeteer": "^1.14.0", + "standard": "^12.0.1", + "ts-loader": "^5.3.3", + "ts-node": "^7.0.1", + "typescript": "^3.2.0", + "webpack": "^4.30.0", + "webpack-cli": "^3.3.0" + }, + "sideEffects": false, + "main": "./build/main/index.js", + "module": "./build/module/index.js", + "types": "./build/main/index.d.ts", + "bin": "./build_fixtures", + "files": [ + "./build/**/*" + ], + "standard": { + "parser": "@typescript-eslint/parser", + "plugins": [ + "@typescript-eslint" + ] + } +} diff --git a/modules/integration-browser/src/decrypt_materials_manager_web_crypto.ts b/modules/integration-browser/src/decrypt_materials_manager_web_crypto.ts new file mode 100644 index 000000000..7e515625f --- /dev/null +++ b/modules/integration-browser/src/decrypt_materials_manager_web_crypto.ts @@ -0,0 +1,143 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + needs, + WebCryptoCryptographicMaterialsManager, + MultiKeyringWebCrypto +} from '@aws-crypto/material-management-browser' +import { + KmsKeyringBrowser, + KmsWebCryptoClientSupplier, // eslint-disable-line no-unused-vars + KMS +} from '@aws-crypto/kms-keyring-browser' +import { + RawAesKeyringWebCrypto, + WrappingSuiteIdentifier, // eslint-disable-line no-unused-vars + RawAesWrappingSuiteIdentifier +} from '@aws-crypto/raw-aes-keyring-browser' +import { RawRsaKeyringWebCrypto } from '@aws-crypto/raw-rsa-keyring-browser' +import { + RsaKeyInfo, // eslint-disable-line no-unused-vars + AesKeyInfo, // eslint-disable-line no-unused-vars + KmsKeyInfo, // eslint-disable-line no-unused-vars + RSAKey, // eslint-disable-line no-unused-vars + AESKey, // eslint-disable-line no-unused-vars + KMSKey, // eslint-disable-line no-unused-vars + KeyInfoTuple // eslint-disable-line no-unused-vars +} from './types' + +import { fromBase64 } from '@aws-sdk/util-base64-browser' +// @ts-ignore +import keyto from '@trust/keyto' +declare const credentials: any + +const Bits2RawAesWrappingSuiteIdentifier: {[key: number]: WrappingSuiteIdentifier} = { + 128: RawAesWrappingSuiteIdentifier.AES128_GCM_IV12_TAG16_NO_PADDING, + /* Browsers do not support 192 Bit keys. + * Leaving this here to make sure this is clear. + *192: RawAesWrappingSuiteIdentifier.AES192_GCM_IV12_TAG16_NO_PADDING, + */ + 256: RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING +} + +export async function decryptMaterialsManagerWebCrypto (keyInfos: KeyInfoTuple[]) { + const children = await Promise.all(keyInfos.map(keyringWebCrypto)) + const keyring = new MultiKeyringWebCrypto({ children }) + return new WebCryptoCryptographicMaterialsManager(keyring) +} + +async function keyringWebCrypto ([ info, key ]: KeyInfoTuple) { + if (info.type === 'aws-kms' && key.type === 'aws-kms') { + return kmsKeyring(info, key) + } + if (info.type === 'raw' && info['encryption-algorithm'] === 'aes' && key.type === 'symmetric') { + return aesKeyring(info, key) + } + if (info.type === 'raw' && info['encryption-algorithm'] === 'rsa' && (key.type === 'public' || key.type === 'private')) { + return rsaKeyring(info, key) + } + throw new Error('Unsupported keyring type') +} + +function kmsKeyring (_keyInfo: KmsKeyInfo, key: KMSKey) { + const keyIds = [key['key-id']] + const clientProvider: KmsWebCryptoClientSupplier = (region: string) => { + return new KMS({ region, credentials }) + } + return new KmsKeyringBrowser({ keyIds, clientProvider }) +} + +async function aesKeyring (keyInfo:AesKeyInfo, key: AESKey) { + const keyName = key['key-id'] + const keyNamespace = keyInfo['provider-id'] + const { encoding, material } = key + needs(encoding === 'base64', 'Unsupported encoding') + const rawKey = fromBase64(material) + if (!Bits2RawAesWrappingSuiteIdentifier[key.bits]) throw new Error('Unsupported right now') + const wrappingSuite = Bits2RawAesWrappingSuiteIdentifier[key.bits] + const masterKey = await RawAesKeyringWebCrypto.importCryptoKey(rawKey, wrappingSuite) + return new RawAesKeyringWebCrypto({ keyName, keyNamespace, masterKey, wrappingSuite }) +} + +async function rsaKeyring (keyInfo: RsaKeyInfo, key: RSAKey) { + const keyName = key['key-id'] + const keyNamespace = keyInfo['provider-id'] + + const rsaKey = await pem2JWK(keyInfo, key) + return new RawRsaKeyringWebCrypto({ keyName, keyNamespace, ...rsaKey }) +} + +async function pem2JWK (keyInfo: RsaKeyInfo, { material, type }: RSAKey) { + const OAEP_SHA1_MFG1 = 'RSA-OAEP' + const OAEP_SHA256_MFG1 = 'RSA-OAEP-256' + const OAEP_SHA384_MFG1 = 'RSA-OAEP-384' + const OAEP_SHA512_MFG1 = 'RSA-OAEP-512' + /* Browsers do not support PKCS1. + * Leaving this here to make sure this is clear. + * const RSASSA_PKCS1_V1_5_SHA1 = 'RSASSA-PKCS1-v1_5' + */ + + // @ts-ignore + const jwk = keyto.from(material, 'pem').toJwk(type) + + const paddingAlgorithm = keyInfo['padding-algorithm'] + const paddingHash = keyInfo['padding-hash'] + if (paddingAlgorithm === 'oaep-mgf1') { + jwk.alg = paddingHash === 'sha1' + ? OAEP_SHA1_MFG1 + : paddingHash === 'sha256' + ? OAEP_SHA256_MFG1 + : paddingHash === 'sha384' + ? OAEP_SHA384_MFG1 + : paddingHash === 'sha512' + ? OAEP_SHA512_MFG1 + : false + } else if (paddingAlgorithm === 'pkcs1') { + throw new Error('Unsupported right now') + } + + if (type === 'public') { + const publicKey = await RawRsaKeyringWebCrypto.importPublicKey(jwk) + return { publicKey } + } + + if (type === 'private') { + const privateKey = await RawRsaKeyringWebCrypto.importPrivateKey(jwk) + return { privateKey } + } + + throw new Error('Unknown type') +} diff --git a/modules/integration-browser/src/integration.test.ts b/modules/integration-browser/src/integration.test.ts new file mode 100644 index 000000000..e64dc9384 --- /dev/null +++ b/modules/integration-browser/src/integration.test.ts @@ -0,0 +1,50 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-env jasmine */ + +import { decryptMaterialsManagerWebCrypto } from './decrypt_materials_manager_web_crypto' +import { fromBase64 } from '@aws-sdk/util-base64-browser' +import { decrypt } from '@aws-crypto/decrypt-browser' + +declare const expect: any +declare const __fixtures__: any +declare const fetch: any + +const notSupportedMessages = [ + '192-bit AES keys are not supported', + 'Unsupported right now' +] +describe('browser decryption vectors', function () { + const tests = __fixtures__['fixtures/tests'] + + for (const testName of tests) { + it(testName, async () => { + console.log(`start: ${testName}`) + const response = await fetch(`base/fixtures/${testName}.json`) + const { keysInfo, cipherText, plainText } = await response.json() + + const cipher = fromBase64(cipherText) + const good = fromBase64(plainText) + try { + const cmm = await decryptMaterialsManagerWebCrypto(keysInfo) + const { clearMessage } = await decrypt(cmm, cipher) + expect(good).toEqual(clearMessage) + } catch (e) { + if (!notSupportedMessages.includes(e.message)) throw e + } + }) + } +}) diff --git a/modules/integration-browser/src/types.ts b/modules/integration-browser/src/types.ts new file mode 100644 index 000000000..88a1e6a6e --- /dev/null +++ b/modules/integration-browser/src/types.ts @@ -0,0 +1,106 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface ManifestList { + manifest: Manifest + client: Client + keys: string + tests: {[key: string]: Test} +} + +export interface KeyList { + manifest: Manifest + keys: {[key: string]: (KMSKey|AESKey|RSAKey)} +} + +interface Manifest { + type: string + version: number +} +interface Client { + name: string + version: string +} + +interface KeyInfo { + type: 'aws-kms'|'raw' + key: string +} + +interface RawKeyInfo extends KeyInfo { + type: 'raw', + 'provider-id': string + 'encryption-algorithm': 'aes'|'rsa', + 'padding-algorithm': 'pkcs1'|'oaep-mgf1'|null +} + +export interface RsaKeyInfo extends RawKeyInfo { + 'encryption-algorithm': 'rsa', + 'padding-algorithm': 'pkcs1'|'oaep-mgf1' + 'padding-hash': 'sha1'|'sha256'|'sha384'|'sha512' +} + +export interface AesKeyInfo extends RawKeyInfo { + 'encryption-algorithm': 'aes' + 'padding-algorithm': null +} + +export interface KmsKeyInfo extends KeyInfo { + type: 'aws-kms' + key: string +} + +interface Test { + plaintext: string + ciphertext: string + 'master-keys': (RsaKeyInfo|AesKeyInfo|KmsKeyInfo)[] +} + +interface Key { + 'encrypt': boolean + 'decrypt': boolean + 'key-id': string +} + +interface RawKey extends Key { + algorithm: string + type: string + bits: number + encoding: string + material: string +} + +export interface RSAKey extends RawKey { + algorithm: 'rsa' + type: 'public'|'private' + bits: number + encoding: 'pem' + material: string +} + +export interface AESKey extends RawKey { + algorithm: 'aes' + type: 'symmetric' + bits: number + encoding: 'base64' + material: string +} + +export interface KMSKey extends Key { + type: 'aws-kms' + 'key-id': string +} + +export type KeyInfoTuple = [RsaKeyInfo, RSAKey] | [AesKeyInfo, AESKey] | [KmsKeyInfo, KMSKey] diff --git a/modules/integration-browser/tsconfig.json b/modules/integration-browser/tsconfig.json new file mode 100644 index 000000000..90a43fa60 --- /dev/null +++ b/modules/integration-browser/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../tsconfig.settings.json", + "compilerOptions": { + "outDir": "build/main", + "rootDir": "./src" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules/**"], + "references": [ + { "path": "../encrypt-browser" }, + { "path": "../decrypt-browser" }, + { "path": "../material-management-browser" }, + { "path": "../kms-keyring-browser" }, + { "path": "../raw-rsa-keyring-browser" }, + { "path": "../raw-aes-keyring-browser" }, + ] +} \ No newline at end of file diff --git a/modules/integration-browser/tsconfig.module.json b/modules/integration-browser/tsconfig.module.json new file mode 100644 index 000000000..6f86aea07 --- /dev/null +++ b/modules/integration-browser/tsconfig.module.json @@ -0,0 +1,18 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "target": "esnext", + "outDir": "build/module", + "module": "esnext", + "allowSyntheticDefaultImports": true + }, + "exclude": [ "node_modules/**" ], + "references": [ + { "path": "../encrypt-browser/tsconfig.module.json" }, + { "path": "../decrypt-browser/tsconfig.module.json" }, + { "path": "../material-management-browser/tsconfig.module.json" }, + { "path": "../kms-keyring-browser/tsconfig.module.json" }, + { "path": "../raw-rsa-keyring-browser/tsconfig.module.json" }, + { "path": "../raw-aes-keyring-browser/tsconfig.module.json" }, + ] +} \ No newline at end of file diff --git a/modules/integration-browser/webpack.config.js b/modules/integration-browser/webpack.config.js new file mode 100644 index 000000000..b422a4814 --- /dev/null +++ b/modules/integration-browser/webpack.config.js @@ -0,0 +1,28 @@ +const path = require('path'); + +module.exports = { + entry: './src/asdf.test.ts', + // devtool: 'inline-source-map', + module: { + rules: [ + { + test: /\.asdf.test.ts$/, + use: 'mocha-loader', + exclude: /node_modules/ + }, + { + test: /\.tsx?$/, + use: 'ts-loader', + exclude: /node_modules/ + } + ] + }, + resolve: { + extensions: [ '.tsx', '.ts', '.js' ] + }, + output: { + filename: 'asdf.test.js', + path: path.resolve(__dirname, 'build') + }, + node: false +}; \ No newline at end of file diff --git a/package.json b/package.json index 223e9cd8c..344f06367 100644 --- a/package.json +++ b/package.json @@ -9,10 +9,13 @@ "clean": "npm run clear-build-cache && lerna clean", "clear-build-cache": "rimraf ./modules/*/build/*", "lint": "standard modules/**/src/*.ts modules/**/test/**/*.ts", - "build": "tsc -b", + "build:node": "tsc -b tsconfig.json", + "build:browser": "tsc -b tsconfig.module.json", + "build": "run-p build:*", "mocha": "mocha --require ts-node/register modules/**/test/*test.ts", "coverage": "nyc --check-coverage -x 'modules/**/test/*test.ts' npm run mocha", "test": "npm run lint && npm run build && npm run coverage", + "integration_browser": "npm run build; lerna run build_fixtures --stream --no-prefix -- -- -v ../../aws-encryption-sdk-test-vectors/vectors/awses-decrypt/python-1.3.8.zip -k", "integration_node": "npm run build; lerna run integration_node --stream --no-prefix -- -- -v ../../aws-encryption-sdk-test-vectors/vectors/awses-decrypt/python-1.3.8.zip" }, "repository": { @@ -42,5 +45,8 @@ "plugins": [ "@typescript-eslint" ] + }, + "devDependencies": { + "npm-run-all": "^4.1.5" } } diff --git a/util/bootstrap_tsconfig b/util/bootstrap_tsconfig index 8fbab2d97..d0f01c70a 100755 --- a/util/bootstrap_tsconfig +++ b/util/bootstrap_tsconfig @@ -24,7 +24,7 @@ const { exec } = require('child_process') const { promisify } = require('util') const execAsync = promisify(exec) -const lernaLs = 'npx lerna ls' +const lernaLs = 'npx lerna la' execAsync(lernaLs) .then(clean) @@ -33,7 +33,11 @@ execAsync(lernaLs) files: [], references })) - .then(tsconfig => writeFileSync('./tsconfig.json', JSON.stringify(tsconfig, null, ' '))) + .then(tsconfig => { + writeFileSync('./tsconfig.json', JSON.stringify(tsconfig, null, ' ')) + const references = tsconfig.references.map(({path}) => ({path: path + '/tsconfig.module.json'})) + writeFileSync('./tsconfig.module.json', JSON.stringify({...tsconfig, references}, null, ' ')) + }) const namespace = '@aws-crypto/' function clean ({ stdout, stderr }) {