16. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 10/4/2017 8:04:33 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

16.1 Files compared

# Location File Last Modified
1 rdk.zip\rdk\product\production\rdk\src\core\factory-components rdk-framework-middleware.js Mon Aug 28 19:41:48 2017 UTC
2 rdk.zip\rdk\product\production\rdk\src\core\factory-components rdk-framework-middleware.js Tue Oct 3 17:14:50 2017 UTC

16.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 868
Changed 1 2
Inserted 0 0
Removed 0 0

16.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

16.4 Active regular expressions

No regular expressions were active.

16.5 Comparison detail

  1   'use stric t';
  2  
  3   var _ = re quire('lod ash');
  4   var bodyPa rser = req uire('body -parser');
  5   var helmet  = require ('helmet') ;
  6   var morgan  = require ('morgan') ;
  7   var onFini shed = req uire('on-f inished');
  8   var onHead ers = requ ire('on-he aders');
  9   var respon seTime = r equire('re sponse-tim e');
  10   var sessio n = requir e('express -session') ;
  11   var uuid =  require(' node-uuid' );
  12   var method Override =  require(' method-ove rride');
  13  
  14   var rdk =  require('. ./rdk');
  15   var rdkJwt  = require ('./rdk-jw t');
  16   var JDSSto re = requi re('../../ utils/conn ect-jds')( session);
  17  
  18   var httpUt il = rdk.u tils.http;
  19   var RdkErr or = rdk.u tils.RdkEr ror;
  20  
  21   module.exp orts.setup AppMiddlew are = setu pAppMiddle ware;
  22  
  23   // Private  exports
  24   module.exp orts._addR dkSendToRe sponse = a ddRdkSendT oResponse;
  25   module.exp orts._extr actSession Id = extra ctSessionI d;
  26   module.exp orts._addL oggerToReq uest = add LoggerToRe quest;
  27   module.exp orts._addR equestedSe ssionId =  addRequest edSessionI d;
  28   module.exp orts._addR equestId =  addReques tId;
  29   module.exp orts._enab leMethodOv erride = e nableMetho dOverride;
  30   module.exp orts._ensu reQueryMat chesBody =  ensureQue ryMatchesB ody;
  31  
  32   function s etupAppMid dleware(ap p) {
  33       setupT rustProxy( app);
  34       setupC ors(app);
  35       enable Helmet(app );
  36       addApp ToRequest( app);
  37       addRdk SendToResp onse(app);
  38       addInt erceptorRe questObjec t(app);
  39       addReq uestId(app );
  40       addReq uestedSess ionId(app) ;
  41       enable MethodOver ride(app);
  42       addLog gerToReque st(app);
  43       setApp Timeout(ap p);
  44       enable Morgan(app );
  45       enable Session(ap p);
  46       enable ResponseTi meHeader(a pp);
  47       enable BodyParser (app);
  48       initia lizeHttpWr apper(app) ;
  49       ensure QueryMatch esBody(app );
  50       rdkJwt .enableJwt (app);
  51   }
  52  
  53   function s etupTrustP roxy(app)  {
  54       app.us e(function (req, res,  next) {
  55             var client IsBalancer  = (req.he aders['x-f orwarded-h ost'] ===  ' IP          ');
  56           if  (app.conf ig.environ ment === ' developmen t') {
  57                app[clie ntIsBalanc er ? 'enab le' : 'dis able']('tr ust proxy' );
  58           }  else {
  59                app.enab le('trust  proxy');
  60           }
  61           ap p.logger.i nfo('trust  proxy [en abled=%s][ %s]', app. enabled('t rust proxy '), req.ip s);
  62           ne xt();
  63       });
  64   }
  65  
  66   function s etupCors(a pp) {
  67       //CORS  not setup  on reload  of config uration si nce CORS i s only use d for deve lopment.
  68       var co rsEnabled  = _.get(ap p, 'config .corsEnabl ed');
  69       var is Developmen tEnvironme nt = _.get (app, 'con fig.enviro nment') == = 'develop ment';
  70       if (!c orsEnabled  || !isDev elopmentEn vironment)  {
  71           re turn;
  72       }
  73       var co rs = requi re('cors') ;
  74       app.us e(cors({
  75           cr edentials:  true,
  76           //  FUTURE-TO DO: allow  configurab le whiteli st of orig ins
  77           or igin: func tion(origi n, callbac k) {
  78                callback (null, tru e);
  79           }
  80       }));
  81   }
  82  
  83   function e nableHelme t(app) {
  84       app.us e(helmet.h idePowered By());
  85       app.us e(helmet.n oCache());
  86       app.us e(helmet.h sts());
  87       app.us e(helmet.i eNoOpen()) ;
  88       app.us e(helmet.n oCache());
  89       app.us e(helmet.n oSniff());
  90       app.us e(helmet.f rameguard( ));
  91       app.us e(helmet.x ssFilter() );
  92   }
  93  
  94   function a ddAppToReq uest(app)  {
  95       // Exp ress.js se ts req.app , but not  as an own  property
  96       // Som e resource s clone re q but only  with own  properties
  97       app.us e(function (req, res,  next) {
  98           re q.app = ap p;
  99           ne xt();
  100       });
  101   }
  102  
  103   function a ddRdkSendT oResponse( app) {
  104       app.us e(function (req, res,  next) {
  105           re s.rdkSend  = function (body) {
  106                var erro r = getRdk ErrorFromB ody(body,  req.logger );
  107  
  108                if (!_.i sEmpty(err or)) {
  109                    body  = error;
  110                }
  111  
  112                if (res. statusCode  === 204)  {
  113                    body  = undefin ed;
  114                } else {
  115                    if ( body === n ull || bod y === unde fined) {
  116                         body = {};
  117                    } el se if (_.i sObject(bo dy) || thi s.get('Con tent-Type' ) === 'app lication/j son') {
  118                         if (_.isSt ring(body) ) {
  119                             try {
  120                                 bo dy = JSON. parse(body );
  121                             } catc h (e) {
  122                                 bo dy = {
  123                                      message:  body
  124                                 };
  125                             }
  126                         }
  127                         if ((!_.ha s(body, 'd ata') || ! _.isObject (body.data )) &&
  128                             !_.has (body, 'me ssage') &&
  129                             (_.isA rray(body)  || !_.isE mpty(body) )) {
  130                             body =  {
  131                                 da ta: body
  132                             };
  133                         }
  134                    } el se {
  135                         body = {
  136                             messag e: String( body)
  137                         };
  138                    }
  139                    if ( res.status Code) {
  140                         body.statu s = res.st atusCode;
  141                    } el se {
  142                         body.statu s = 200;
  143                    }
  144                }
  145  
  146                req._rdk SendUsed =  true;
  147                if (body ) {
  148                    res. data = bod y.data;
  149                }
  150                return t his.send(b ody);
  151           };
  152           ne xt();
  153       });
  154   }
  155  
  156   function g etRdkError FromBody(b ody, logge r) {
  157       var it em = {};
  158       if (bo dy instanc eof RdkErr or) {
  159           if  (!body.lo gged) {
  160                body.log (logger);
  161           }
  162           it em = body. sanitize() ;
  163       }
  164       return  item;
  165   }
  166  
  167   function a ddIntercep torRequest Object(app ) {
  168       app.us e(function (req, res,  next) {
  169           re q.intercep torResults  = {};
  170           ne xt();
  171       });
  172   }
  173  
  174   function a ddRequestI d(app) {
  175       app.us e(function (req, res,  next) {
  176           Ob ject.defin eProperty( req, 'id',  {
  177                value: u uid.v4(),
  178                writable : false
  179           }) ;
  180           re s.set('X-R equest-ID' , req.id);
  181           ne xt();
  182       });
  183   }
  184  
  185   function a ddRequeste dSessionId (app) {
  186       app.us e(function (req, res,  next) {
  187           va r requeste dSessionId  = extract SessionId( req);
  188           Ob ject.defin eProperty( req, '_req uestedSess ionId', {
  189                value: r equestedSe ssionId,
  190                writable : false
  191           }) ;
  192           ne xt();
  193       });
  194   }
  195  
  196   function a ddLoggerTo Request(ap p) {
  197       app.us e(function (req, res,  next) {
  198           va r idLogger  = app.log ger.child( {
  199                requestI d: req.id,
  200                sid: req ._requeste dSessionId
  201           }) ;
  202           if  (req.url  === req.ap p.config.r ootPath +  '/version' ) { // Hac k. TODO: f ix up the  version re source and  move it t o the rdk  core
  203                idLogger  = idLogge r.child({v ersionReso urce: true });
  204           }
  205           if  (req.meth od === req .originalM ethod) {
  206                idLogger .info('New  Request:  %s %s', re q.method,  req.origin alUrl || r eq.url);
  207           }  else {
  208                idLogger .info('New  Request:  (via %s) % s %s', req .originalM ethod, req .method, r eq.origina lUrl || re q.url);
  209           }
  210           id Logger.deb ug({
  211                remote:  req.ip ||  req.connec tion.remot eAddress
  212           }) ;
  213           re q.logger =  idLogger;
  214           ne xt();
  215       });
  216   }
  217  
  218   function e xtractSess ionId(req)  {
  219       var co okieHeader  = req.get ('cookie') ;
  220       var rd kSessionRe gex = new  RegExp(_.e scapeRegEx p(getCooki eName(req. app.config )) + '=(.* ?)(?:;|$)' );
  221       var ma tch = rdkS essionRege x.exec(coo kieHeader) ;
  222       if (ma tch === nu ll) {
  223           re turn null;
  224       }
  225       var ra wCookie =  match[1];
  226       var de codedCooki e;
  227       try {
  228           de codedCooki e = decode URICompone nt(rawCook ie);
  229       } catc h (ex) {
  230           de codedCooki e = rawCoo kie;
  231       }
  232       var is SignedCook ie = decod edCookie.s ubstr(0, 2 ) === 's:' ;
  233       if (is SignedCook ie) {
  234           de codedCooki e = stripC ookieSigna ture(decod edCookie);
  235       }
  236       return  decodedCo okie;
  237   }
  238  
  239   function s tripCookie Signature( signedCook ie) {
  240       return  signedCoo kie.slice( 2, signedC ookie.last IndexOf('. '));
  241   }
  242  
  243   function s etAppTimeo ut(app) {
  244       app.us e(function (req, res,  next) {
  245           va r timeoutM illis = Nu mber(req.a pp.config. responseTi meoutMilli s || 30000 0);
  246           re s.setTimeo ut(timeout Millis);
  247           re q.logger.i nfo('respo nse timeou t=%s ms',  timeoutMil lis);
  248           ne xt();
  249       });
  250   }
  251  
  252   function e nableMorga n(app) {
  253       app.us e(morganBu nyanLogger );
  254   }
  255  
  256   function m organBunya nLogger(re q, res, ne xt) {
  257       var lo gger = req .logger ||  req.app.l ogger;
  258       var mo rganFormat  = req.app .config.mo rganFormat  || 'bunya n';
  259       if (mo rganFormat  === 'buny an') {
  260           //  Make buny an a speci al case in stead of m organ.form at('bunyan ') to avoi d extra JS ON.parse
  261           re q._remoteA ddress = g etIp(req);
  262           re cordStartT ime.call(r eq);
  263           on Headers(re s, recordS tartTime);
  264           on Finished(r es, functi on() {
  265                var resp onseInfo =  {
  266                    remo teAddress:  getIp(req ),
  267                    remo teUser: _. get(req, ' session.us er.accessC ode'),
  268                    meth od: req.me thod,
  269                    orig inalMethod : req.orig inalMethod ,
  270                    path : req.orig inalUrl,
  271                    http Version: r eq.httpVer sion,
  272                    stat us: res.st atusCode,
  273                    cont entLength:  res.getHe ader('cont ent-length '),
  274                    refe rer: req.g et('refere r'),
  275                    user Agent: req .get('user -agent')
  276                };
  277                if (req. _startAt & & res._sta rtAt) {
  278                    resp onseInfo.r esponseTim eMs = (
  279                         (res._star tAt[0] - r eq._startA t[0]) * 1e 3 + // sec onds
  280                         (res._star tAt[1] - r eq._startA t[1]) * 1e -6 // nano seconds
  281                    );
  282                    logg er.info({
  283                         sid: _.get (req, 'ses sion.id',  req._reque stedSessio nId),
  284                         responseIn fo: respon seInfo
  285                    });
  286                }
  287           }) ;
  288           re turn next( );
  289       } else  {
  290           va r morganTo Bunyan = m organ(morg anFormat,  {
  291                stream:  {
  292                    writ e: functio n(string)  {
  293                         logger.inf o(string);
  294                    }
  295                }
  296           }) ;
  297           re turn morga nToBunyan( req, res,  next);
  298       }
  299  
  300       functi on getIp(r eq) {
  301           re turn req.i p || req._ remoteAddr ess || (re q.connecti on && req. connection .remoteAdd ress);
  302       }
  303  
  304       functi on recordS tartTime()  {
  305           th is._startA t = proces s.hrtime() ; // jshin t ignore:l ine
  306           th is._startT ime = new  Date(); //  jshint ig nore:line
  307       }
  308   }
  309  
  310   function g etCookieNa me(config)  {
  311       var pr efix = _.r esult(conf ig, 'cooki ePrefix',  null);
  312       var co okieName =  'rdk.sid' ;
  313       if (pr efix) {
  314           co okieName =  prefix +  '.' + cook ieName;
  315       }
  316       return  cookieNam e;
  317   }
  318  
  319   function e nableSessi on(app) {
  320       app.us e(function (req, res,  next) {
  321           se ssion({
  322                store: n ew JDSStor e({
  323                    jdsS erver: {
  324                         baseUrl: r eq.app.con fig.jdsSer ver.baseUr l
  325                    }
  326                }, req.l ogger, req .app),
  327                secret:  app.config .secret,
  328                name: ge tCookieNam e(app.conf ig),
  329                cookie:  {
  330                    maxA ge: app.co nfig.sessi onLength
  331                },
  332                resave:  true,
  333                rolling:  true, //t his allows  the sessi on and tok en to refr esh each t ime
  334                saveUnin itialized:  false
  335           }) (req, res,  next);
  336       });
  337       app.us e(function (req, res,  next) {
  338           va r currentS essionId =  _.get(req , 'session .id', req. _requested SessionId) ;
  339           if  (currentS essionId ! == req._re questedSes sionId) {
  340                var logg erWithSess ionId = re q.logger.c hild({ sid : currentS essionId } );
  341                loggerWi thSessionI d.info('Ne w session  created');
  342                req.logg er = logge rWithSessi onId;
  343           }
  344           re turn next( );
  345       });
  346   }
  347  
  348   function e nableBodyP arser(app)  {
  349       app.us e(bodyPars er.json({
  350           li mit: '1mb'
  351       }));
  352   }
  353  
  354   function i nitializeH ttpWrapper (app) {
  355       httpUt il.initial izeTimeout (app.confi g.timeoutM illis);
  356       httpUt il.setMaxS ockets(app .config.ma xSockets);
  357   }
  358  
  359   function e nableMetho dOverride( app) {
  360       var me thodOverri deHeaderMi ddleware =  methodOve rride('X-H TTP-Method -Override' );
  361       app.us e(function (req, res,  next) {
  362           //  FHIR reso urces alre ady contai n their ow n version  of method  overriding
  363           //  Hack away  the dupli cate metho d overridi ng functio nality
  364           if  (isFhirRe source(req )) {
  365                req.orig inalMethod  = req.met hod;
  366                return n ext();
  367           }
  368           re turn metho dOverrideH eaderMiddl eware(req,  res, next );
  369       });
  370  
  371       functi on isFhirR esource(re q) {
  372           re turn _.sta rtsWith(re q.path, re q.app.conf ig.rootPat h + '/fhir ');
  373       }
  374   }
  375  
  376   function e nsureQuery MatchesBod y(app) {
  377       app.us e(function (req, res,  next) {
  378           if  (req.meth od === req .originalM ethod) {
  379                return n ext();
  380           }
  381           va r queryIsV alid = doe sQueryMatc hBody(req) ;
  382           if  (!queryIs Valid) {
  383                var rdkE rror = new  RdkError( {
  384                    code : 'rdk.400 .1008',
  385                    logg er: req.lo gger
  386                });
  387                return r es.status( 400).rdkSe nd(rdkErro r);
  388           }
  389           re q.query =  req.body;
  390           re turn next( );
  391       });
  392  
  393       functi on doesQue ryMatchBod y(req) {
  394           //  Ensure th at every q uery param eter is in  the body
  395           //  Ensure th at no quer y paramete r conflict s with a b ody parame ter
  396           va r queryMat chesBody =  _.every(r eq.query,  function(q ueryValue,  queryKey)  {
  397                if (_.is Undefined( req.body[q ueryKey]))  {
  398                    retu rn false;
  399                }
  400                try {
  401                    retu rn _.isEqu al(stringi fyValues(r eq.body[qu eryKey]),  queryValue );
  402                } catch  (ex) {
  403                    // M aximum cal l stack si ze exceede d
  404                    req. logger.err or(ex);
  405                    req. logger.err or('Error  stringifyi ng body va lues');
  406                    retu rn false;
  407                }
  408           }) ;
  409           re turn query MatchesBod y;
  410       }
  411  
  412       functi on stringi fyValues(o bject, _re cursed) {
  413           //  query par ameter val ues are al ways strin gs
  414           if  (!_recurs ed) {
  415                object =  _.cloneDe ep(object) ;
  416           }
  417           if  (_.isObje ct(object) ) {
  418                _.each(o bject, fun ction(valu e, key) {
  419                    if ( _.isObject (value)) {
  420                         object[key ] = string ifyValues( value, tru e);
  421                    } el se {
  422                         object[key ] = String (value);
  423                    }
  424                });
  425           }  else {
  426                object =  String(ob ject);
  427           }
  428           re turn objec t;
  429       }
  430   }
  431  
  432   function e nableRespo nseTimeHea der(app) {
  433       app.us e(response Time());
  434   }
  435