All files / lib swsInterface.js

32.91% Statements 52/158
23.53% Branches 16/68
37.5% Functions 9/24
33.12% Lines 52/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x         1x     1x                                                             517x 517x           517x           517x 517x           517x 517x               2x 2x 2x                                                                                                                                                                                     2x 2x     2x 2x     2x 2x                                             1x     1x   1x       1x   1x   519x 519x 519x       519x 2x 517x   517x     517x         517x                         517x                                         517x   517x                                                         1x   1x                                                                                              
/**
 * Created by sv2 on 2/16/17.
 */
 
'use strict';
 
const fs = require('fs');
const path = require('path');
const url = require('url');
const debug = require('debug')('sws:interface');
const promClient = require("prom-client");
const basicAuth = require("basic-auth");
const Cookies = require('cookies');
const uuidv1 = require('uuid/v1');
 
const swsSettings = require('./swssettings');
const swsUtil = require('./swsUtil');
const swsProcessor = require('./swsProcessor');
const swsEgress = require('./swsegress');
const send = require('send');
const qs = require('qs');
 
const swsHapi = require('./swsHapi');
 
// API data processor
//var processor = null;
 
var uiMarkup = swsUtil.swsEmbeddedUIMarkup;
 
// Session IDs storage
var sessionIDs = {};
 
// Store / update session id
function storeSessionID(sid){
    var tssec = Date.now() + swsSettings.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 {
        swsProcessor.processRequest(req,res);
    }catch(e){
        debug("SWS:processRequest:ERROR: " + e);
        return;
    }
 
    Iif(('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 {
        swsProcessor.processResponse(res);
    }catch(e){
        debug("SWS:processResponse:ERROR: " + e);
    }
}
 
function processAuth(req,res,useWWWAuth) {
 
    return new Promise( function (resolve, reject) {
        Eif( !swsSettings.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:swsSettings.uriPath,maxAge:swsSettings.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 swsSettings.onAuthenticate === 'function'){
 
                Promise.resolve(swsSettings.onAuthenticate(req, authInfo.name, authInfo.pass)).then(function(onAuthResult) {
                    if( onAuthResult ){
 
                        authenticated = true;
 
                        // Session is only for stats requests
                        if(req.url.startsWith(swsSettings.pathStats)){
                            // Generate session id
                            var sessid = uuidv1();
                            storeSessionID(sessid);
                            // Set session cookie with expiration in 15 min
                            cookies.set('sws-session-id',sessid,{path:swsSettings.uriPath,maxAge:swsSettings.sessionMaxAge*1000});
                        }
 
                        req['sws-auth'] = true;
                        return resolve(true);
 
                    }else{
                        msg = 'Invalid credentials';
                        res.statusCode = 403;
                        res.end(msg);
                        return resolve(false);
                    }
                });
 
            }else{
                res.statusCode = 403;
                res.end(msg);
                return resolve(false);
            }
        }else{
            res.statusCode = 403;
            res.end(msg);
            return resolve(false);
        }
 
    });
 
}
 
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.statusCode = 200;
    res.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){
        Iif(!authResult){
            return;
        }
        res.statusCode = 200;
        Iif(('sws-auth' in req) && req['sws-auth']){
            res.setHeader('x-sws-authenticated','true');
        }
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(swsProcessor.getStats(req.sws.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.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end(promClient.register.metrics());
    });
}
 
// Express Middleware
function expressMiddleware(options) {
 
    // Init settings
    swsSettings.init(options);
 
    // Init probes
    swsEgress.init();
 
    Iif( swsSettings.authentication ){
        setInterval(expireSessionIDs,500);
    }
 
    swsProcessor.init();
 
    return function trackingMiddleware(req, res, next) {
 
        res._swsReq = req;
        req.sws = {};
        req.sws.query = qs.parse(url.parse(req.url).query);
 
        // Respond to requests handled by swagger-stats
        // swagger-stats requests will not be counted in statistics
        if(req.url.startsWith(swsSettings.pathStats)) {
            return processGetStats(req, res);
        }else Iif(req.url.startsWith(swsSettings.pathMetrics)){
            return processGetMetrics(req,res);
        }else Iif(req.url.startsWith(swsSettings.pathLogout)){
            processLogout(req,res);
            return;
        }else Iif(req.url.startsWith(swsSettings.pathUI) ){
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html');
            res.end(uiMarkup);
            return;
        }else Iif(req.url.startsWith(swsSettings.pathDist)) {
            var fileName = req.url.replace(swsSettings.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.setHeader('Content-Type', send.mime.lookup(path.basename(fileName)));
            send(req, fileName, options).pipe(res);
            return;
        } else Iif(req.url.startsWith(swsSettings.pathUX)) {
            let filename = null;
            if(req.url === swsSettings.pathUX){
                fileName = 'index.html';
            }else {
                fileName = req.url.replace(swsSettings.pathUX+'/', '');
                let qidx = fileName.indexOf('?');
                if ( qidx != -1 ) {
                    fileName = fileName.substring(0, qidx);
                }
            }
            let options = {
                root: path.join(__dirname,'..','ux'),
                dotfiles: 'deny'
                // TODO Caching
            };
            res.setHeader('Content-Type', send.mime.lookup(path.basename(fileName)));
            send(req, fileName, options).pipe(res);
            return;
        }
 
        handleRequest(req, res);
 
        return next();
    };
}
 
function fastifyPlugin (fastify, opts, done) {
    fastify.decorate('utility', () => {})
    fastify.use(expressMiddleware(opts));
    /*
    fastify.addHook('onRequest', (request, reply, done) => {
        const self = this;
        console.log(`Got onRequest`);
        done()
    });
     */
    fastify.addHook('onResponse', (request, reply, done) => {
        // pre-process request, response, context before response handled by sws
        // Capture Fastify-specific data
        request.raw.sws = request.raw.sws || {};
        // TODO Headers
        //let h = Object.getOwnPropertySymbols(reply);
        //let hh = reply[headersSymbol];
        // Set route_path as reply.context.config.url
        if(('context' in reply) && ('config' in reply.context) && ('url' in reply.context.config)){
            request.raw.sws.route_path = reply.context.config.url;
        }
        done()
    });
    done();
}
fastifyPlugin[Symbol.for('skip-override')] = true;
 
module.exports = {
 
    // Returns Hapi plugin
    getHapiPlugin: {
        name: 'swagger-stats',
        version: '0.97.9',
        register: async function (server, options) {
 
            // Init settings
            swsSettings.init(options);
 
            // Init probes TODO Reconsider
            swsEgress.init();
 
            swsProcessor.init();
 
            return swsHapi.register(server, options);
        }
    },
 
    getFastifyPlugin: fastifyPlugin,
 
    // Initialize swagger-stats and return
    // middleware to perform API Data collection
    getMiddleware: expressMiddleware,
 
    // TODO Support specifying which stat fields to return
    // Returns object with collected statistics
    getCoreStats: function() {
        return swsProcessor.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;
    },
 
    // Stop the processor so that Node.js can exit
    stop: function () {
        return swsProcessor.stop();
    }
};