import streamToPromise from 'stream-to-promise' ; import { writeFileSync } from 'fs' ; import { parseDecryptionFiles , readUriOnce , centralDirectory , StreamEntry , DecryptTest , KeyInfoTuple , DecryptionFixture , } from '@aws-crypto/integration-vectors' ; export async function buildDecryptFixtures ( fixtures , vectorFile , testName ? , slice ? ) { const [ start = 0 , end = 9999 ] = ( slice || '' ) . split ( ':' ) . map ( ( n ) => parseInt ( n , 10 ) ) ; const filesMap = await centralDirectory ( vectorFile ) ; const { tests , keys } = await parseDecryptionFiles ( filesMap ) ; 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 ; } const { result , description , ciphertext , 'master-keys' : masterKeys , 'decryption-method' : decryptionMethod , } = testInfo ; if ( decryptionMethod == 'streaming-unsigned-only' ) { continue ; } testNames . push ( name ) ; let resultContent ; if ( 'output' in result ) { const plainTextInfo = filesMap . get ( result . output . plaintext ) ; if ( ! plainTextInfo ) throw new Error ( `no plaintext file for ${ name }: ${ result . output . plaintext }` ) ; const plainTextBuffer = await readUriOnce ( `file://${ plainTextInfo . fileName }` , filesMap ) ; resultContent = { plainText : plainTextBuffer . toString ( 'base64' ) , } ; } else { resultContent = { errorDescription : result . error [ 'error-description' ] } ; } const cipherInfo = filesMap . get ( ciphertext ) ; if ( ! cipherInfo ) throw new Error ( `no file for ${ name }: ${ ciphertext }` ) ; const cipherText = await streamToPromise ( await cipherInfo . stream ( ) ) ; const keysInfo = masterKeys . map ( ( keyInfo ) => { if ( keyInfo . type === 'aws-kms-mrk-aware-discovery' ) { return [ keyInfo ] as KeyInfoTuple ; } const key = keys [ keyInfo . key ] ; if ( ! key ) throw new Error ( `no key for ${ name }` ) ; return [ keyInfo , key ] as KeyInfoTuple ; } ) ; const test = { name , description , keysInfo , cipherFile : cipherInfo . fileName , cipherText : cipherText . toString ( 'base64' ) , result : resultContent , } ; writeFileSync ( `${ fixtures }/${ name }.json` , JSON . stringify ( test ) ) ; } writeFileSync ( `${ fixtures }/decrypt_tests.json` , JSON . stringify ( testNames ) ) ; }