import { DecryptCommand, EncryptCommand, KMSClient } from '@aws-sdk/client-kms' import { expect } from 'chai' import Crypto from '../../src/Crypto/Crypto.js' import { mockAwsClient, mockAwsCommand, mockAwsResult } from '../AwsSdkTest.utils.js' const KMSMock = mockAwsClient(KMSClient) function fakeEncryption(v) { const f = new TextEncoder().encode(v) return Buffer.from(f as any, 'utf8').toString('hex') } function fakeDecryption(v) { return new TextEncoder().encode(v) } describe('Encryption', () => { // reset mock beforeEach(() => { KMSMock.reset() }) const provider = new Crypto('ca-central-1', 'abc123') test('Encrypts json object', async () => { const encryptionObj = { userID: 123 } KMSMock.on(mockAwsCommand(EncryptCommand)).resolves( mockAwsResult({ CiphertextBlob: new TextEncoder().encode(JSON.stringify(encryptionObj)), }) ) const token = await provider.encryptData(encryptionObj) expect(token).is.not.null expect(token).to.be.equals(fakeEncryption(JSON.stringify(encryptionObj))) }) test('Encrypts string', async () => { const encryptionText = 'Hello encryption!' KMSMock.on(mockAwsCommand(EncryptCommand)).resolves( mockAwsResult({ CiphertextBlob: new TextEncoder().encode(encryptionText), }) ) const token = await provider.encryptData(encryptionText) expect(token).is.not.null expect(token).to.be.equals(fakeEncryption(encryptionText)) }) test('Fails to encrypt a number', async () => { const encryptionText = 123 KMSMock.on(mockAwsCommand(EncryptCommand)).rejects(new Error('failed')) const token = await provider.encryptData(encryptionText) expect(token).is.null }) }) describe('Decryption', () => { // reset mock beforeEach(() => { KMSMock.reset() }) const provider = new Crypto('ca-central-1', 'abc123') test('Decrypts json object', async () => { const encryptionObj = { userID: 123 } KMSMock.on(mockAwsCommand(DecryptCommand)).resolves( mockAwsResult({ Plaintext: fakeDecryption(JSON.stringify(encryptionObj)), }) ) const token = await provider.decryptData(fakeEncryption(JSON.stringify(encryptionObj))) expect(token).is.not.null expect(token).to.be.equals(JSON.stringify(encryptionObj)) }) test('Decrypts string', async () => { const encryptionText = 'abc123' KMSMock.on(mockAwsCommand(DecryptCommand)).resolves( mockAwsResult({ Plaintext: fakeDecryption(encryptionText), }) ) const token = await provider.decryptData(fakeEncryption(encryptionText)) expect(token).is.not.null expect(token).to.be.equals(encryptionText) }) test('Fails to decrypt a number', async () => { const encryptionText = 123 KMSMock.on(mockAwsCommand(DecryptCommand)).rejects(new Error('failed')) // @ts-ignore const token = await provider.decryptData(encryptionText) expect(token).is.null }) }) export {}