Repository navigation
Expand file tree
/
Copy pathsendotp.test.js
More file actions
811 lines (770 loc) · 37.3 KB
/
Copy pathsendotp.test.js
File metadata and controls
811 lines (770 loc) · 37.3 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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
'use strict';
const { test, beforeEach, afterEach, mock } = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const Module = require('node:module');
const { CompactEncrypt } = require('jose');
const { ClientAssertionCredential, ManagedIdentityCredential } = require('@azure/identity');
const { SecretClient } = require('@azure/keyvault-secrets');
const fixtures = require('../../tests/fixtures/contract.json');
const providers = require('../src/functions/providers');
const jwe = require('../src/functions/jwe');
const {
CredentialTokenService,
credentialTokenService,
} = require('../src/functions/credentials');
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
let handler;
let startHook;
let stopHook;
const originalLoad = Module._load;
const registration = mock.method(Module, '_load', function (name, ...args) {
if (name === './providers') {
return { selectProvider: (...args) => providers.selectProvider(...args) };
}
if (name === './jwe') {
return { decryptDeliveryContext: (...args) => jwe.decryptDeliveryContext(...args) };
}
if (name === '@azure/functions') {
return {
app: {
hook: {
appStart: (callback) => { startHook = callback; },
appTerminate: (callback) => { stopHook = callback; },
},
http: (_name, options) => { handler = options.handler; },
},
};
}
return originalLoad.call(this, name, ...args);
});
try {
require('../src/functions/SendOtp');
} finally {
registration.mock.restore();
}
const envKeys = [
'EPP_ENCRYPTION_KEY_ID', 'AZURE_CLIENT_ID', 'EPP_PROVIDER_NAME',
'EPP_PROVIDER_ENDPOINT', 'EPP_PROVIDER_CHANNEL', 'EPP_PROVIDER_TIMEOUT_MS',
'EPP_PROVIDER_SMS_ENDPOINT', 'EPP_PROVIDER_VOICE_ENDPOINT',
'EPP_PROVIDER_AUTH_MODE', 'EPP_PROVIDER_TENANT_ID', 'EPP_PROVIDER_SCOPE',
'EPP_OUTBOUND_CLIENT_ID', 'EPP_OUTBOUND_MI_CLIENT_ID', 'KEY_VAULT_URL',
'EPP_DECRYPTION_KEY_PEM', 'SINCH_SERVICE_PLAN_ID', 'SINCH_VOICE_ENDPOINT',
'EPP_KEY_VAULT_CACHE_ENABLED', 'EPP_ACCESS_TOKEN_CACHE_ENABLED',
];
const baseDelivery = {
nonce: 'PRIVATE-NONCE',
phoneNumber: '+15551234567',
message: ' PRIVATE-MESSAGE 918273.\n',
locale: 'fr-FR',
riskContext: { value: 'PRIVATE-RISK' },
};
let savedEnv;
let service;
let fetchMock;
let getSecret;
let getToken;
let records;
beforeEach(() => {
savedEnv = Object.fromEntries(envKeys.map((key) => [key, process.env[key]]));
for (const key of envKeys) delete process.env[key];
Object.assign(process.env, {
EPP_DECRYPTION_KEY_PEM: privateKey.export({ type: 'pkcs8', format: 'pem' }),
KEY_VAULT_URL: 'https://unit-test.vault.azure.net',
EPP_PROVIDER_NAME: 'soprano',
EPP_PROVIDER_SMS_ENDPOINT: 'https://provider.example/epp/messages',
EPP_PROVIDER_VOICE_ENDPOINT: 'https://provider.example/epp/messages',
EPP_PROVIDER_AUTH_MODE: 'oauth',
EPP_PROVIDER_TENANT_ID: '11111111-1111-1111-1111-111111111111',
EPP_PROVIDER_SCOPE: 'api://provider/.default',
EPP_OUTBOUND_CLIENT_ID: '22222222-2222-2222-2222-222222222222',
EPP_OUTBOUND_MI_CLIENT_ID: '33333333-3333-3333-3333-333333333333',
});
service = new CredentialTokenService();
mock.method(credentialTokenService, 'getCredentials',
(...args) => service.getCredentials(...args));
mock.method(credentialTokenService, 'close', () => service.close());
mock.method(ManagedIdentityCredential.prototype, 'getToken', async () => ({
token: 'PRIVATE-ASSERTION',
expiresOnTimestamp: Date.now() + 3600000,
}));
getToken = mock.method(ClientAssertionCredential.prototype, 'getToken', async function () {
assert.equal(await this.getAssertion(), 'PRIVATE-ASSERTION');
return { token: 'PRIVATE-OAUTH-TOKEN', expiresOnTimestamp: Date.now() + 3600000 };
});
getSecret = mock.method(SecretClient.prototype, 'getSecret',
async () => ({ value: 'PRIVATE-API-KEY' }));
fetchMock = mock.method(global, 'fetch', async () => ({
ok: true,
status: 201,
text: async () => JSON.stringify({
status: 'ENROUTE',
id: 'provider-reference-id',
description: 'PRIVATE-STATUS',
}),
}));
});
afterEach(() => {
service.close();
mock.restoreAll();
for (const [key, value] of Object.entries(savedEnv)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
async function envelope(overrides = {}, delivery = baseDelivery, protectedHeader = {}) {
const encryptedDeliveryContext = await new CompactEncrypt(Buffer.from(JSON.stringify(delivery)))
.setProtectedHeader({
alg: 'RSA-OAEP-256',
enc: 'A256GCM',
kid: 'PRIVATE-KID',
...protectedHeader,
})
.encrypt(publicKey);
return {
type: 'microsoft.mfa.otpDeliver.v1',
channel: 1,
mode: 1,
ttlSeconds: 60,
correlationId: 'correlation-id',
encryptedDeliveryContext,
...overrides,
};
}
async function invoke(body, headers = {}) {
records = [];
const capture = (value) => records.push(JSON.parse(value));
const result = await handler({
headers: { get: (name) => headers[name.toLowerCase()] ?? null },
text: async () => typeof body === 'string' ? body : JSON.stringify(body),
}, {
invocationId: 'function-invocation-id',
log: capture,
warn: capture,
error: capture,
});
assert.equal(records.at(-1).eventName, 'request_completed');
assert.equal(records.at(-1).httpStatus, result.status);
assert.equal(records.filter((event) => event.eventName === 'request_completed').length, 1);
assert.equal(records.filter((event) => event.eventName === 'response_prepared').length, 1);
assert.ok(records.every((event) => event.functionRequestId
&& event.functionInvocationId === 'function-invocation-id'));
assert.doesNotMatch(JSON.stringify(records), /PRIVATE|FORGED|918273|15551234567/);
return result;
}
function failure(result, status, error = 'provider_delivery_failed') {
assert.equal(result.status, status);
assert.equal(result.jsonBody.error, error);
assert.equal(result.jsonBody.nonce, undefined);
}
function event(name) {
return records.find((record) => record.eventName === name);
}
for (const channel of ['sms', 'voice']) {
for (const [name, fields] of [
['present', { otp: '001234' }], ['omitted', {}], ['null', { otp: null }],
]) {
test(`${channel}: ${name} OTP survives decryption and live delivery without evaluation I/O`, async () => {
const provider = providers.selectProvider('soprano');
const createRequest = mock.fn((input) => provider.createRequest(input));
const selectProvider = mock.method(providers, 'selectProvider',
() => ({ ...provider, createRequest }));
const context = {
...baseDelivery,
message: baseDelivery.message.replace('918273', '001234'),
...fields,
};
const body = await envelope({ channel }, context);
const expected = {
nonce: context.nonce, correlationId: body.correlationId, providerStatus: 'accepted',
};
const evaluated = await invoke({ ...body, mode: 2 });
assert.equal(evaluated.status, 200);
assert.deepEqual(evaluated.jsonBody, expected);
assert.deepEqual([
selectProvider.mock.callCount(), getSecret.mock.callCount(),
getToken.mock.callCount(), fetchMock.mock.callCount(),
], [0, 0, 0, 0]);
assert.doesNotMatch(JSON.stringify(records), /001234|"otp"/);
const result = await invoke(body);
assert.equal(result.status, 200);
assert.deepEqual(result.jsonBody, expected);
assert.equal(createRequest.mock.callCount(), 1);
const delivery = createRequest.mock.calls[0].arguments[0].delivery;
assert.equal(delivery.otp, fields.otp);
assert.equal(delivery.message, context.message);
assert.equal(delivery.channel, channel);
assert.equal(fetchMock.mock.callCount(), 1);
assert.doesNotMatch(JSON.stringify(records), /001234|"otp"/);
});
}
}
test('non-string OTP values fail before provider work', async () => {
for (const otp of [123456, true, [], {}]) {
const result = await invoke(await envelope({ mode: 2 }, { ...baseDelivery, otp }));
failure(result, 400, 'bad_request');
assert.equal(result.jsonBody.reason, 'incomplete delivery context');
assert.equal(event('request_failed').failureStage, 'delivery_context_validation');
}
assert.deepEqual([
getSecret.mock.callCount(), getToken.mock.callCount(), fetchMock.mock.callCount(),
], [0, 0, 0]);
});
for (const channel of ['sms', 'voice']) {
for (const { name, overrides } of fixtures.riskContexts) {
test(`${channel}: ${name} risk context reaches the adapter but not its wire request`, async () => {
const provider = providers.selectProvider('soprano');
const createRequest = mock.fn((input) => provider.createRequest(input));
mock.method(providers, 'selectProvider', () => ({ ...provider, createRequest }));
const context = { ...baseDelivery, riskContext: undefined, ...overrides };
const body = await envelope({ channel }, context);
const expected = {
nonce: context.nonce, correlationId: body.correlationId, providerStatus: 'accepted',
};
const evaluated = await invoke({ ...body, mode: 2 });
assert.equal(evaluated.status, 200);
assert.deepEqual(evaluated.jsonBody, expected);
assert.deepEqual([
createRequest.mock.callCount(), getSecret.mock.callCount(),
getToken.mock.callCount(), fetchMock.mock.callCount(),
], [0, 0, 0, 0]);
assert.doesNotMatch(JSON.stringify(records), /riskContext/);
const result = await invoke(body);
assert.equal(result.status, 200);
assert.deepEqual(result.jsonBody, expected);
assert.equal(createRequest.mock.callCount(), 1);
const input = createRequest.mock.calls[0].arguments[0];
assert.deepEqual(input.delivery.riskContext, overrides.riskContext);
assert.equal(input.delivery.message, context.message);
assert.equal(input.delivery.channel, channel);
const withoutRisk = provider.createRequest({
...input, delivery: { ...input.delivery, riskContext: undefined },
});
assert.equal(fetchMock.mock.callCount(), 1);
assert.equal(fetchMock.mock.calls[0].arguments[1].body, withoutRisk.body);
assert.doesNotMatch(JSON.stringify(records), /riskContext/);
});
}
}
for (const mode of [1, 2]) {
test(`mode ${mode}: non-object risk context fails before provider work`, async () => {
for (const riskContext of fixtures.invalidRiskContexts) {
const result = await invoke(await envelope({ mode }, { ...baseDelivery, riskContext }));
failure(result, 400, 'bad_request');
assert.equal(result.jsonBody.reason, 'incomplete delivery context');
assert.equal(event('request_failed').failureStage, 'delivery_context_validation');
assert.doesNotMatch(JSON.stringify(result.jsonBody), /PRIVATE-RISK/);
}
assert.deepEqual([
getSecret.mock.callCount(), getToken.mock.callCount(), fetchMock.mock.callCount(),
], [0, 0, 0]);
});
}
for (const provider of ['telesign', 'soprano']) {
test(`${provider}: only live requests acquire credentials and obsolete cache settings are ignored`, async () => {
const apiKey = provider === 'telesign';
process.env.EPP_PROVIDER_NAME = provider;
process.env.EPP_PROVIDER_AUTH_MODE = apiKey ? 'apiKey' : 'oauth';
process.env.EPP_KEY_VAULT_CACHE_ENABLED = 'PRIVATE-OBSOLETE';
process.env.EPP_ACCESS_TOKEN_CACHE_ENABLED = 'PRIVATE-OBSOLETE';
if (apiKey) fetchMock.mock.mockImplementation(async () => ({
ok: true, status: 200, text: async () => JSON.stringify({ status: { code: 3001 } }),
}));
assert.equal(startHook, undefined);
const evaluated = await invoke(await envelope({ mode: 2 }));
assert.equal(evaluated.status, 200);
assert.equal(evaluated.jsonBody.nonce, baseDelivery.nonce);
assert.deepEqual([getSecret.mock.callCount(), getToken.mock.callCount(), fetchMock.mock.callCount()], [0, 0, 0]);
for (let i = 0; i < 2; i++) assert.equal((await invoke(await envelope())).status, 200);
assert.equal(getSecret.mock.callCount(), apiKey ? 4 : 0);
assert.equal(getToken.mock.callCount(), apiKey ? 0 : 2);
});
}
test('a credential failure is request-correlated and the next live request can recover immediately', async () => {
getToken.mock.mockImplementationOnce(async () => { throw new Error('PRIVATE-SDK-FAILURE'); });
assert.equal((await invoke(await envelope({ mode: 2 }))).status, 200);
failure(await invoke(await envelope()), 502);
assert.equal(event('request_failed').failureStage, 'provider_credentials');
assert.equal(event('request_failed').failureReason, 'credential_unavailable');
assert.equal(fetchMock.mock.callCount(), 0);
assert.equal((await invoke(await envelope())).status, 200);
assert.equal(getToken.mock.callCount(), 2);
assert.equal(fetchMock.mock.callCount(), 1);
});
test('startup does not warm credentials and shutdown closes pending acquisition', async () => {
assert.equal(startHook, undefined);
assert.equal(getToken.mock.callCount(), 0);
assert.equal(getSecret.mock.callCount(), 0);
assert.equal(fetchMock.mock.callCount(), 0);
await invoke(await envelope());
assert.equal(getToken.mock.callCount(), 1);
assert.equal(fetchMock.mock.callCount(), 1);
stopHook();
failure(await invoke(await envelope()), 502);
assert.equal(event('request_failed').failureReason, 'credential_unavailable');
});
test('startup without a provider and evaluation perform no provider I/O', async () => {
delete process.env.EPP_PROVIDER_NAME;
assert.equal(startHook, undefined);
const result = await invoke(await envelope({ mode: 'evaluation' }));
assert.equal(result.status, 200);
assert.equal(result.jsonBody.nonce, baseDelivery.nonce);
assert.deepEqual([getToken.mock.callCount(), getSecret.mock.callCount(), fetchMock.mock.callCount()],
[0, 0, 0]);
assert.equal(event('evaluation_completed').eventName, 'evaluation_completed');
});
for (const field of ['channel', 'mode']) {
for (const value of [
'constructor', '__proto__', 'CONSTRUCTOR', '__PROTO__',
'toString', 'valueOf', 'hasOwnProperty', 'unsupported',
]) {
test(`${field}: unsupported enum ${value} fails before decryption and provider work`, async () => {
const decrypt = mock.method(jwe, 'decryptDeliveryContext');
const selectProvider = mock.method(providers, 'selectProvider');
const result = await invoke(await envelope({ [field]: value }));
assert.deepEqual({
status: result.status,
nonce: result.jsonBody.nonce,
decryptionCalls: decrypt.mock.callCount(),
providerSelections: selectProvider.mock.callCount(),
credentialCalls: credentialTokenService.getCredentials.mock.callCount(),
providerCalls: fetchMock.mock.callCount(),
}, {
status: 400,
nonce: undefined,
decryptionCalls: 0,
providerSelections: 0,
credentialCalls: 0,
providerCalls: 0,
});
failure(result, 400, 'bad_request');
assert.equal(result.jsonBody.reason, `unsupported ${field}`);
assert.equal(event('request_failed').failureStage, 'request_validation');
assert.equal(event('envelope_validated'), undefined);
assert.deepEqual([getToken.mock.callCount(), getSecret.mock.callCount()], [0, 0]);
});
}
}
for (const [channelName, channels] of [
['sms', [1, 'sms', 'SMS', 'sMs']],
['voice', [2, 'voice', 'VOICE', 'VoIcE']],
]) {
for (const [evaluation, modes] of [
[false, [1, 'live', 'LIVE', 'LiVe']],
[true, [2, 'evaluation', 'EVALUATION', 'EvAlUaTiOn']],
]) {
test(`enum variants preserve ${channelName} ${evaluation ? 'evaluation' : 'live'} behavior`, async () => {
const selectProvider = mock.method(providers, 'selectProvider');
process.env.EPP_PROVIDER_SMS_ENDPOINT = 'https://sms.provider.example/send';
process.env.EPP_PROVIDER_VOICE_ENDPOINT = 'https://voice.provider.example/send';
let sends = 0;
for (const channel of channels) {
for (const mode of modes) {
const body = await envelope({ channel, mode });
const result = await invoke(body);
assert.deepEqual(result, {
status: 200,
jsonBody: {
nonce: baseDelivery.nonce,
correlationId: body.correlationId,
providerStatus: 'accepted',
},
});
if (!evaluation) {
sends++;
const [url, init] = fetchMock.mock.calls.at(-1).arguments;
assert.equal(url, channelName === 'voice'
? process.env.EPP_PROVIDER_VOICE_ENDPOINT : process.env.EPP_PROVIDER_SMS_ENDPOINT);
assert.deepEqual(JSON.parse(init.body).messageTypes, [channelName]);
}
assert.deepEqual([
selectProvider.mock.callCount(), credentialTokenService.getCredentials.mock.callCount(),
getToken.mock.callCount(), getSecret.mock.callCount(), fetchMock.mock.callCount(),
], [sends, sends, sends, 0, sends]);
assert.equal(event('evaluation_completed') !== undefined, evaluation);
}
}
});
}
}
test('shared invalid requests preserve exact reasons and never perform provider I/O', async () => {
const valid = {
type: 'microsoft.mfa.otpDeliver.v1',
channel: 1,
mode: 1,
encryptedDeliveryContext: 'unused',
};
for (const fixture of fixtures.badRequests) {
const result = await invoke(fixture.rawBody ?? { ...valid, ...fixture.overrides });
failure(result, 400, 'bad_request');
assert.equal(result.jsonBody.reason, fixture.reason, fixture.name);
assert.equal(event('request_failed').failureStage, 'request_validation');
}
for (const changes of fixtures.incompleteContexts) {
const result = await invoke(await envelope({ mode: 2 }, { ...baseDelivery, ...changes }));
failure(result, 400, 'bad_request');
assert.equal(result.jsonBody.reason, 'incomplete delivery context');
assert.equal(event('request_failed').failureStage, 'delivery_context_validation');
}
assert.deepEqual([getToken.mock.callCount(), getSecret.mock.callCount(), fetchMock.mock.callCount()],
[0, 0, 0]);
});
test('JWE algorithm policy, size/shape and bad tags fail before provider I/O', async () => {
for (const fixture of fixtures.jwe) {
const result = await invoke(await envelope({ mode: 2 }, baseDelivery, fixture));
if (fixture.accepted) assert.equal(result.status, 200);
else failure(result, 400, 'decryption_failed');
}
const body = await envelope({ mode: 2 });
const parts = body.encryptedDeliveryContext.split('.');
parts[4] = `${parts[4][0] === 'A' ? 'B' : 'A'}${parts[4].slice(1)}`;
for (const encryptedDeliveryContext of [
parts.join('.'),
parts.slice(0, 4).join('.'),
'a'.repeat(16385),
]) {
failure(await invoke({ ...body, encryptedDeliveryContext }), 400, 'decryption_failed');
}
assert.equal(fetchMock.mock.callCount(), 0);
});
test('JWE authenticates original protected bytes and caches PEM-compatible keys', async () => {
const header = '{ "kid" : "test-key", "enc" : "A256GCM", "alg" : "RSA-OAEP-256" }';
const encodedHeader = Buffer.from(header).toString('base64url');
const contentKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', contentKey, iv);
cipher.setAAD(Buffer.from(encodedHeader, 'ascii'));
const ciphertext = Buffer.concat([
cipher.update(JSON.stringify(baseDelivery), 'utf8'),
cipher.final(),
]);
const wrappedKey = crypto.publicEncrypt({
key: publicKey,
oaepHash: 'sha256',
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
}, contentKey);
const segments = [encodedHeader, ...[wrappedKey, iv, ciphertext, cipher.getAuthTag()]
.map((value) => value.toString('base64url'))];
const body = await envelope({ mode: 2, encryptedDeliveryContext: segments.join('.') });
assert.equal((await invoke(body)).status, 200);
segments[0] = Buffer.from(JSON.stringify(JSON.parse(header))).toString('base64url');
failure(await invoke({ ...body, encryptedDeliveryContext: segments.join('.') }),
400, 'decryption_failed');
const certificate = require('node:tls').rootCertificates[0];
const pem = privateKey.export({ type: 'pkcs8', format: 'pem' });
for (const bundle of [`${certificate}\n${pem}`, `${pem}\n${certificate}`]) {
for (const value of [bundle, Buffer.from(bundle).toString('base64')]) {
process.env.EPP_DECRYPTION_KEY_PEM = value;
assert.equal((await invoke(await envelope({ mode: 2 }))).status, 200);
}
}
});
test('evaluation checks advisory key ID but remains provider-independent', async () => {
delete process.env.EPP_PROVIDER_SMS_ENDPOINT;
delete process.env.EPP_PROVIDER_VOICE_ENDPOINT;
delete process.env.KEY_VAULT_URL;
process.env.EPP_ENCRYPTION_KEY_ID = 'different-kid';
const result = await invoke(await envelope({ mode: 2 }));
assert.equal(result.status, 200);
assert.ok(event('encryption_key_id_mismatch'));
assert.equal(event('provider_selected'), undefined);
assert.deepEqual([getToken.mock.callCount(), getSecret.mock.callCount(), fetchMock.mock.callCount()],
[0, 0, 0]);
});
for (const provider of ['telesign', 'soprano']) {
for (const legacyChannel of [undefined, 'sms', 'voice', 'invalid']) {
test(`${provider}: request selects either channel with legacy setting ${legacyChannel}`, async () => {
process.env.EPP_PROVIDER_NAME = provider;
process.env.EPP_PROVIDER_AUTH_MODE = provider === 'telesign' ? 'apiKey' : 'oauth';
if (legacyChannel !== undefined) process.env.EPP_PROVIDER_CHANNEL = legacyChannel;
fetchMock.mock.mockImplementation(async () => ({
ok: true,
status: 200,
text: async () => JSON.stringify({
status: provider === 'telesign' ? { code: 3001 } : 'ENROUTE',
}),
}));
for (const [channel, channelName] of [[1, 'sms'], ['SMS', 'sms'], [2, 'voice'], ['VOICE', 'voice']]) {
const result = await invoke(await envelope({ channel }));
assert.equal(result.status, 200);
assert.equal(result.jsonBody.nonce, baseDelivery.nonce);
const [url, init] = fetchMock.mock.calls.at(-1).arguments;
assert.equal(url, channelName === 'voice'
? process.env.EPP_PROVIDER_VOICE_ENDPOINT : process.env.EPP_PROVIDER_SMS_ENDPOINT);
const body = JSON.parse(init.body);
if (provider === 'telesign') {
assert.deepEqual(body.channels, [{ channel: channelName }]);
} else {
assert.deepEqual(body.messageTypes, [channelName]);
}
}
assert.equal(fetchMock.mock.callCount(), 4);
});
}
}
for (const [provider, response, smsPath, voicePath] of [
['telesign', { status: { code: 3001 } }, '', ''],
['soprano', { status: 'ENROUTE' }, '', ''],
['infobip', { messages: [{ status: { groupName: 'PENDING' } }] }, '/sms/3/messages', '/tts/3/advanced'],
['sinch', { id: 'provider-id' }, '/xms/v1/plan/batches', '/calling/v1/callouts'],
]) {
test(`${provider}: request channel selects distinct configured endpoints`, async () => {
Object.assign(process.env, {
EPP_PROVIDER_NAME: provider,
EPP_PROVIDER_AUTH_MODE: provider === 'soprano' ? 'oauth' : 'apiKey',
EPP_PROVIDER_SMS_ENDPOINT: 'https://sms.provider.example/send',
EPP_PROVIDER_VOICE_ENDPOINT: 'https://voice.provider.example/send',
SINCH_SERVICE_PLAN_ID: 'plan',
SINCH_VOICE_ENDPOINT: 'https://legacy.provider.example',
});
fetchMock.mock.mockImplementation(async () => ({
ok: true, status: 200, text: async () => JSON.stringify(response),
}));
for (const legacyEndpoint of [undefined, 'https://legacy.provider.example']) {
if (legacyEndpoint === undefined) delete process.env.EPP_PROVIDER_ENDPOINT;
else process.env.EPP_PROVIDER_ENDPOINT = legacyEndpoint;
for (const [channel, endpoint, path] of [
[1, process.env.EPP_PROVIDER_SMS_ENDPOINT, smsPath],
[2, process.env.EPP_PROVIDER_VOICE_ENDPOINT, voicePath],
]) {
const result = await invoke(await envelope({ channel }));
assert.equal(result.status, 200);
assert.equal(result.jsonBody.nonce, baseDelivery.nonce);
assert.equal(fetchMock.mock.calls.at(-1).arguments[0], endpoint + path);
}
}
assert.equal(fetchMock.mock.callCount(), 4);
});
}
for (const channel of ['sms', 'voice']) {
test(`${channel}: requires its endpoint without legacy or cross-channel fallback`, async () => {
const selected = channel === 'sms' ? 'EPP_PROVIDER_SMS_ENDPOINT' : 'EPP_PROVIDER_VOICE_ENDPOINT';
const other = channel === 'sms' ? 'EPP_PROVIDER_VOICE_ENDPOINT' : 'EPP_PROVIDER_SMS_ENDPOINT';
process.env.EPP_PROVIDER_ENDPOINT = 'https://legacy.provider.example/send';
process.env[other] = 'https://other.provider.example/send';
for (const value of [undefined, '', ' ', 'http://invalid.provider.example']) {
if (value === undefined) delete process.env[selected];
else process.env[selected] = value;
failure(await invoke(await envelope({ channel })), 502);
assert.equal(event('request_failed').failureReason, 'invalid_provider_endpoint');
assert.equal((await invoke(await envelope({ channel, mode: 2 }))).status, 200);
}
assert.equal(fetchMock.mock.callCount(), 0);
process.env[selected] = 'https://selected.provider.example/send';
process.env[other] = 'http://invalid.provider.example';
assert.equal((await invoke(await envelope({ channel }))).status, 200);
assert.equal(fetchMock.mock.calls[0].arguments[0], process.env[selected]);
assert.equal(fetchMock.mock.callCount(), 1);
});
}
test('live Soprano flow preserves message/correlation and never forwards inbound authorization', async () => {
const result = await invoke(await envelope(), {
authorization: 'FORGED-INBOUND-AUTH',
'x-ms-client-principal': 'FORGED-PRINCIPAL',
'x-ms-client-request-id': 'client-request-id',
});
assert.deepEqual(result, {
status: 200,
jsonBody: {
nonce: baseDelivery.nonce,
correlationId: 'correlation-id',
providerStatus: 'accepted',
},
});
const [url, init] = fetchMock.mock.calls[0].arguments;
assert.equal(url, process.env.EPP_PROVIDER_SMS_ENDPOINT);
assert.equal(init.redirect, 'manual');
assert.equal(init.headers.Authorization, 'Bearer PRIVATE-OAUTH-TOKEN');
assert.notEqual(init.headers.Authorization, 'FORGED-INBOUND-AUTH');
assert.deepEqual(JSON.parse(init.body), {
destination: '15551234567',
messageTypes: ['sms'],
correlationId: 'correlation-id',
shutterMode: false,
text: baseDelivery.message,
});
assert.deepEqual(records.map((record) => record.eventName), [
'request_received',
'envelope_validated',
'delivery_context_decrypted',
'provider_selected',
'provider_credential_resolution_started',
'provider_credential_resolved',
'provider_request_build_started',
'provider_request_built',
'provider_request_started',
'provider_response_received',
'provider_response_processed',
'response_prepared',
'request_completed',
]);
assert.equal(event('provider_response_processed').providerMessageId, 'provider-reference-id');
});
test('Soprano voice derives the first rendered six-digit code', async () => {
const result = await invoke(await envelope({ channel: 2 }, {
...baseDelivery,
message: 'Before 001234 after 654321.',
}));
assert.equal(result.status, 200);
assert.deepEqual(JSON.parse(fetchMock.mock.calls[0].arguments[1].body).voice.text2voice, {
beforePasswordText: 'Before ',
password: '001234',
afterPasswordText: ' after 654321.',
language: 'fr-FR',
gender: 1,
loop: 2,
});
});
test('provider selection, configuration, credential and request-build failures are fixed and safe', async () => {
const cases = [
['provider_selection', 'unknown_provider', 400, () => {
process.env.EPP_PROVIDER_NAME = 'PRIVATE-UNKNOWN';
}, {}],
['provider_configuration', 'authentication_mode_mismatch', 502, () => {
process.env.EPP_PROVIDER_AUTH_MODE = 'apiKey';
}, {}],
['provider_configuration', 'invalid_provider_endpoint', 502, () => {
process.env.EPP_PROVIDER_SMS_ENDPOINT = 'http://PRIVATE-ENDPOINT';
}, {}],
['provider_request_build', 'request_build_failed', 502, () => {}, {
delivery: { ...baseDelivery, message: 'No passcode here.' },
envelope: { channel: 2 },
}],
];
for (const [stage, reason, status, configure, options] of cases) {
configure();
const result = await invoke(await envelope(options.envelope, options.delivery || baseDelivery));
failure(result, status);
assert.deepEqual([event('request_failed').failureStage, event('request_failed').failureReason],
[stage, reason]);
Object.assign(process.env, {
EPP_PROVIDER_NAME: 'soprano',
EPP_PROVIDER_SMS_ENDPOINT: 'https://provider.example/epp/messages',
EPP_PROVIDER_AUTH_MODE: 'oauth',
});
}
});
test('credential failure emits request_failed without provider HTTP', async () => {
credentialTokenService.getCredentials.mock.mockImplementation(async () => {
throw new Error('PRIVATE-CREDENTIAL-FAILURE');
});
failure(await invoke(await envelope()), 502);
assert.deepEqual([
event('request_failed').failureStage,
event('request_failed').failureReason,
fetchMock.mock.callCount(),
], ['provider_credentials', 'credential_unavailable', 0]);
});
test('provider network, timeout, invalid JSON, unknown status and HTTP failures classify safely', async () => {
const cases = [
[async () => { throw new Error('PRIVATE-NETWORK'); }, 502, 'provider_network_error'],
[async (_url, { signal }) => ({
ok: true,
status: 200,
text: () => new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => reject(new Error('PRIVATE-TIMEOUT')), { once: true });
}),
}), 504, 'provider_timeout'],
[async () => ({ ok: true, status: 200, text: async () => '<PRIVATE-HTML>' }),
502, 'invalid_provider_json'],
[async () => ({ ok: true, status: 200,
text: async () => JSON.stringify({ id: 'provider-id', status: 'PRIVATE-STATUS' }) }),
502, 'unrecognized_provider_status'],
[async () => ({ ok: false, status: 429,
text: async () => JSON.stringify({ id: 'provider-id', status: 'ENROUTE' }) }),
429, 'provider_http_error'],
];
for (const [implementation, status, reason] of cases) {
process.env.EPP_PROVIDER_TIMEOUT_MS = status === 504 ? '1' : '1500';
fetchMock.mock.mockImplementation(implementation);
failure(await invoke(await envelope()), status);
assert.equal(event('request_failed').failureReason, reason);
assert.equal(records.at(-1).eventName, 'request_completed');
}
});
test('Sinch successful HTTP without a nonblank message ID fails closed', async () => {
process.env.EPP_PROVIDER_NAME = 'sinch';
process.env.EPP_PROVIDER_AUTH_MODE = 'apiKey';
process.env.SINCH_SERVICE_PLAN_ID = 'plan';
fetchMock.mock.mockImplementation(async () => ({
ok: true,
status: 200,
text: async () => JSON.stringify({ id: ' ', status: 'Delivered' }),
}));
failure(await invoke(await envelope()), 502);
assert.equal(event('request_failed').failureReason, 'missing_provider_message_id');
});
test('Telesign strict integer status and voice pacing keep endpoint outcomes stable', async () => {
process.env.EPP_PROVIDER_NAME = 'telesign';
process.env.EPP_PROVIDER_AUTH_MODE = 'apiKey';
process.env.EPP_PROVIDER_VOICE_ENDPOINT = 'https://verify.telesign.com/epp/send';
for (const [code, status] of [[290, 200], ['290', 502], [true, 502]]) {
fetchMock.mock.mockImplementation(async () => ({
ok: true,
status: 200,
text: async () => JSON.stringify({ reference_id: 'reference-id', status: { code } }),
}));
const result = await invoke(await envelope({ channel: 2 }));
assert.equal(result.status, status);
const sent = JSON.parse(fetchMock.mock.calls.at(-1).arguments[1].body);
assert.equal(sent.message.text,
' PRIVATE-MESSAGE 9, 1, 8, 2, 7, 3.\n PRIVATE-MESSAGE 9, 1, 8, 2, 7, 3.\n');
}
});
test('correlation precedence preserves wire IDs while logs omit unsafe values', async () => {
const headers = {
'x-ms-client-request-id': 'client-request-id',
'x-ms-correlation-id': 'header-correlation-id',
};
for (const [value, expected] of [
['envelope-correlation-id', 'envelope-correlation-id'],
['opaque correlation/value', 'opaque correlation/value'],
[null, 'header-correlation-id'],
[{ private: 'PRIVATE' }, 'header-correlation-id'],
]) {
const result = await invoke(await envelope({ mode: 2, correlationId: value }), headers);
assert.equal(result.jsonBody.correlationId, expected);
assert.equal(records[0]['x-ms-correlation-id'], 'header-correlation-id');
assert.equal(records.at(-1)['x-ms-correlation-id'],
value === 'opaque correlation/value' ? null : expected);
assert.equal(records.at(-1).omittedIdFields.includes('x-ms-correlation-id'),
value === 'opaque correlation/value');
}
const result = await invoke(await envelope({ mode: 2, correlationId: null }));
assert.equal(result.jsonBody.correlationId, records.at(-1).functionRequestId);
});
test('fixed logging excludes bodies, secrets, query strings, descriptions and exceptions', async () => {
process.env.EPP_PROVIDER_SMS_ENDPOINT = 'https://provider.example/api/send?key=PRIVATE-QUERY';
fetchMock.mock.mockImplementation(async () => ({
ok: true,
status: 201,
text: async () => JSON.stringify({
id: 'support-id',
status: 'ENROUTE',
description: 'PRIVATE-DESCRIPTION',
}),
}));
await invoke(await envelope({
tenantId: 'PRIVATE-TENANT',
unknown: { body: 'PRIVATE-BODY' },
}), { authorization: 'PRIVATE-INBOUND' });
assert.equal(event('provider_request_built').providerEndpoint,
'https://provider.example/api/send');
assert.equal(event('provider_request_started').providerEndpoint,
'https://provider.example/api/send');
assert.equal(event('provider_request_started').providerHttpMethod, 'POST');
assert.deepEqual({
providerTenantId: event('provider_credential_resolution_started').providerTenantId,
functionOutboundClientId:
event('provider_credential_resolution_started').functionOutboundClientId,
functionOutboundManagedIdentityClientId:
event('provider_credential_resolution_started').functionOutboundManagedIdentityClientId,
}, {
providerTenantId: process.env.EPP_PROVIDER_TENANT_ID,
functionOutboundClientId: process.env.EPP_OUTBOUND_CLIENT_ID,
functionOutboundManagedIdentityClientId: process.env.EPP_OUTBOUND_MI_CLIENT_ID,
});
assert.equal(event('provider_response_processed').providerMessageId, 'support-id');
assert.equal(event('request_failed'), undefined);
assert.doesNotMatch(JSON.stringify(records), /PRIVATE|918273|15551234567/);
});