forked from aws/aws-encryption-sdk-javascript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencrypt.test.ts
416 lines (360 loc) · 13 KB
/
encrypt.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/* eslint-env mocha */
import * as chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import {
NodeDecryptionMaterial,
NodeEncryptionMaterial,
KeyringNode,
EncryptedDataKey,
KeyringTraceFlag,
AlgorithmSuiteIdentifier,
NodeAlgorithmSuite,
CommitmentPolicy,
} from '@aws-crypto/material-management-node'
import {
deserializeFactory,
decodeBodyHeader,
deserializeSignature,
MessageHeader,
} from '@aws-crypto/serialize'
import { buildEncrypt } from '../src/index'
import { _encrypt } from '../src/encrypt'
import from from 'from2'
// @ts-ignore
import { finished } from 'readable-stream'
import { randomBytes } from 'crypto'
const { encrypt, encryptStream } = buildEncrypt(
CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT
)
chai.use(chaiAsPromised)
const { expect } = chai
const toUtf8 = (input: Uint8Array) =>
Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString('utf8')
const { deserializeMessageHeader } = deserializeFactory(
toUtf8,
NodeAlgorithmSuite
)
/* These tests only check structure.
* see decrypt-node for actual cryptographic tests
* see integration-node for exhaustive compatibility tests
*/
describe('encrypt structural testing', () => {
const edk = new EncryptedDataKey({
providerId: 'k',
providerInfo: 'k',
encryptedDataKey: new Uint8Array(3),
/* rawInfo added because it will always be there when deserialized.
* This way deep equal will pass nicely.
* 107 is 'k' in ASCII
*/
rawInfo: new Uint8Array([107]),
})
class TestKeyring extends KeyringNode {
async _onEncrypt(material: NodeEncryptionMaterial) {
const unencryptedDataKey = new Uint8Array(
material.suite.keyLengthBytes
).fill(0)
const trace = {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
}
return material
.setUnencryptedDataKey(unencryptedDataKey, trace)
.addEncryptedDataKey(
edk,
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
)
}
async _onDecrypt(): Promise<NodeDecryptionMaterial> {
throw new Error('I should never see this error')
}
}
const keyRing = new TestKeyring()
it('encrypt a string', async () => {
const suiteId = AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
const plaintext = 'asdf'
const { result, messageHeader } = await encrypt(keyRing, plaintext, {
suiteId,
})
expect(messageHeader.suiteId).to.equal(suiteId)
expect(messageHeader.encryptionContext).to.deep.equal({})
expect(messageHeader.encryptedDataKeys).lengthOf(1)
expect(messageHeader.encryptedDataKeys[0]).to.deep.equal(edk)
const messageInfo = deserializeMessageHeader(result)
if (!messageInfo) throw new Error('I should never see this error')
expect(messageHeader).to.deep.equal(messageInfo.messageHeader)
})
it('encrypt a buffer', async () => {
const encryptionContext = { simple: 'context' }
const plaintext = Buffer.from('asdf')
const { result, messageHeader } = await encrypt(keyRing, plaintext, {
encryptionContext,
})
/* The default algorithm suite will add a signature key to the context.
* So I only check that the passed context elements exist.
*/
expect(messageHeader.encryptionContext)
.to.haveOwnProperty('simple')
.and.to.equal('context')
expect(messageHeader.encryptedDataKeys).lengthOf(1)
expect(messageHeader.encryptedDataKeys[0]).to.deep.equal(edk)
const messageInfo = deserializeMessageHeader(result)
if (!messageInfo) throw new Error('I should never see this error')
expect(messageHeader).to.deep.equal(messageInfo.messageHeader)
})
it('encrypt a stream', async () => {
const encryptionContext = { simple: 'context' }
let pushed = false
const plaintext = from(
(_: number, next: (err: Error | null, chunk: string | null) => void) => {
if (pushed) return next(null, null)
pushed = true
next(null, 'asdf')
}
)
const { result, messageHeader } = await encrypt(keyRing, plaintext, {
encryptionContext,
})
/* The default algorithm suite will add a signature key to the context.
* So I only check that the passed context elements exist.
*/
expect(messageHeader.encryptionContext)
.to.haveOwnProperty('simple')
.and.to.equal('context')
expect(messageHeader.encryptedDataKeys).lengthOf(1)
expect(messageHeader.encryptedDataKeys[0]).to.deep.equal(edk)
const messageInfo = deserializeMessageHeader(result)
if (!messageInfo) throw new Error('I should never see this error')
expect(messageHeader).to.deep.equal(messageInfo.messageHeader)
})
it('Unsupported plaintext', async () => {
const plaintext = {} as any
await expect(encrypt(keyRing, plaintext)).to.rejectedWith(Error)
})
it('encryptStream', async () => {
const encryptionContext = { simple: 'context' }
const data = randomBytes(300)
const i = data.values()
const plaintext = from(
(
_: number,
next: (err: Error | null, chunk: Uint8Array | null) => void
) => {
/* Pushing 1 byte at time is the most annoying thing.
* This is done intentionally to hit _every_ boundary condition.
*/
const { value, done } = i.next()
if (done) return next(null, null)
next(null, new Uint8Array([value]))
}
)
let messageHeader: any
const buffer: Buffer[] = []
const stream = plaintext
.pipe(encryptStream(keyRing, { encryptionContext, frameLength: 5 }))
.on('MessageHeader', (header: MessageHeader) => {
// MessageHeader should only be called once
if (messageHeader) throw new Error('I should never see this error')
messageHeader = header
})
// data event to drain the stream
.on('data', (chunk: Buffer) => {
buffer.push(chunk)
})
await finishedAsync(stream)
if (!messageHeader) throw new Error('I should never see this error')
const result = Buffer.concat(buffer)
/* The default algorithm suite will add a signature key to the context.
* So I only check that the passed context elements exist.
*/
expect(messageHeader.encryptionContext)
.to.haveOwnProperty('simple')
.and.to.equal('context')
expect(messageHeader.encryptedDataKeys).lengthOf(1)
expect(messageHeader.encryptedDataKeys[0]).to.deep.equal(edk)
const messageInfo = deserializeMessageHeader(result)
if (!messageInfo) throw new Error('I should never see this error')
expect(messageHeader).to.deep.equal(messageInfo.messageHeader)
})
it('Precondition: encryptStream needs a valid commitmentPolicy.', async () => {
await expect(
_encrypt(
{
commitmentPolicy: 'fake_policy' as any,
maxEncryptedDataKeys: false,
},
keyRing,
'asdf'
)
).to.rejectedWith(Error, 'Invalid commitment policy.')
})
it('Precondition: encryptStream needs a valid maxEncryptedDataKeys.', async () => {
await expect(
_encrypt(
{
commitmentPolicy: CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT,
maxEncryptedDataKeys: 0,
},
keyRing,
'asdf'
)
).to.rejectedWith(Error, 'Invalid maxEncryptedDataKeys value.')
})
it('Precondition: The frameLength must be less than the maximum frame size Node.js stream.', async () => {
const frameLength = 0
await expect(encrypt(keyRing, 'asdf', { frameLength })).to.rejectedWith(
Error,
'frameLength out of bounds: 0'
)
})
it('Precondition: Only request NodeEncryptionMaterial for algorithm suites supported in commitmentPolicy.', async () => {
await expect(
_encrypt(
{
commitmentPolicy: CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT,
maxEncryptedDataKeys: false,
},
keyRing,
'asdf',
{
suiteId:
AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY,
}
)
).to.rejectedWith(
Error,
'Configuration conflict. Cannot encrypt due to CommitmentPolicy'
)
})
it('Precondition: Only use NodeEncryptionMaterial for algorithm suites supported in commitmentPolicy.', async () => {
let called_getEncryptionMaterials = false
const cmm = {
async getEncryptionMaterials() {
called_getEncryptionMaterials = true
return new NodeEncryptionMaterial(
new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY
),
{}
)
},
} as any
await expect(
_encrypt(
{
commitmentPolicy: CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT,
maxEncryptedDataKeys: false,
},
cmm,
'asdf'
)
).to.rejectedWith(
Error,
'Configuration conflict. Cannot encrypt due to CommitmentPolicy'
)
expect(called_getEncryptionMaterials).to.equal(true)
})
it('Precondition: _encryptStream encryption materials must not exceed maxEncryptedDataKeys', async () => {
for (const numKeys of [2, 3, 4]) {
let called_getEncryptionMaterials = false
const cmm = {
async getEncryptionMaterials() {
called_getEncryptionMaterials = true
const material = await keyRing.onEncrypt(
new NodeEncryptionMaterial(
new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY
),
{}
)
)
for (let i = 1; i < numKeys; i++) {
material.addEncryptedDataKey(
edk,
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
)
}
return material
},
} as any
const encryptPromise = _encrypt(
{
commitmentPolicy: CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT,
maxEncryptedDataKeys: 3,
},
cmm,
'asdf'
)
if (numKeys > 3) {
await expect(encryptPromise).to.rejectedWith(
Error,
'maxEncryptedDataKeys exceeded.'
)
} else {
await encryptPromise
}
expect(called_getEncryptionMaterials).to.equal(true)
}
})
it('can fully parse a framed message', async () => {
const plaintext = 'asdf'
const frameLength = 1
const { result } = await encrypt(keyRing, plaintext, { frameLength })
const headerInfo = deserializeMessageHeader(result)
if (!headerInfo) throw new Error('this should never happen')
const tagLength = headerInfo.algorithmSuite.tagLength / 8
let readPos =
headerInfo.headerLength + headerInfo.algorithmSuite.ivLength + tagLength
let i = 0
let bodyHeader: any
// for every frame...
for (; i < 5; i++) {
bodyHeader = decodeBodyHeader(result, headerInfo, readPos)
if (!bodyHeader) throw new Error('this should never happen')
readPos = bodyHeader.readPos + bodyHeader.contentLength + tagLength
}
expect(i).to.equal(5) // 4 frames
expect(bodyHeader.isFinalFrame).to.equal(true) // we got to the end
// This implicitly tests that I have consumed all the data,
// because otherwise the footer section will be too large
const footerSection = result.slice(readPos)
// This will throw if it does not deserialize correctly
deserializeSignature(footerSection)
})
it('can encrypt empty message', async () => {
const plaintext = new Uint8Array()
const { result, messageHeader } = await encrypt(keyRing, plaintext)
/* The default algorithm suite will add a signature key to the context.
* So I only check that the passed context elements exist.
*/
expect(messageHeader.encryptionContext)
.to.haveOwnProperty('simple')
.and.to.equal('context')
expect(messageHeader.encryptedDataKeys).lengthOf(1)
expect(messageHeader.encryptedDataKeys[0]).to.deep.equal(edk)
const headerInfo = deserializeMessageHeader(result)
if (!headerInfo) throw new Error('this should never happen')
expect(messageHeader).to.deep.equal(headerInfo.messageHeader)
const readPos =
headerInfo.headerLength + headerInfo.headerAuth.headerAuthLength
const bodyHeader = decodeBodyHeader(result, headerInfo, readPos)
if (!bodyHeader) throw new Error('I should never see this error')
expect(bodyHeader.isFinalFrame).to.equal(true)
expect(bodyHeader.contentLength).to.equal(0)
const sigPos =
bodyHeader.readPos + bodyHeader.contentLength + bodyHeader.tagLength / 8
// This implicitly tests that I have consumed all the data,
// because otherwise the footer section will be too large
const footerSection = result.slice(sigPos)
// This will throw if it does not deserialize correctly
deserializeSignature(footerSection)
})
})
async function finishedAsync(stream: any) {
return new Promise<void>((resolve, reject) => {
finished(stream, (err: Error) => (err ? reject(err) : resolve()))
})
}