Repository navigation
Expand file tree
/
Copy pathprovider-flow.test.js
More file actions
425 lines (403 loc) · 18.7 KB
/
Copy pathprovider-flow.test.js
File metadata and controls
425 lines (403 loc) · 18.7 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
'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { inspect } = require('node:util');
const fixtures = require('../../tests/fixtures/contract.json');
const { AppConfig, readConfig } = require('../src/functions/config');
const { parseEntraPayload } = require('../src/functions/entraPayload');
const { DeliveryContext, OtpDelivery } = require('../src/functions/delivery');
const { OUTCOME } = require('../src/functions/providerResult');
const { selectProvider } = require('../src/functions/providers');
const {
ProviderTransportError,
isValidProviderUrl,
parseProviderTimeout,
sendProviderRequest,
} = require('../src/functions/providerTransport');
const { createRequestContext } = require('../src/functions/logging');
const delivery = new OtpDelivery({
phoneNumber: '+15551234567',
message: ' Your code is 001234; ref 1234567; alternate 654321.\n',
otp: '001234',
channel: 'sms',
messageId: 'message-id',
correlationId: 'correlation-id',
locale: 'fr-FR',
});
const input = {
channel: 'sms',
endpoint: 'https://provider.example',
delivery,
credential: { mode: 'apiKey', identity: 'id', secret: 'key' },
env: { SINCH_SERVICE_PLAN_ID: 'plan' },
};
const response = (json, providerHttpStatus = 200, validJson = true) => ({
json,
providerHttpStatus,
ok: providerHttpStatus >= 200 && providerHttpStatus < 300,
validJson,
elapsedMs: 1,
});
const envelope = (overrides = {}) => ({
type: 'microsoft.mfa.otpDeliver.v1',
channel: 1,
mode: 1,
encryptedDeliveryContext: 'a.b.c.d.e',
...overrides,
});
test('config and fixed provider lookup have no default or registry', () => {
const config = readConfig({ EPP_PROVIDER_NAME: ' SiNcH ', EPP_PROVIDER_TIMEOUT_MS: ' 0012 ' });
assert.ok(config instanceof AppConfig);
assert.equal(inspect(config), '[AppConfig]');
assert.deepEqual([config.providerName, config.providerTimeoutMs], ['sinch', ' 0012 ']);
assert.equal(selectProvider(' SiNcH ').name, 'sinch');
assert.equal(selectProvider('unknown'), null);
assert.equal(selectProvider(''), null);
});
test('validated Entra payload and delivery models preserve content', () => {
const parsed = parseEntraPayload(envelope({ channel: 'voice', mode: 'evaluation', ttlSeconds: 1 }));
assert.equal(parsed.error, undefined);
assert.equal(parsed.payload.channelName, 'voice');
assert.equal(parsed.payload.isEvaluation, true);
assert.equal(inspect(parsed.payload), '[EntraSendOtpPayload]');
const context = DeliveryContext.fromPayload({
nonce: 'nonce',
phoneNumber: delivery.phoneNumber,
message: delivery.message,
});
assert.ok(context.isComplete);
assert.equal(context.message, delivery.message);
assert.equal(inspect(context), '[DeliveryContext]');
assert.equal(inspect(delivery), '[OtpDelivery]');
for (const value of [null, [], 'text', 1]) assert.equal(DeliveryContext.fromPayload(value), null);
});
test('delivery models preserve optional OTP strings without coercion or message extraction', () => {
for (const fields of [{}, { otp: null }, { otp: '' }, { otp: '001234' }, { otp: '000000' }]) {
const context = DeliveryContext.fromPayload({
nonce: 'nonce',
phoneNumber: delivery.phoneNumber,
message: delivery.message,
...fields,
});
assert.ok(context.isComplete);
assert.equal(context.otp, fields.otp);
assert.equal(context.message, delivery.message);
const request = new OtpDelivery({ ...delivery, otp: context.otp });
assert.equal(request.otp, fields.otp);
assert.equal(inspect(context), '[DeliveryContext]');
assert.equal(inspect(request), '[OtpDelivery]');
}
});
test('delivery models retain arbitrary risk dictionaries without inspecting their fields', () => {
for (const { overrides } of fixtures.riskContexts) {
const context = DeliveryContext.fromPayload({ ...delivery, nonce: 'nonce', ...overrides });
assert.ok(context.isComplete);
assert.deepEqual(context.riskContext, overrides.riskContext);
const request = new OtpDelivery({ ...delivery, riskContext: context.riskContext });
assert.deepEqual(request.riskContext, overrides.riskContext);
assert.equal(inspect(context), '[DeliveryContext]');
assert.equal(inspect(request), '[OtpDelivery]');
}
});
test('payload validation preserves exact shared reasons and order', () => {
for (const fixture of fixtures.badRequests) {
if (fixture.reason === 'invalid JSON body') continue;
const value = fixture.rawBody !== undefined
? JSON.parse(fixture.rawBody)
: envelope(fixture.overrides);
assert.equal(parseEntraPayload(value).error, fixture.reason, fixture.name);
}
});
test('payload enums preserve numeric values and case-insensitive supported names', () => {
for (const [channel, expectedChannel, channelName] of [
[1, 1, 'sms'], ['sms', 1, 'sms'], ['SMS', 1, 'sms'], ['sMs', 1, 'sms'],
[2, 2, 'voice'], ['voice', 2, 'voice'], ['VOICE', 2, 'voice'], ['VoIcE', 2, 'voice'],
]) {
for (const [mode, expectedMode] of [
[1, 1], ['live', 1], ['LIVE', 1], ['LiVe', 1],
[2, 2], ['evaluation', 2], ['EVALUATION', 2], ['EvAlUaTiOn', 2],
]) {
const parsed = parseEntraPayload(envelope({ channel, mode }));
assert.equal(parsed.error, undefined);
assert.deepEqual([
parsed.payload.channel, parsed.payload.mode,
parsed.payload.channelName, parsed.payload.isEvaluation,
], [expectedChannel, expectedMode, channelName, expectedMode === 2],
JSON.stringify({ channel, mode }));
}
}
});
for (const field of ['channel', 'mode']) {
for (const value of [
'constructor', '__proto__', 'CONSTRUCTOR', '__PROTO__',
'toString', 'valueOf', 'hasOwnProperty', 'unsupported',
]) {
test(`payload ${field} rejects unsupported enum name ${value}`, () => {
assert.deepEqual(parseEntraPayload(envelope({ [field]: value })),
{ error: `unsupported ${field}` });
});
}
test(`payload ${field} rejects invalid enum values without coercion`, () => {
for (const value of [
undefined, null, true, false, 0, -1, 3, 1.5, {}, [], ['sms'], ['evaluation'],
'', '1', '2', ' sms', 'sms ', ' voice', 'voice ',
' live', 'live ', ' evaluation', 'evaluation ',
]) {
assert.deepEqual(parseEntraPayload(envelope({ [field]: value })),
{ error: `unsupported ${field}` }, JSON.stringify(value));
}
});
}
test('provider URLs and timeout parsing preserve safety boundaries and cap', () => {
for (const url of ['http://provider.example', 'https://@provider.example', 'https://provider.example#',
'https://provider.example:0', 'https://provider.example:-1', 'https://provider.example:65536',
'https://provider.example\\path', 'https://provider.example/\npath']) {
assert.equal(isValidProviderUrl(url), false, url);
}
assert.equal(isValidProviderUrl('https://provider.example:65535/path?secret=hidden'), true);
for (const value of [null, '0', '-1', '1e3']) assert.equal(parseProviderTimeout(value), 1500);
assert.equal(parseProviderTimeout(' 0012 '), 12);
assert.equal(parseProviderTimeout('999999999999999999999999999'), 2500);
});
test('Soprano owns OAuth request creation and rendered voice splitting', () => {
const soprano = selectProvider('soprano');
assert.deepEqual(soprano.credentialSpec, { mode: 'oauth' });
const sms = soprano.createRequest({
...input,
endpoint: 'https://provider.example/messages',
credential: { mode: 'oauth', accessToken: 'token' },
});
assert.equal(sms.url, 'https://provider.example/messages');
assert.equal(sms.headers.Authorization, 'Bearer token');
assert.deepEqual(JSON.parse(sms.body), {
destination: '15551234567',
messageTypes: ['sms'],
correlationId: 'correlation-id',
shutterMode: false,
text: delivery.message,
});
const voice = soprano.createRequest({
...input,
channel: 'voice',
credential: { mode: 'oauth', accessToken: 'token' },
});
assert.deepEqual(JSON.parse(voice.body).voice.text2voice, {
beforePasswordText: ' Your code is ',
password: '001234',
afterPasswordText: '; ref 1234567; alternate 654321.\n',
language: 'fr-FR',
gender: 1,
loop: 2,
});
assert.throws(() => soprano.createRequest({
...input,
channel: 'voice',
delivery: new OtpDelivery({ ...delivery, message: 'No code.' }),
credential: { mode: 'oauth', accessToken: 'token' },
}), /six-digit passcode/);
});
test('Soprano accepts root or first array object with strict status and flexible IDs', () => {
const soprano = selectProvider('soprano');
for (const [json, id, status, outcome] of [
[{ id: 123, status: 'enroute' }, '123', 'ENROUTE', OUTCOME.CONTINUE],
[[{ id: '', messageId: 456, state: 'accepted' }], '456', 'ACCEPTED', OUTCOME.CONTINUE],
[{ id: {}, messageId: 'fallback', status: '', state: 'ACCEPTED' }, 'fallback', 'UNKNOWN', OUTCOME.FAIL],
[{ status: false, state: 'ACCEPTED' }, null, 'UNKNOWN', OUTCOME.FAIL],
[[], null, 'UNKNOWN', OUTCOME.FAIL],
]) {
const result = soprano.interpretResponse(response(json));
assert.deepEqual([result.providerMessageId, result.providerStatusName, result.outcome],
[id, status, outcome]);
}
});
test('Infobip uses OAuth with the tested SMS and advanced voice contracts on both setup routes', () => {
const infobip = selectProvider('infobip');
const profile = require('../../setup/providers/infobip.json');
assert.equal(infobip.authenticationMode, 'oauth');
assert.deepEqual(infobip.credentialSpec, { mode: 'oauth' });
for (const [region, baseUrl] of [
['global', 'https://api.infobip.com'],
['eu', 'https://api-eu.infobip.com'],
]) {
for (const channel of ['sms', 'voice']) {
const request = infobip.createRequest({
...input,
channel,
endpoint: profile.deployment.routes[region][`${channel}Endpoint`],
credential: { mode: 'oauth', accessToken: 'provider-token' },
env: { EPP_PROVIDER_ACCOUNT_NAME: 'EPP' },
});
assert.equal(request.url, baseUrl + (channel === 'voice' ? '/tts/3/advanced' : '/sms/3/messages'));
assert.equal(request.method, 'POST');
assert.deepEqual(request.headers, {
Authorization: ['Bearer', 'provider-token'].join(' '),
'Content-Type': 'application/json',
Accept: 'application/json',
});
const destinations = [{ to: delivery.phoneNumber, messageId: 'correlation-id' }];
assert.deepEqual(JSON.parse(request.body), {
messages: [channel === 'voice' ? {
from: 'EPP',
destinations,
text: delivery.message,
language: 'fr-FR',
voice: { name: 'Joanna', gender: 'female' },
} : {
sender: 'EPP',
destinations,
content: { text: delivery.message },
}],
});
}
}
});
test('Infobip accepts only strict recognized status strings', () => {
const infobip = selectProvider('infobip');
for (const [status, expected] of [
['ACCEPTED', OUTCOME.CONTINUE],
['pending', OUTCOME.CONTINUE],
['DELIVERED', OUTCOME.CONTINUE],
['REJECTED', OUTCOME.FAIL],
[290, OUTCOME.FAIL],
[true, OUTCOME.FAIL],
[{}, OUTCOME.FAIL],
[null, OUTCOME.FAIL],
]) {
const result = infobip.interpretResponse(response({
messages: [{ messageId: 'provider-id', status: { groupName: status } }],
}));
assert.equal(result.outcome, expected);
assert.equal(result.statusRecognized, typeof status === 'string'
&& ['ACCEPTED', 'PENDING', 'DELIVERED', 'REJECTED'].includes(status.toUpperCase()));
}
});
test('Sinch HTTP success requires a nonblank string ID and may infer Dispatched', () => {
const sinch = selectProvider('sinch');
const request = sinch.createRequest(input);
assert.equal(request.headers.Authorization, 'Bearer key');
assert.equal(JSON.parse(request.body).body, delivery.message);
for (const [json, outcome, reason, status] of [
[{ id: 'batch-id' }, OUTCOME.CONTINUE, null, 'Dispatched'],
[{ callId: 'call-id', status: 'Delivered' }, OUTCOME.CONTINUE, null, 'Delivered'],
[{ id: ' ', status: 'Delivered' }, OUTCOME.FAIL, 'missing_provider_message_id', 'Delivered'],
[{ id: 123, status: 'Delivered' }, OUTCOME.FAIL, 'missing_provider_message_id', 'Delivered'],
[{ id: 'batch-id', status: true }, OUTCOME.FAIL, 'unrecognized_provider_status', null],
]) {
const result = sinch.interpretResponse(response(json));
assert.deepEqual([result.outcome, result.failureReason, result.providerStatusName],
[outcome, reason, status]);
}
});
test('Telesign request validates E.164 and voice pacing remains unchanged', () => {
const telesign = selectProvider('telesign');
const credential = { mode: 'oauth', accessToken: 'provider-token' };
const voice = telesign.createRequest({ ...input, channel: 'voice', credential });
assert.deepEqual(telesign.credentialSpec, { mode: 'oauth' });
assert.equal(JSON.parse(voice.body).message.text,
' Your code is 0, 0, 1, 2, 3, 4; ref 1234567; alternate 6, 5, 4, 3, 2, 1.\n'
+ ' Your code is 0, 0, 1, 2, 3, 4; ref 1234567; alternate 6, 5, 4, 3, 2, 1.\n');
for (const phoneNumber of ['15551234567', '+0123', '+1', '+1234567890123456', '+123\n']) {
assert.throws(() => telesign.createRequest({
...input, credential,
delivery: new OtpDelivery({ ...delivery, phoneNumber }),
}), /invalid recipient/);
}
});
test('Telesign status.code must be an integer number', () => {
const telesign = selectProvider('telesign');
for (const [code, outcome, normalized] of [
[290, OUTCOME.CONTINUE, '290'],
[3001, OUTCOME.CONTINUE, '3001'],
[true, OUTCOME.FAIL, 'UNKNOWN'],
['290', OUTCOME.FAIL, 'UNKNOWN'],
[290.5, OUTCOME.FAIL, 'UNKNOWN'],
[null, OUTCOME.FAIL, 'UNKNOWN'],
]) {
const result = telesign.interpretResponse(response({ status: { code } }));
assert.deepEqual([result.outcome, result.providerStatusCode], [outcome, normalized]);
}
});
test('Telesign sends OAuth bearer credentials for both channels', () => {
const telesign = selectProvider('telesign');
assert.equal(telesign.authenticationMode, 'oauth');
for (const channel of ['sms', 'voice']) {
const request = telesign.createRequest({
...input, channel, credential: { mode: 'oauth', accessToken: 'provider-token' },
});
assert.equal(request.headers.Authorization, 'Bearer provider-token');
assert.equal(request.url, input.endpoint);
const body = JSON.parse(request.body);
assert.deepEqual(body.recipient, { phone_number: delivery.phoneNumber });
assert.deepEqual(body.channels, [{ channel }]);
assert.equal(body.correlation_id, delivery.correlationId);
assert.equal(body.message.language, delivery.locale);
if (channel === 'sms') assert.equal(body.message.text, delivery.message);
}
});
test('providers fail closed with fixed safe classifications', () => {
const cases = [
[selectProvider('infobip'), response(null, 200, false), 'invalid_provider_json', 502],
[selectProvider('soprano'), response({ status: 'PRIVATE' }), 'unrecognized_provider_status', 502],
[selectProvider('infobip'), response({ messages: [{ status: { name: 'REJECTED' } }] }),
'provider_rejected', 502],
[selectProvider('telesign'), response({ status: { code: 290 } }, 429), 'provider_http_error', 429],
[selectProvider('sinch'), response({ id: 'id' }, 500), 'provider_http_error', 502],
];
for (const [provider, providerResponse, reason, httpStatus] of cases) {
const result = provider.interpretResponse(providerResponse);
assert.deepEqual([result.failureReason, result.httpStatus], [reason, httpStatus]);
}
});
test('shared transport uses manual redirects, omits query from logs, and awaits the body', async (t) => {
const records = [];
const context = createRequestContext({
invocationId: 'invocation',
log: (value) => records.push(JSON.parse(value)),
warn: (value) => records.push(JSON.parse(value)),
error: (value) => records.push(JSON.parse(value)),
}, 'request-id', null, null);
let release;
const body = new Promise((resolve) => { release = resolve; });
const fetchMock = t.mock.method(global, 'fetch', async () => ({
ok: true,
status: 200,
text: () => body,
}));
let settled = false;
const pending = sendProviderRequest({
url: 'https://provider.example/api/send?secret=PRIVATE',
method: 'POST',
headers: { Authorization: 'PRIVATE-TOKEN' },
body: '{}',
}, 1500, context).then((value) => { settled = true; return value; });
await new Promise(setImmediate);
assert.equal(settled, false);
release('{"status":"ok"}');
assert.equal((await pending).validJson, true);
assert.equal(fetchMock.mock.calls[0].arguments[1].redirect, 'manual');
assert.equal(records.find((event) => event.eventName === 'provider_request_built').providerEndpoint,
'https://provider.example/api/send');
assert.doesNotMatch(JSON.stringify(records), /PRIVATE/);
});
test('shared transport AbortController covers body reading and classifies timeout', async (t) => {
const context = createRequestContext({
invocationId: 'invocation',
log() {},
warn() {},
error() {},
}, 'request-id', null, null);
const fetchMock = t.mock.method(global, 'fetch', async (_url, { signal }) => ({
ok: true,
status: 200,
text: () => new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => reject(new Error('private')), { once: true });
}),
}));
await assert.rejects(
sendProviderRequest({ url: 'https://provider.example', method: 'POST' }, 1, context),
(error) => error instanceof ProviderTransportError
&& error.httpStatus === 504
&& error.reason === 'provider_timeout',
);
assert.equal(fetchMock.mock.calls[0].arguments[1].signal.aborted, true);
});