-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathencrypt-decrypt.spec.ts
More file actions
537 lines (479 loc) · 17.4 KB
/
Copy pathencrypt-decrypt.spec.ts
File metadata and controls
537 lines (479 loc) · 17.4 KB
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
// Simplest HTTP server that supports RANGE headers AFAIK.
import { assert } from 'chai';
import { getMocks } from '../mocks/index.js';
import { KasPublicKeyAlgorithm } from '../../src/access.js';
import { AuthProvider, HttpRequest } from '../../src/auth/auth.js';
import { AesGcmCipher, KeyInfo, SplitKey, WebCryptoService } from '../../tdf3/index.js';
import { Client } from '../../tdf3/src/index.js';
import {
AssertionConfig,
AssertionVerificationKeys,
getSystemMetadataAssertionConfig,
Assertion,
} from '../../tdf3/src/assertions.js';
import { Scope } from '../../tdf3/src/client/builders.js';
import { NetworkError } from '../../src/errors.js';
const Mocks = getMocks();
const authProvider = {
// eslint-disable-next-line @typescript-eslint/no-empty-function
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => httpReq,
};
describe('rewrap error cases', function () {
const kasUrl = 'http://localhost:3000';
const expectedVal = 'test data';
let client: Client.Client;
let cipher: AesGcmCipher;
let encryptionInformation: SplitKey;
let key1: KeyInfo;
beforeEach(async function () {
// Setup base auth provider that will be modified per test
const baseAuthProvider = {
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => httpReq,
};
client = new Client.Client({
platformUrl: kasUrl,
kasEndpoint: kasUrl,
dpopKeys: Mocks.entityKeyPair(),
clientId: 'id',
authProvider: baseAuthProvider,
});
cipher = new AesGcmCipher(WebCryptoService);
encryptionInformation = new SplitKey(cipher);
key1 = await encryptionInformation.generateKey();
});
async function encryptTestData({ customAuthProvider }: { customAuthProvider?: AuthProvider }) {
const keyMiddleware = async () => ({ keyForEncryption: key1, keyForManifest: key1 });
if (customAuthProvider) {
client = new Client.Client({
kasEndpoint: kasUrl,
allowedKases: [kasUrl],
dpopKeys: Mocks.entityKeyPair(),
clientId: 'id',
authProvider: customAuthProvider,
});
}
return client.encrypt({
metadata: Mocks.getMetadataObject(),
offline: true,
scope: {
dissem: ['user@domain.com'],
attributes: [],
},
keyMiddleware,
source: new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(expectedVal));
controller.close();
},
}),
});
}
it('should handle 401 Unauthorized error', async function () {
const authProvider = {
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => ({
...httpReq,
headers: { ...httpReq.headers, authorization: 'Invalid' },
}),
};
const encryptedStream = await encryptTestData({ customAuthProvider: authProvider });
try {
await client.decrypt({
source: {
type: 'stream',
location: encryptedStream.stream,
},
});
assert.fail('Expected Error');
} catch (error) {
assert.instanceOf(error, NetworkError);
}
});
it('should handle 403 Forbidden error', async function () {
const authProvider = {
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => ({
...httpReq,
headers: { ...httpReq.headers, 'x-test-response': '403' },
}),
};
const encryptedStream = await encryptTestData({ customAuthProvider: authProvider });
try {
await client.decrypt({
source: {
type: 'stream',
location: encryptedStream.stream,
},
});
assert.fail('Expected Error');
} catch (error) {
assert.instanceOf(error, NetworkError);
}
});
it('should handle 400 Bad Request error', async function () {
// Modify the mock server to return 400 for invalid body
const authProvider = {
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => ({
...httpReq,
headers: {
...httpReq.headers,
'x-test-response': '400',
'x-test-response-message': 'IntegrityError',
},
}),
};
const encryptedStream = await encryptTestData({ customAuthProvider: authProvider });
try {
await client.decrypt({
source: {
type: 'stream',
location: encryptedStream.stream,
},
});
assert.fail('Expected Error');
} catch (error) {
assert.instanceOf(error, NetworkError);
}
});
it('should handle 500 Server error', async function () {
const authProvider = {
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => ({
...httpReq,
headers: { ...httpReq.headers, 'x-test-response': '500' },
}),
};
const encryptedStream = await encryptTestData({ customAuthProvider: authProvider });
try {
await client.decrypt({
source: {
type: 'stream',
location: encryptedStream.stream,
},
});
assert.fail('Expected ServiceError');
} catch (error) {
assert.instanceOf(error, NetworkError);
}
});
it('should handle network failures', async function () {
try {
// Point to a non-existent server
client = new Client.Client({
kasEndpoint: 'http://localhost:9999',
allowedKases: ['http://localhost:9999'],
dpopKeys: Mocks.entityKeyPair(),
clientId: 'id',
authProvider: {
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => httpReq,
},
});
const encryptedStream = await encryptTestData({});
await client.decrypt({
source: {
type: 'stream',
location: encryptedStream.stream,
},
});
assert.fail('Expected NetworkError');
} catch (error) {
assert.instanceOf(error, NetworkError);
}
});
it('should handle decrypt errors with invalid keys', async function () {
const authProvider: AuthProvider = {
updateClientPublicKey: async () => {},
withCreds: async (httpReq: HttpRequest) => ({
...httpReq,
body: new URLSearchParams({ invalidKey: 'true' }),
headers: {
...httpReq.headers,
'x-test-response': '400',
'x-test-response-message': 'DecryptError',
},
}),
};
const encryptedStream = await encryptTestData({ customAuthProvider: authProvider });
try {
await client.decrypt({
source: {
type: 'stream',
location: encryptedStream.stream,
},
});
assert.fail('Expected InvalidFileError');
} catch (error) {
assert.instanceOf(error, NetworkError);
assert.include(error.message, '404 Not Found');
}
});
});
describe('encrypt decrypt test', async function () {
const expectedVal = 'hello world';
const kasUrl = `http://localhost:3000`;
for (const encapKeyType of ['ec:secp256r1', 'rsa:2048'] as KasPublicKeyAlgorithm[]) {
for (const rewrapKeyType of ['ec:secp256r1', 'rsa:2048'] as KasPublicKeyAlgorithm[]) {
it(`encrypt-decrypt stream source happy path {encap: ${encapKeyType}, rewrap: ${rewrapKeyType}}`, async function () {
const cipher = new AesGcmCipher(WebCryptoService);
const encryptionInformation = new SplitKey(cipher);
const key1 = await encryptionInformation.generateKey();
const keyMiddleware = async () => ({ keyForEncryption: key1, keyForManifest: key1 });
const client = new Client.Client({
kasEndpoint: kasUrl,
platformUrl: kasUrl,
dpopKeys: Mocks.entityKeyPair(),
clientId: 'id',
authProvider,
});
// Generate RSA key pair for RS256 assertions as PEM strings
const assertionKeys = await client.cryptoService.generateSigningKeyPair();
const assertionPublicKey = assertionKeys.publicKey;
const assertionPrivateKey = assertionKeys.privateKey;
const scope: Scope = {
dissem: ['user@domain.com'],
attributes: [],
};
// Generate a random HS256 key
const hs256Key = new Uint8Array(32);
crypto.getRandomValues(hs256Key);
console.log('ASDF about to encrypt');
const encryptedStream = await client.encrypt({
metadata: Mocks.getMetadataObject(),
wrappingKeyAlgorithm: encapKeyType,
offline: true,
scope,
keyMiddleware,
source: new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(expectedVal));
controller.close();
},
}),
assertionConfigs: [
{
id: 'assertion1',
type: 'handling',
scope: 'tdo',
statement: {
format: 'json',
schema: 'https://example.com/schema',
value: '{"example": "value"}',
},
appliesToState: 'encrypted',
signingKey: {
alg: 'HS256',
key: hs256Key,
},
},
{
id: 'assertion2',
type: 'handling',
scope: 'tdo',
statement: {
format: 'json',
schema: 'https://example.com/schema',
value: '{"example": "value"}',
},
appliesToState: 'encrypted',
signingKey: {
alg: 'RS256',
key: assertionPrivateKey,
},
},
{
id: 'assertion3',
type: 'handling',
scope: 'tdo',
statement: {
format: 'json',
schema: 'https://example.com/schema',
value: '{"example": "value"}',
},
appliesToState: 'encrypted',
},
// Add more assertion configs as needed
] as AssertionConfig[],
});
// Create AssertionVerificationKeys for verification
const assertionVerificationKeys: AssertionVerificationKeys = {
Keys: {
assertion1: {
alg: 'HS256',
key: hs256Key,
},
assertion2: {
alg: 'RS256',
key: assertionPublicKey,
},
},
};
const decryptStream = await client.decrypt({
source: {
type: 'stream',
location: encryptedStream.stream,
},
assertionVerificationKeys,
wrappingKeyAlgorithm: rewrapKeyType,
});
const { value: decryptedText } = await decryptStream.stream.getReader().read();
assert.equal(new TextDecoder().decode(decryptedText), expectedVal);
});
}
}
it('decrypts when the same KAS wraps the same split twice (DSPX-3379)', async function () {
const cipher = new AesGcmCipher(WebCryptoService);
const encryptionInformation = new SplitKey(cipher);
const key1 = await encryptionInformation.generateKey();
const keyMiddleware = async () => ({ keyForEncryption: key1, keyForManifest: key1 });
const client = new Client.Client({
kasEndpoint: kasUrl,
platformUrl: kasUrl,
allowedKases: [kasUrl],
dpopKeys: Mocks.entityKeyPair(),
clientId: 'id',
authProvider,
});
const scope: Scope = { dissem: ['user@domain.com'], attributes: [] };
// Two KAOs pointing at the same KAS for the same split id: the same KAS
// wraps the same split twice. Previously this threw; now the copies are
// disjunction alternatives and the file must still decrypt.
const encryptedStream = await client.encrypt({
metadata: Mocks.getMetadataObject(),
wrappingKeyAlgorithm: 'rsa:2048',
offline: true,
scope,
keyMiddleware,
splitPlan: [
{ kas: kasUrl, sid: '1' },
{ kas: kasUrl, sid: '1' },
],
source: new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(expectedVal));
controller.close();
},
}),
});
const kaos = encryptedStream.manifest.encryptionInformation.keyAccess;
assert.equal(kaos.length, 2, 'expected two KAOs for the duplicated split');
assert.equal(kaos[0].url, kaos[1].url);
assert.equal(kaos[0].sid, kaos[1].sid);
const decryptStream = await client.decrypt({
source: { type: 'stream', location: encryptedStream.stream },
wrappingKeyAlgorithm: 'rsa:2048',
});
const { value: decryptedText } = await decryptStream.stream.getReader().read();
assert.equal(new TextDecoder().decode(decryptedText), expectedVal);
});
it('encrypt-decrypt with system metadata assertion', async function () {
const cipher = new AesGcmCipher(WebCryptoService);
const encryptionInformation = new SplitKey(cipher);
const key1 = await encryptionInformation.generateKey();
const keyMiddleware = async () => ({ keyForEncryption: key1, keyForManifest: key1 });
const client = new Client.Client({
kasEndpoint: kasUrl,
platformUrl: kasUrl,
dpopKeys: Mocks.entityKeyPair(),
clientId: 'id',
authProvider,
});
const scope: Scope = {
dissem: ['user@domain.com'],
attributes: [],
};
const encryptedStream = await client.encrypt({
metadata: Mocks.getMetadataObject(),
wrappingKeyAlgorithm: 'rsa:2048',
offline: true,
scope,
keyMiddleware,
source: new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(expectedVal));
controller.close();
},
}),
systemMetadataAssertion: true, // Enable the system metadata assertion
});
// Consume the stream into a buffer. This also ensures manifest population is complete.
const encryptedTdfBuffer = await encryptedStream.toBuffer();
// Verify the manifest for the system metadata assertion
const manifest = encryptedStream.manifest;
assert.isArray(manifest.assertions, 'Manifest assertions should be an array');
assert.lengthOf(manifest.assertions, 1, 'Should have one assertion for system metadata');
const systemAssertion = manifest.assertions.find(
(assertion: Assertion) => assertion.id === 'system-metadata'
);
assert.isDefined(systemAssertion, 'System metadata assertion should be found');
if (systemAssertion) {
assert.equal(systemAssertion.type, 'other', 'Assertion type should be "other"');
assert.equal(systemAssertion.scope, 'tdo', 'Assertion scope should be "tdo"');
assert.equal(systemAssertion.statement.format, 'json', 'Statement format should be "json"');
assert.equal(
systemAssertion.statement.schema,
'system-metadata-v1',
'Statement schema should be "system-metadata-v1"'
);
const metadataValue = JSON.parse(systemAssertion.statement.value);
assert.property(metadataValue, 'tdf_spec_version', 'Metadata should have tdfSpecVersion');
assert.property(metadataValue, 'creation_date', 'Metadata should have creationDate');
assert.property(metadataValue, 'sdk_version', 'Metadata should have sdkVersion');
assert.property(metadataValue, 'browser_user_agent', 'Metadata should have browserUserAgent');
assert.property(metadataValue, 'platform', 'Metadata should have platform');
// Compare Values
const systemMetadata = getSystemMetadataAssertionConfig();
assert.equal(systemMetadata.id, systemAssertion.id, 'ID should match');
assert.equal(systemMetadata.type, systemAssertion.type, 'Type should match');
assert.equal(systemMetadata.scope, systemAssertion.scope, 'Scope should match');
assert.equal(
systemMetadata.statement.format,
systemAssertion.statement.format,
'Statement format should match'
);
assert.equal(
systemMetadata.statement.schema,
systemAssertion.statement.schema,
'Statement schema should match'
);
assert.equal(
systemMetadata.appliesToState,
systemAssertion.appliesToState,
'AppliesToState should match'
);
// Parse statement.value and compare individual fields, ignoring creationDate for direct equality
const expectedMetadataValue = JSON.parse(systemMetadata.statement.value);
const actualMetadataValue = JSON.parse(systemAssertion.statement.value);
assert.isString(actualMetadataValue.creation_date, 'creation_date should be a string');
assert.isNotEmpty(actualMetadataValue.creation_date, 'creation_date should not be empty');
assert.equal(
actualMetadataValue.tdf_spec_version,
expectedMetadataValue.tdf_spec_version,
'tdf_spec_version should match'
);
assert.equal(
actualMetadataValue.sdk_version,
expectedMetadataValue.sdk_version,
'sdk_version should match'
);
assert.equal(
actualMetadataValue.browser_user_agent,
expectedMetadataValue.browser_user_agent,
'browser_user_agent should match'
);
assert.equal(
actualMetadataValue.platform,
expectedMetadataValue.platform,
'platform should match'
);
}
const decryptStream = await client.decrypt({
source: { type: 'buffer', location: encryptedTdfBuffer },
});
const { value: decryptedText } = await decryptStream.stream.getReader().read();
assert.equal(new TextDecoder().decode(decryptedText), expectedVal);
});
});