-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathrequester.js
More file actions
571 lines (522 loc) · 18.1 KB
/
Copy pathrequester.js
File metadata and controls
571 lines (522 loc) · 18.1 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
/*
* Copyright (c) 2015-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
*/
'use strict';
const createAuthInitializer = require('./www-authenticate-patched/www-authenticate');
const Kerberos = require('./optional.js')
.libraryProperty('kerberos', 'Kerberos');
const Multipart = require('multipart-stream');
const through2 = require('through2');
const mlutil = require('./mlutil.js');
const responder = require('./responder.js');
let kerberos = null;
const https = require('https');
const formData = require('form-data');
function createAuthenticator(client, user, password, challenge) {
const authenticator = createAuthInitializer.call(null, user, password)(challenge);
if (!client.authenticator) {
client.authenticator = {};
}
client.authenticator[user] = authenticator;
return authenticator;
}
function createAuthenticatorKerberos(client, credentials) {
const authenticatorKerberos = {
'credentials': credentials
};
client.authenticatorKerberos = authenticatorKerberos;
return authenticatorKerberos;
}
function getAuthenticator(client, user) {
if (!client.authenticator) {
return null;
}
return client.authenticator[user];
}
function getAuthenticatorKerberos(client) {
if (!client.authenticatorKerberos) {
return null;
}
return client.authenticatorKerberos;
}
function getAccessToken(operation){
const postData = `${encodeURI('grant_type')}=${encodeURI('apikey')}&${encodeURI('key')}=${encodeURI(operation.client.connectionParams.apiKey)}`;
const path = operation.client.connectionParams.accessTokenDuration?'/token?duration='+encodeURIComponent(operation.client.connectionParams.accessTokenDuration):'/token';
function handleTokenError(error, contextMessage) {
if (!operation.lockAccessToken) {
return;
}
operation.lockAccessToken = false;
const baseMessage = (contextMessage == null) ? 'Failed to obtain access token' : contextMessage;
const errorMessage = (error && error.message) ? `${baseMessage}: ${error.message}` : baseMessage;
operation.errorListener(new Error(errorMessage));
}
const options = {
hostname: operation.client.connectionParams.host,
port: 443,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const req = https.request(options, (res) => {
let responseBody = '';
res.on('data', (d) => {
responseBody += d.toString();
});
res.on('end', () => {
if(res.statusCode === 400){
handleTokenError(null, 'Token endpoint returned 400: ' + responseBody);
return;
}
try {
const responseValue = JSON.parse(responseBody);
if (!responseValue.access_token || !responseValue['.expires']) {
throw new Error('missing required token fields');
}
const expiration = new Date(responseValue['.expires']);
if (Number.isNaN(expiration.getTime())) {
throw new Error('invalid .expires value');
}
operation.accessToken = responseValue.access_token;
operation.expiration = expiration;
operation.lockAccessToken = false;
} catch (error) {
handleTokenError(error, 'Invalid token endpoint response');
return;
}
authenticatedRequest(operation);
});
res.on('error', (e) => {
handleTokenError(e, 'Failed to obtain access token');
});
});
req.on('error', (e) => {
handleTokenError(e, 'Failed to obtain access token');
});
req.write(postData);
req.end();
}
function startRequest(operation) {
const options = operation.options;
const operationErrorListener = responder.operationErrorListener;
operation.errorListener = mlutil.callbackOn(operation, operationErrorListener);
let headers = options.headers;
if (headers == null) {
headers = {};
options.headers = headers;
}
headers['X-Error-Accept'] = 'application/json';
if (!options.disableTelemetryHeader) {
headers['ML-Agent-ID'] = 'nodejs'; // Telemetry header
}
if(options.enableGzippedResponses) {
headers['Accept-Encoding'] = 'gzip';
}
let started = null;
let operationResultPromise = null;
switch(operation.requestType) {
case 'empty':
break;
case 'single':
operation.inputSender = singleRequester;
break;
case 'multipart':
operation.inputSender = multipartRequester;
break;
case 'chunked':
operationResultPromise = responder.operationResultPromise;
started = through2();
started.result = mlutil.callbackOn(operation, operationResultPromise);
operation.requestWriter = started;
operation.inputSender = chunkedRequester;
break;
case 'chunkedMultipart':
operationResultPromise = responder.operationResultPromise;
started = through2();
started.result = mlutil.callbackOn(operation, operationResultPromise);
operation.requestWriter = started;
operation.inputSender = chunkedMultipartRequester;
break;
default:
throw new Error('unknown request type '+operation.requestType);
}
const authType = options.authType.toUpperCase();
let needsAuthenticator = (
authType === 'DIGEST' ||
authType === 'KERBEROS'
);
if (needsAuthenticator) {
let authenticator = null;
switch(authType) {
case 'DIGEST':
authenticator = getAuthenticator(operation.client, options.user);
break;
case 'KERBEROS':
authenticator = getAuthenticatorKerberos(operation.client);
break;
default:
throw new Error('initialization for unknown authenticator type '+authType);
}
if (authenticator !== null) {
needsAuthenticator = false;
operation.authenticator = authenticator;
}
}
if (needsAuthenticator) {
switch(authType) {
case 'DIGEST':
challengeRequest(operation);
break;
case 'KERBEROS':
credentialsRequest(operation);
break;
default:
throw new Error('request for unknown authenticator type '+authType);
}
} else {
if(operation.client.connectionParams.apiKey && !operation.accessToken){
if(!operation.lockAccessToken){
operation.lockAccessToken = true;
getAccessToken(operation);
} else {
authenticatedRequest(operation);
}
} else {
authenticatedRequest(operation);
}
}
if (started === null) {
const ResponseSelector = responder.ResponseSelector;
started = new ResponseSelector(operation);
}
return started;
}
function challengeRequest(operation) {
const isRead = (operation.inputSender === null);
const options = operation.options;
const challengeOpts = isRead ? options : {
method: 'HEAD',
path: '/v1/ping'
};
if (!isRead) {
Object.keys(options).forEach(function optionKeyCopier(key) {
if (challengeOpts[key] === void 0) {
const value = options[key];
if (value != null) {
challengeOpts[key] = value;
}
}
});
}
operation.logger.debug('challenge request for %s', challengeOpts.path);
var request1 = operation.client.request(challengeOpts, function challengeResponder(response1) {
const statusCode1 = response1.statusCode;
const successStatus = (statusCode1 < 400);
const challenge = response1.headers['www-authenticate'];
const hasChallenge = (challenge != null);
operation.logger.debug('response with status %d and %s challenge for %s',
statusCode1, hasChallenge, challengeOpts.path);
if ((statusCode1 === 401 && hasChallenge) || (successStatus && !isRead)) {
try{
operation.authenticator = (hasChallenge) ? createAuthenticator(
operation.client, options.user, options.password, challenge
) : null;
} catch(error){
request1.emit('error', new Error('Authentication failed.'));
}
authenticatedRequest(operation);
// should never happen
} else if (successStatus && isRead) {
const responseDispatcher = responder.responseDispatcher;
responseDispatcher.call(operation, response1);
} else if (isRetry(response1)) {
retryRequest(operation, response1, challengeRequest);
} else {
operation.errorListener('challenge request failed for '+options.path);
}
});
request1.on('error', operation.errorListener);
request1.end();
}
function credentialsRequest(operation) {
kerberos = new Kerberos();
const uri = 'HTTP@'+operation.options.host;
kerberos.authGSSClientInit(uri, 0, function(err, ctx) {
if (err) {
operation.errorListener('kerberos initialization failed at '+uri);
}
operation.logger.debug('kerberos initialized at '+uri);
kerberos.authGSSClientStep(ctx, '', function (err) {
if (err) {
operation.errorListener('kerberos credentials failed');
}
operation.logger.debug('kerberos credentials retrieved');
operation.authenticator = createAuthenticatorKerberos(
operation.client,
ctx.response
);
authenticatedRequest(operation);
kerberos.authGSSClientClean(ctx, function(err) {
if (err) {
operation.errorListener('kerberos client clean failed');
}
});
});
});
}
function authenticatedRequest(operation) {
const isRead = (operation.inputSender === null);
const options = operation.options;
operation.logger.debug('authenticated request for %s', options.path);
const authenticator = operation.authenticator;
const responseDispatcher = operation.isReplayable ? retryDispatcher : responder.responseDispatcher;
const request = operation.client.request(
options, mlutil.callbackOn(operation, responseDispatcher)
);
const authType = options.authType.toUpperCase();
if (authenticator != null) {
switch(authType) {
case 'DIGEST':
operation.logger.debug('digest authentication');
request.setHeader(
'authorization',
authenticator.authorize(options.method, options.path)
);
break;
case 'KERBEROS':
operation.logger.debug('kerberos authentication');
request.setHeader(
'authorization',
'Negotiate '+authenticator.credentials
);
break;
default:
operation.errorListener('unknown authentication type '+authType);
}
} else {
switch(authType) {
case 'SAML':
operation.logger.debug('saml authentication');
request.setHeader(
'authorization',
options.auth
);
break;
case 'CLOUD':
operation.logger.debug('cloud authentication');
request.setHeader(
'authorization',
'bearer ' + operation.accessToken
);
break;
case 'OAUTH':
request.setHeader(
'Authorization',
'Bearer ' +options.oauthToken
);
}
}
request.on('error', operation.errorListener);
if (isRead) {
request.end();
} else {
operation.inputSender(request);
}
}
function retryDispatcher(response) {
/*jshint validthis:true */
const operation = this;
if (isRetry(response)) {
retryRequest(operation, response, authenticatedRequest);
} else {
responder.responseDispatcher.call(operation, response);
}
}
function isRetry(response) {
const retryStatus = [502, 503, 504];
return retryStatus.indexOf(response.statusCode) > -1;
}
function retryRequest(operation, response, requestSender) {
const retryAfterRaw = response.headers['retry-after'];
const retryAfter = (retryAfterRaw === void 0 || retryAfterRaw === null) ? -1 :
Number.parseInt(retryAfterRaw, 10);
operation.retryAttempt++;
const retryTimeout = 120000; // 2 minutes
const retryMin = 50; // milliseconds
const retryExpMax = 6; // maximum exponential range
const randomized = Math.floor(Math.random() * (retryMin + 1)) + retryMin; // 50 to 100
const nextRetry = Math.max(
retryAfter,
// 1 = 100 to 200, 2 = 200 to 400, 3 = 400 to 800, 4 = 800 to 1600, 5 = 1600 to 3200, N = 3200 to 6400
randomized * Math.pow(2, Math.min(operation.retryAttempt, retryExpMax))
);
operation.retryDuration += nextRetry;
if (operation.retryDuration > retryTimeout) {
operation.errorListener(`retry failed for ${response.statusCode} status after ${
operation.retryAttempt} attempts over ${operation.retryDuration / 1000} seconds`);
} else {
operation.logger.debug('retry status = %d next = %d attempt = %d duration = %d',
response.statusCode, nextRetry, operation.retryAttempt, operation.retryDuration);
setTimeout(requestSender, nextRetry, operation);
}
}
function singleRequester(request) {
/*jshint validthis:true */
const operation = this;
const requestSource = mlutil.marshal(operation.requestBody, operation);
if (requestSource == null) {
request.end();
} else if (typeof requestSource === 'string' || requestSource instanceof String) {
request.write(requestSource, 'utf8');
request.end();
// readable stream might not inherit from ReadableStream
} else if (typeof requestSource._read === 'function') {
requestSource.pipe(request);
} else {
request.write(requestSource);
request.end();
}
}
function multipartRequester(request) {
/*jshint validthis:true */
const operation = this;
const operationBoundary = operation.multipartBoundary;
const multipartStream = new Multipart((operationBoundary == null) ?
mlutil.multipartBoundary : operationBoundary);
const requestPartsProvider = operation.requestPartsProvider;
if(operation.bindingParam) {
const form = new formData();
const bindingParam = operation.bindingParam;
const query = bindingParam.query;
const key = bindingParam.key;
const binding = bindingParam[key];
const attachments = bindingParam.attachments;
const metadata = bindingParam.metadata;
form.setBoundary(mlutil.multipartBoundary);
form.append('query', query, {contentType: 'application/json', filename: 'fromParam-AST.js'});
form.append(key, JSON.stringify(binding), {contentType: 'application/json', filename: 'data.json'});
if(attachments && attachments instanceof Array && attachments.length) {
for (let i = 0; i < attachments.length; i++) {
const attachment = attachments[i];
const keys = Object.keys(attachment);
for(let j = 0; j < keys.length; j++) {
const key = keys[j];
if(typeof attachment[key] === 'object') {
form.append('doc', JSON.stringify(attachment[key]), {filename: key});
} else {
form.append('doc', attachment[key], {filename: key});
}
}
}
} else {
if(typeof attachments === 'object') {
const keys = Object.keys(attachments);
for(let j = 0; j < keys.length; j++) {
const key = keys[j];
if(typeof attachments[key] === 'object') {
form.append('doc', JSON.stringify(attachments[key]), {filename: key});
} else {
form.append('doc', attachments[key], {filename: key});
}
}
}
}
if(metadata) {
form.append('metadata', JSON.stringify(metadata), {contentType: 'application/json', filename: 'metadata.json'});
}
multipartStream.add({
headers: {
'Content-Type': 'multipart/form-data; boundary=' + mlutil.multipartBoundary,
Accept: 'application/json',
},
body: form,
});
} else if (typeof requestPartsProvider === 'function') {
requestPartsProvider.call(operation, multipartStream);
} else {
const parts = operation.requestPartList;
if (Array.isArray(parts)) {
const partsLen = parts.length;
operation.logger.debug('writing %s parts', partsLen);
for (let i=0; i < partsLen; i++) {
const part = parts[i];
const headers = part.headers;
const content = part.content;
if ((headers != null) &&
(content != null)) {
operation.logger.debug('starting part %s', i);
multipartStream.addPart({
headers: headers,
body: content
});
operation.logger.debug('finished part %s', i);
} else {
operation.logger.debug('nothing to write for part %d', i);
}
}
} else {
operation.logger.debug('no part list to write');
}
}
multipartStream.pipe(request);
}
function chunkedRequester(request) {
/*jshint validthis:true */
const operation = this;
const requestWriter = operation.requestWriter;
if (requestWriter === null || requestWriter === undefined) {
operation.errorListener('no request writer for streaming request');
request.end();
}
requestWriter.pipe(request);
}
function chunkedMultipartRequester(request) {
/*jshint validthis:true */
const operation = this;
const requestWriter = operation.requestWriter;
const requestDocument = operation.requestDocument;
if (requestWriter == null) {
operation.errorListener('no request writer for streaming request');
request.end();
} else if (requestDocument == null) {
operation.errorListener('no request document for streaming request');
request.end();
} else {
const operationBoundary = operation.multipartBoundary;
const multipartStream = new Multipart((operationBoundary == null) ?
mlutil.multipartBoundary : operationBoundary);
const partLast = requestDocument.length - 1;
for (let i=0; i <= partLast; i++) {
const part = requestDocument[i];
const headers = part.headers;
if (i < partLast) {
const content = part.content;
if ((headers != null) &&
(content != null)) {
multipartStream.addPart({
headers: headers,
body: mlutil.marshal(content, operation)
});
} else {
operation.logger.debug('could not write metadata part');
}
} else {
if (headers != null) {
multipartStream.addPart({
headers: headers,
body: requestWriter
});
} else {
operation.logger.debug('could not write content part');
}
}
}
multipartStream.pipe(request);
}
}
module.exports = {
startRequest: startRequest,
getAccessToken: getAccessToken
};