-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
swsInterface.js
386 lines (311 loc) · 11 KB
/
swsInterface.js
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
/**
* Created by sv2 on 2/16/17.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var debug = require('debug')('sws:interface');
var promClient = require("prom-client");
var basicAuth = require("basic-auth");
var Cookies = require('cookies');
const uuidv1 = require('uuid/v1');
var swsUtil = require('./swsUtil');
var swsProcessor = require('./swsProcessor');
// API data processor
var processor = null;
// swagger-stats default options
var swsOptions = {
version:'',
swaggerSpec: null,
uriPath: '/swagger-stats',
durationBuckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
requestSizeBuckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
responseSizeBuckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
apdexThreshold: 25,
onResponseFinish: null,
authentication: false,
sessionMaxAge: 900,
onAuthenticate: null
};
var uiMarkup = swsUtil.swsEmbeddedUIMarkup;
var pathUI = swsOptions.uriPath+'/ui';
var pathDist = swsOptions.uriPath+'/dist';
var pathStats = swsOptions.uriPath+'/stats';
var pathMetrics = swsOptions.uriPath+'/metrics';
var pathLogout = swsOptions.uriPath+'/logout';
// Session IDs storage
var sessionIDs = {};
// Store / update session id
function storeSessionID(sid){
var tssec = Date.now() + swsOptions.sessionMaxAge*1000;
sessionIDs[sid] = tssec;
//debug('Session ID updated: %s=%d', sid,tssec);
}
// Remove Session ID
function removeSessionID(sid){
delete sessionIDs[sid];
}
// If authentication is enabled, executed periodically and expires old session IDs
function expireSessionIDs(){
var tssec = Date.now();
var expired = [];
for(var sid in sessionIDs){
if(sessionIDs[sid] < (tssec + 500)){
expired.push(sid);
}
}
for(var i=0;i<expired.length;i++){
delete sessionIDs[expired[i]];
debug('Session ID expired: %s', expired[i]);
}
}
// Request hanlder
function handleRequest(req, res){
try {
processor.processRequest(req,res);
}catch(e){
debug("SWS:processRequest:ERROR: " + e);
return;
}
if(('sws' in req) && ('track' in req.sws) && !req.sws.track ){
// Tracking disabled for this request
return;
}
// Setup handler for finishing reponse
res.on('finish',function(){
handleResponseFinished(this);
});
}
// Response finish hanlder
function handleResponseFinished(res){
try {
processor.processResponse(res);
}catch(e){
debug("SWS:processResponse:ERROR: " + e);
}
}
// Override defaults if options are provided
function processOptions(options){
if(!options) return;
for(var op in swsUtil.supportedOptions){
if(op in options){
swsOptions[op] = options[op];
}
}
// update standard path
pathUI = swsOptions.uriPath+'/ui';
pathDist = swsOptions.uriPath+'/dist';
pathStats = swsOptions.uriPath+'/stats';
pathMetrics = swsOptions.uriPath+'/metrics';
pathLogout = swsOptions.uriPath+'/logout';
if( swsOptions.authentication ){
setInterval(expireSessionIDs,500);
}
}
function processAuth(req,res,useWWWAuth) {
return new Promise( function (resolve, reject) {
if( !swsOptions.authentication ){
return resolve(true);
}
var cookies = new Cookies( req, res );
// Check session cookie
var sessionIdCookie = cookies.get('sws-session-id');
if( (sessionIdCookie !== undefined) && (sessionIdCookie !== null) ){
if( sessionIdCookie in sessionIDs ){
// renew it
//sessionIDs[sessionIdCookie] = Date.now();
storeSessionID(sessionIdCookie);
cookies.set('sws-session-id',sessionIdCookie,{path:swsOptions.uriPath,maxAge:swsOptions.sessionMaxAge*1000});
// Ok
req['sws-auth'] = true;
return resolve(true);
}
}
var authInfo = basicAuth(req);
var authenticated = false;
var msg = 'Authentication required';
if( (authInfo !== undefined) && (authInfo!==null) && ('name' in authInfo) && ('pass' in authInfo)){
if(typeof swsOptions.onAuthenticate === 'function'){
Promise.resolve(swsOptions.onAuthenticate(req, authInfo.name, authInfo.pass)).then(function(onAuthResult) {
if( onAuthResult ){
authenticated = true;
// Session is only for stats requests
if(req.url.startsWith(pathStats)){
// Generate session id
var sessid = uuidv1();
storeSessionID(sessid);
// Set session cookie with expiration in 15 min
cookies.set('sws-session-id',sessid,{path:swsOptions.uriPath,maxAge:swsOptions.sessionMaxAge*1000});
}
req['sws-auth'] = true;
return resolve(true);
}else{
msg = 'Invalid credentials';
res.status(403).end(msg);
return resolve(false);
}
});
}else{
res.status(403).end(msg);
return resolve(false);
}
}else{
res.status(403).end(msg);
return resolve(false);
}
});
/*
if( !swsOptions.authentication ){
return true;
}
var cookies = new Cookies( req, res );
// Check session cookie
var sessionIdCookie = cookies.get('sws-session-id');
if( (sessionIdCookie !== undefined) && (sessionIdCookie !== null) ){
if( sessionIdCookie in sessionIDs ){
// renew it
//sessionIDs[sessionIdCookie] = Date.now();
storeSessionID(sessionIdCookie);
cookies.set('sws-session-id',sessionIdCookie,{path:swsOptions.uriPath,maxAge:swsOptions.sessionMaxAge*1000});
// Ok
req['sws-auth'] = true;
return true;
}
}
var authInfo = basicAuth(req);
var authenticated = false;
var msg = 'Authentication required';
if( (authInfo !== undefined) && (authInfo!==null) && ('name' in authInfo) && ('pass' in authInfo)){
if(typeof swsOptions.onAuthenticate === 'function'){
if( swsOptions.onAuthenticate(req, authInfo.name, authInfo.pass) ){
authenticated = true;
// Session is only for stats requests
if(req.url.startsWith(pathStats)){
// Generate session id
var sessid = uuidv1();
storeSessionID(sessid);
// Set session cookie with expiration in 15 min
cookies.set('sws-session-id',sessid,{path:swsOptions.uriPath,maxAge:swsOptions.sessionMaxAge*1000});
}
}else{
msg = 'Invalid credentials';
}
}
}
if( !authenticated ){
// Reconsidered 401 response. Make it be 403 to prevent browser Basic Auth pop-up in UI
res.status(403).end(msg);
return false;
}
req['sws-auth'] = true;
return true;
*/
}
function processLogout(req,res){
var cookies = new Cookies( req, res );
// Check session cookie
var sessionIdCookie = cookies.get('sws-session-id');
if( (sessionIdCookie !== undefined) && (sessionIdCookie !== null) ){
if( sessionIdCookie in sessionIDs ){
removeSessionID(sessionIdCookie);
cookies.set('sws-session-id'); // deletes cookie
}
}
res.status(200).end('Logged out');
}
// Process /swagger-stats/stats request
// Return statistics according to request parameters
// Query parameters (fields, path, method) defines which stat fields to return
function processGetStats(req,res){
processAuth(req,res).then(function (authResult){
if(!authResult){
return;
}
res.status(200);
if(('sws-auth' in req) && req['sws-auth']){
res.setHeader('x-sws-authenticated','true');
}
res.json( processor.getStats( req.query ) );
});
/*
if(!processAuth(req,res)) {
return;
}
if(('sws-auth' in req) && req['sws-auth']){
res.setHeader('x-sws-authenticated','true');
}
res.status(200).json( processor.getStats( req.query ) );
*/
}
// Process /swagger-stats/metrics request
// Return all metrics for Prometheus
function processGetMetrics(req,res){
processAuth(req,res).then(function (authResult){
if(!authResult){
return;
}
res.status(200).set('Content-Type', 'text/plain');
res.end(promClient.register.metrics());
});
/*
if(!processAuth(req,res)) {
return;
}
res.status(200).set('Content-Type', 'text/plain');
res.end(promClient.register.metrics());
*/
}
module.exports = {
// Initialize swagger-stats and return
// middleware to perform API Data collection
getMiddleware: function (options) {
processOptions(options);
processor = new swsProcessor();
processor.init(swsOptions);
return function trackingMiddleware(req, res, next) {
// Respond to requests handled by swagger-stats
// swagger-stats requests will not be counted in statistics
if(req.url.startsWith(pathStats)) {
return processGetStats(req, res);
}else if(req.url.startsWith(pathMetrics)){
return processGetMetrics(req,res);
}else if(req.url.startsWith(pathLogout)){
processLogout(req,res);
return;
}else if(req.url.startsWith(pathUI) ){
res.status(200).send(uiMarkup);
return;
}else if(req.url.startsWith(pathDist)) {
var fileName = req.url.replace(pathDist+'/','');
var qidx = fileName.indexOf('?');
if(qidx!=-1) fileName = fileName.substring(0,qidx);
var options = {
root: path.join(__dirname,'..','dist'),
dotfiles: 'deny'
// TODO Caching
};
res.sendFile(fileName, options, function (err) {
if (err) {
debug('unable to send file: %s',fileName);
}
});
return;
}
handleRequest(req, res);
return next();
};
},
// TODO Support specifying which stat fields to return
// Returns object with collected statistics
getCoreStats: function() {
return processor.getStats();
},
// Allow get stats as prometheus format
getPromStats: function() {
return promClient.register.metrics();
},
// Expose promClient to allow for custom metrics by application
getPromClient: function () {
return promClient;
}
};