@contrast/assess 1.31.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/lib/crypto-analysis/install/crypto.test.js +146 -0
  2. package/lib/crypto-analysis/install/math.test.js +65 -0
  3. package/lib/dataflow/index.test.js +36 -0
  4. package/lib/dataflow/propagation/index.test.js +103 -0
  5. package/lib/dataflow/propagation/install/JSON/index.test.js +50 -0
  6. package/lib/dataflow/propagation/install/JSON/parse-fn.test.js +232 -0
  7. package/lib/dataflow/propagation/install/JSON/parse.test.js +968 -0
  8. package/lib/dataflow/propagation/install/JSON/stringify.test.js +265 -0
  9. package/lib/dataflow/propagation/install/array-prototype-join.test.js +106 -0
  10. package/lib/dataflow/propagation/install/buffer.test.js +109 -0
  11. package/lib/dataflow/propagation/install/contrast-methods/add.test.js +94 -0
  12. package/lib/dataflow/propagation/install/contrast-methods/index.test.js +49 -0
  13. package/lib/dataflow/propagation/install/contrast-methods/number.test.js +50 -0
  14. package/lib/dataflow/propagation/install/contrast-methods/string.test.js +148 -0
  15. package/lib/dataflow/propagation/install/contrast-methods/tag.test.js +145 -0
  16. package/lib/dataflow/propagation/install/decode-uri-component.test.js +78 -0
  17. package/lib/dataflow/propagation/install/ejs/escape-xml.test.js +69 -0
  18. package/lib/dataflow/propagation/install/ejs/template.test.js +62 -0
  19. package/lib/dataflow/propagation/install/encode-uri.test.js +83 -0
  20. package/lib/dataflow/propagation/install/escape-html.test.js +71 -0
  21. package/lib/dataflow/propagation/install/escape.test.js +73 -0
  22. package/lib/dataflow/propagation/install/handlebars-utils-escape-expression.test.js +71 -0
  23. package/lib/dataflow/propagation/install/isnumeric-0.test.js +58 -0
  24. package/lib/dataflow/propagation/install/joi/any.test.js +270 -0
  25. package/lib/dataflow/propagation/install/joi/array.test.js +912 -0
  26. package/lib/dataflow/propagation/install/joi/boolean.test.js +103 -0
  27. package/lib/dataflow/propagation/install/joi/expression.test.js +76 -0
  28. package/lib/dataflow/propagation/install/joi/index.test.js +39 -0
  29. package/lib/dataflow/propagation/install/joi/number.test.js +103 -0
  30. package/lib/dataflow/propagation/install/joi/object.test.js +119 -0
  31. package/lib/dataflow/propagation/install/joi/ref.test.js +607 -0
  32. package/lib/dataflow/propagation/install/joi/string-schema.test.js +513 -0
  33. package/lib/dataflow/propagation/install/mongoose/index.test.js +42 -0
  34. package/lib/dataflow/propagation/install/mongoose/schema-map.test.js +348 -0
  35. package/lib/dataflow/propagation/install/mongoose/schema-mixed.test.js +512 -0
  36. package/lib/dataflow/propagation/install/mongoose/schema-string.test.js +160 -0
  37. package/lib/dataflow/propagation/install/mustache-escape.test.js +62 -0
  38. package/lib/dataflow/propagation/install/mysql-connection-escape.test.js +74 -0
  39. package/lib/dataflow/propagation/install/parse-int.test.js +48 -0
  40. package/lib/dataflow/propagation/install/path/basename.test.js +143 -0
  41. package/lib/dataflow/propagation/install/path/dirname.test.js +167 -0
  42. package/lib/dataflow/propagation/install/path/extname.test.js +141 -0
  43. package/lib/dataflow/propagation/install/path/format.test.js +250 -0
  44. package/lib/dataflow/propagation/install/path/index.test.js +45 -0
  45. package/lib/dataflow/propagation/install/path/join-and-resolve.test.js +485 -0
  46. package/lib/dataflow/propagation/install/path/normalize.test.js +176 -0
  47. package/lib/dataflow/propagation/install/path/parse.test.js +238 -0
  48. package/lib/dataflow/propagation/install/path/relative.test.js +239 -0
  49. package/lib/dataflow/propagation/install/path/toNamespacedPath.test.js +158 -0
  50. package/lib/dataflow/propagation/install/pug/index.test.js +55 -0
  51. package/lib/dataflow/propagation/install/pug-runtime-escape.test.js +69 -0
  52. package/lib/dataflow/propagation/install/querystring/escape.test.js +63 -0
  53. package/lib/dataflow/propagation/install/querystring/index.test.js +40 -0
  54. package/lib/dataflow/propagation/install/querystring/parse.test.js +272 -0
  55. package/lib/dataflow/propagation/install/querystring/stringify.test.js +301 -0
  56. package/lib/dataflow/propagation/install/reg-exp-prototype-exec.test.js +281 -0
  57. package/lib/dataflow/propagation/install/send.test.js +63 -0
  58. package/lib/dataflow/propagation/install/sequelize/query-generator.test.js +73 -0
  59. package/lib/dataflow/propagation/install/sequelize/sql-string.test.js +130 -0
  60. package/lib/dataflow/propagation/install/sql-template-strings.test.js +100 -0
  61. package/lib/dataflow/propagation/install/string/concat.test.js +132 -0
  62. package/lib/dataflow/propagation/install/string/format-methods.test.js +61 -0
  63. package/lib/dataflow/propagation/install/string/html-methods.test.js +164 -0
  64. package/lib/dataflow/propagation/install/string/index.test.js +103 -0
  65. package/lib/dataflow/propagation/install/string/match-all.test.js +399 -0
  66. package/lib/dataflow/propagation/install/string/match.test.js +361 -0
  67. package/lib/dataflow/propagation/install/string/replace.test.js +588 -0
  68. package/lib/dataflow/propagation/install/string/slice.test.js +265 -0
  69. package/lib/dataflow/propagation/install/string/split.test.js +500 -0
  70. package/lib/dataflow/propagation/install/string/substring.test.js +238 -0
  71. package/lib/dataflow/propagation/install/string/trim.test.js +122 -0
  72. package/lib/dataflow/propagation/install/unescape.test.js +78 -0
  73. package/lib/dataflow/propagation/install/url/domain-parsers.test.js +63 -0
  74. package/lib/dataflow/propagation/install/url/parse.test.js +391 -0
  75. package/lib/dataflow/propagation/install/url/searchParams.test.js +538 -0
  76. package/lib/dataflow/propagation/install/url/url.test.js +466 -0
  77. package/lib/dataflow/propagation/install/util-format.test.js +336 -0
  78. package/lib/dataflow/propagation/install/validator/hooks.test.js +211 -0
  79. package/lib/dataflow/sinks/index.test.js +78 -0
  80. package/lib/dataflow/sinks/install/child-process.test.js +338 -0
  81. package/lib/dataflow/sinks/install/eval.test.js +95 -0
  82. package/lib/dataflow/sinks/install/express/index.test.js +33 -0
  83. package/lib/dataflow/sinks/install/express/reflected-xss.js +55 -57
  84. package/lib/dataflow/sinks/install/express/reflected-xss.test.js +109 -0
  85. package/lib/dataflow/sinks/install/express/unvalidated-redirect.test.js +144 -0
  86. package/lib/dataflow/sinks/install/fastify/index.test.js +32 -0
  87. package/lib/dataflow/sinks/install/fastify/unvalidated-redirect.test.js +130 -0
  88. package/lib/dataflow/sinks/install/fs.test.js +138 -0
  89. package/lib/dataflow/sinks/install/function.test.js +103 -0
  90. package/lib/dataflow/sinks/install/hapi/index.test.js +32 -0
  91. package/lib/dataflow/sinks/install/hapi/unvalidated-redirect.test.js +130 -0
  92. package/lib/dataflow/sinks/install/http/index.test.js +33 -0
  93. package/lib/dataflow/sinks/install/http/request.test.js +184 -0
  94. package/lib/dataflow/sinks/install/http/server-response.test.js +162 -0
  95. package/lib/dataflow/sinks/install/koa/index.test.js +32 -0
  96. package/lib/dataflow/sinks/install/koa/unvalidated-redirect.test.js +200 -0
  97. package/lib/dataflow/sinks/install/libxmljs.test.js +158 -0
  98. package/lib/dataflow/sinks/install/marsdb.test.js +166 -0
  99. package/lib/dataflow/sinks/install/mongodb.test.js +621 -0
  100. package/lib/dataflow/sinks/install/mssql.test.js +136 -0
  101. package/lib/dataflow/sinks/install/mysql.test.js +233 -0
  102. package/lib/dataflow/sinks/install/node-serialize.test.js +85 -0
  103. package/lib/dataflow/sinks/install/postgres.test.js +158 -0
  104. package/lib/dataflow/sinks/install/restify.test.js +142 -0
  105. package/lib/dataflow/sinks/install/sequelize.test.js +100 -0
  106. package/lib/dataflow/sinks/install/sqlite3.test.js +118 -0
  107. package/lib/dataflow/sinks/install/vm.test.js +326 -0
  108. package/lib/dataflow/sources/handler.test.js +463 -0
  109. package/lib/dataflow/sources/index.test.js +58 -0
  110. package/lib/dataflow/sources/install/body-parser1.test.js +248 -0
  111. package/lib/dataflow/sources/install/busboy.test.js +152 -0
  112. package/lib/dataflow/sources/install/cookie-parser1.test.js +143 -0
  113. package/lib/dataflow/sources/install/express/params.test.js +105 -0
  114. package/lib/dataflow/sources/install/express/parsedUrl.test.js +65 -0
  115. package/lib/dataflow/sources/install/fastify/fastify.test.js +210 -0
  116. package/lib/dataflow/sources/install/fastify/index.test.js +33 -0
  117. package/lib/dataflow/sources/install/formidable1.test.js +119 -0
  118. package/lib/dataflow/sources/install/hapi/hapi.test.js +172 -0
  119. package/lib/dataflow/sources/install/hapi/index.test.js +33 -0
  120. package/lib/dataflow/sources/install/http.test.js +155 -0
  121. package/lib/dataflow/sources/install/koa/index.test.js +40 -0
  122. package/lib/dataflow/sources/install/koa/koa-bodyparsers.test.js +161 -0
  123. package/lib/dataflow/sources/install/koa/koa-multer.test.js +197 -0
  124. package/lib/dataflow/sources/install/koa/koa-routers.test.js +146 -0
  125. package/lib/dataflow/sources/install/koa/koa2.test.js +145 -0
  126. package/lib/dataflow/sources/install/multer1.test.js +145 -0
  127. package/lib/dataflow/sources/install/qs6.test.js +131 -0
  128. package/lib/dataflow/sources/install/querystring.test.js +82 -0
  129. package/lib/dataflow/sources/install/restify/fieldedTextBodyParser.test.js +88 -0
  130. package/lib/dataflow/sources/install/restify/index.test.js +38 -0
  131. package/lib/dataflow/sources/install/restify/jsonBodyParser.test.js +144 -0
  132. package/lib/dataflow/sources/install/restify/router.test.js +83 -0
  133. package/lib/dataflow/tag-utils-complete.test.js +27 -0
  134. package/lib/dataflow/tag-utils.test.js +192 -0
  135. package/lib/dataflow/tracker.test.js +216 -0
  136. package/lib/dataflow/utils/is-safe-content-type.test.js +16 -0
  137. package/lib/dataflow/utils/is-vulnerable.test.js +115 -0
  138. package/lib/event-factory.test.js +321 -0
  139. package/lib/get-policy.test.js +194 -0
  140. package/lib/get-source-context.test.js +108 -0
  141. package/lib/index.test.js +41 -0
  142. package/lib/make-source-context.test.js +50 -0
  143. package/lib/response-scanning/handlers/index.test.js +425 -0
  144. package/lib/response-scanning/handlers/utils.test.js +391 -0
  145. package/lib/response-scanning/index.test.js +41 -0
  146. package/lib/response-scanning/install/http.test.js +175 -0
  147. package/lib/rule-scopes.test.js +27 -0
  148. package/lib/session-configuration/handlers.test.js +84 -0
  149. package/lib/session-configuration/index.test.js +36 -0
  150. package/lib/session-configuration/install/express-session.test.js +220 -0
  151. package/lib/session-configuration/install/fastify-cookie.test.js +65 -0
  152. package/lib/session-configuration/install/hapi.test.js +269 -0
  153. package/lib/session-configuration/install/koa.test.js +92 -0
  154. package/package.json +2 -2
@@ -0,0 +1,155 @@
1
+ 'use strict';
2
+
3
+ const EventEmitter = require('events');
4
+ const sinon = require('sinon');
5
+ const { expect } = require('chai');
6
+ const { initAssessFixture } = require('@contrast/test/fixtures');
7
+
8
+ describe('assess dataflow sources http', function () {
9
+ let core, simulateRequestScope, request, response, server;
10
+
11
+ beforeEach(function () {
12
+ ({ core, simulateRequestScope } = initAssessFixture());
13
+
14
+ request = {
15
+ url: 'http://host:8080/index.html?param=foo',
16
+ httpVersion: 1,
17
+ method: 'GET',
18
+ socket: {
19
+ remoteAddress: '127.0.0.1'
20
+ },
21
+ rawHeaders: ['Content-Type', 'application/json'],
22
+ headers: {
23
+ 'content-type': 'application/json'
24
+ }
25
+ };
26
+ response = new EventEmitter();
27
+ response.writeHead = function () { };
28
+ response.setHeader = function () { };
29
+ class Server extends EventEmitter { }
30
+ core.depHooks.resolve.withArgs({ name: 'http' }).yields({ Server });
31
+ core.logger.child = () => core.logger;
32
+
33
+ require('./http')(core).install();
34
+ server = new Server();
35
+ });
36
+
37
+ it('instantiates assess store with appropriate metadata and handles base sources', function (next) {
38
+ simulateRequestScope(() => {
39
+ server.on('request', test);
40
+ server.emit('request', request, response);
41
+ });
42
+
43
+ function test(req, res) {
44
+ const store = core.scopes.sources.getStore()?.assess;
45
+ // validate store
46
+ expect(store).to.have.property('propagationEventsCount', 0);
47
+ // 3: url, headers, rawHeaders
48
+ expect(store).to.have.property('sourceEventsCount', 3);
49
+ expect(store.policy.enabledRules).to.be.a('Set').and.length.greaterThan(5);
50
+ expect(store.reqData).to.deep.equal({
51
+ ip: '127.0.0.1',
52
+ httpVersion: 1,
53
+ method: 'GET',
54
+ headers: { 'content-type': 'application/json' },
55
+ uriPath: 'http://host:8080/index.html',
56
+ queries: 'param=foo',
57
+ contentType: 'application/json'
58
+ });
59
+ expect(store.responseData).to.deep.equal({});
60
+ // tracked inputs
61
+ expect(core.assess.dataflow.tracker.getData(request.url)).to.be.ok;
62
+ expect(core.assess.dataflow.tracker.getData(request.headers['content-type'])).to.be.ok;
63
+ // patched methods
64
+ expect(core.patcher.isContrastHooked(res.writeHead)).to.be.true;
65
+ expect(core.patcher.isContrastHooked(res.setHeader)).to.be.true;
66
+ response.writeHead(200, { 'content-type': 'application/json' });
67
+ expect(store.responseData).to.deep.equal({ contentType: 'application/json' });
68
+ response.setHeader('content-type', 'text/html');
69
+ expect(store.responseData).to.deep.equal({ contentType: 'text/html' });
70
+ response.writeHead(); // instrumentation is noop
71
+ expect(store.responseData).to.deep.equal({ contentType: 'text/html' });
72
+ next();
73
+ }
74
+ });
75
+
76
+ it('noop if server event is not type \'request\'', function (next) {
77
+ simulateRequestScope(() => {
78
+ server.on('foo', test);
79
+ server.emit('foo', request, response);
80
+ });
81
+
82
+ function test(req, res) {
83
+ const store = core.scopes.sources.getStore()?.assess;
84
+ // // validate store
85
+ expect(store).to.have.property('propagationEventsCount', 0);
86
+ expect(store).to.have.property('sourceEventsCount', 0);
87
+ expect(store.policy.enabledRules).to.be.a('Set').and.length.greaterThan(5);
88
+ // // tracked inputs
89
+ expect(core.assess.dataflow.tracker.getData(request.url)).to.be.null;
90
+ expect(core.assess.dataflow.tracker.getData(request.headers['content-type'])).to.be.null;
91
+ // // patched methods
92
+ expect(core.patcher.isContrastHooked(res.writeHead)).to.be.false;
93
+ expect(core.patcher.isContrastHooked(res.setHeader)).to.be.false;
94
+ next();
95
+ }
96
+ });
97
+
98
+ it('logs debug message if there is no async request store', function (next) {
99
+ server.on('request', test);
100
+ server.emit('request', request, response);
101
+
102
+ function test(req, res) {
103
+ const store = core.scopes.sources.getStore()?.assess;
104
+ // logging
105
+ expect(core.logger.error).to.have.been.calledWith(
106
+ { err: sinon.match.has('message', 'async request store not found'), funcKey: sinon.match.string },
107
+ 'Error during Assess request handling'
108
+ );
109
+ // validate store
110
+ expect(store).to.be.undefined;
111
+ // tracked inputs
112
+ expect(core.assess.dataflow.tracker.getData(request.url)).to.be.null;
113
+ expect(core.assess.dataflow.tracker.getData(request.headers['content-type'])).to.be.null;
114
+ // patched methods
115
+ expect(core.patcher.isContrastHooked(res.writeHead)).to.be.false;
116
+ expect(core.patcher.isContrastHooked(res.setHeader)).to.be.false;
117
+ next();
118
+ }
119
+ });
120
+
121
+ it('handles a case with an error in the `.handle` method', function (next) {
122
+ const err = new Error('test');
123
+ core.assess.dataflow.sources.handle = sinon.stub().throws(err);
124
+
125
+ simulateRequestScope(() => {
126
+ server.on('request', test);
127
+ server.emit('request', request, response);
128
+ });
129
+
130
+ function test(req, res) {
131
+ const store = core.scopes.sources.getStore()?.assess;
132
+ // validate store
133
+ expect(store).to.have.property('propagationEventsCount', 0);
134
+ expect(store).to.have.property('sourceEventsCount', 0);
135
+ expect(store.policy.enabledRules).to.be.a('Set').and.length.greaterThan(5);
136
+ expect(store.reqData).to.deep.equal({
137
+ ip: '127.0.0.1',
138
+ httpVersion: 1,
139
+ method: 'GET',
140
+ headers: { 'content-type': 'application/json' },
141
+ uriPath: 'http://host:8080/index.html',
142
+ queries: 'param=foo',
143
+ contentType: 'application/json'
144
+ });
145
+ expect(store.responseData).to.deep.equal({});
146
+ // tracked inputs
147
+ expect(core.assess.dataflow.tracker.getData(request.url)).to.be.null;
148
+ expect(core.assess.dataflow.tracker.getData(request.headers['content-type'])).to.be.null;
149
+ // patched methods
150
+ expect(core.patcher.isContrastHooked(res.writeHead)).to.be.true;
151
+ expect(core.patcher.isContrastHooked(res.setHeader)).to.be.true;
152
+ next();
153
+ }
154
+ });
155
+ });
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ const { expect } = require('chai');
4
+ const proxyquire = require('proxyquire');
5
+ const mocks = require('@contrast/test/mocks');
6
+
7
+ const moduleMock = (moduleName, mock) => (deps) => {
8
+ deps.assess.dataflow.sources.koaInstrumentation[moduleName] = mock[moduleName];
9
+ };
10
+
11
+ describe('assess dataflow sources koa', function () {
12
+ let core, koaSourcesMock, koaSourcesModule, modulesWithInstall;
13
+
14
+ beforeEach(function () {
15
+ core = mocks.core();
16
+ core.assess = mocks.assess();
17
+ koaSourcesMock = core.assess.dataflow.sources.koaInstrumentation;
18
+ koaSourcesModule = proxyquire('.', {
19
+ './koa2': moduleMock('koa2', koaSourcesMock),
20
+ './koa-bodyparsers': moduleMock('koaBodyparsers', koaSourcesMock),
21
+ './koa-multer': moduleMock('koaMulter', koaSourcesMock),
22
+ './koa-routers': moduleMock('koaRouters', koaSourcesMock),
23
+ });
24
+ modulesWithInstall = [
25
+ 'koa2',
26
+ 'koaBodyparsers',
27
+ 'koaMulter',
28
+ 'koaRouters',
29
+ ];
30
+ });
31
+
32
+ it('installs the components', function () {
33
+ koaSourcesModule(core).install();
34
+
35
+ modulesWithInstall.forEach((module) => {
36
+ expect(koaSourcesMock[module].install).to.have.been.calledOnce;
37
+ });
38
+ });
39
+ });
40
+
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+
3
+ const sinon = require('sinon');
4
+ const { expect } = require('chai');
5
+ const { initAssessFixture } = require('@contrast/test/fixtures');
6
+ const { InputType } = require('@contrast/common');
7
+ const koaBodyInstr = require('./koa-bodyparsers');
8
+
9
+ describe('assess dataflow sources koa-body v5.x.x and koa-bodyparser v4.x.x', function () {
10
+ let core, simulateRequestScope, koaBodyparserMock, patchedKoaBodyparser, body, sources, nextStub;
11
+
12
+ beforeEach(function () {
13
+ ({ core, simulateRequestScope } = initAssessFixture());
14
+
15
+ sources = core.assess.dataflow.sources;
16
+ sinon.spy(sources, 'handle');
17
+
18
+ body = { parameter: 'parsed' };
19
+
20
+ koaBodyparserMock = (body) => (ctx, next) => {
21
+ ctx.request.body = body;
22
+ next();
23
+ };
24
+ nextStub = sinon.stub();
25
+ sinon.spy(core.patcher, 'patch');
26
+
27
+ koaBodyInstr(core).install();
28
+ patchedKoaBodyparser = core.depHooks.resolve.yield(koaBodyparserMock)[0];
29
+ core.patcher.patch.resetHistory();
30
+ });
31
+
32
+ it('calls patcher on the `koa-body` and `koa-bodyparser` module exports', function () {
33
+ core.depHooks.resolve.yield(koaBodyparserMock);
34
+
35
+ expect(core.patcher.patch).to.have.been.calledTwice;
36
+ expect(core.patcher.patch).to.have.been.calledWithMatch(koaBodyparserMock, {
37
+ name: 'koa-body',
38
+ patchType: 'assess-dataflow-source',
39
+ post: sinon.match.func
40
+ });
41
+ expect(core.patcher.patch).to.have.been.calledWithMatch(koaBodyparserMock, {
42
+ name: 'koa-bodyparser',
43
+ patchType: 'assess-dataflow-source',
44
+ post: sinon.match.func
45
+ });
46
+ });
47
+
48
+ it('calls `.handle` when parsing body is successful and in right context', function () {
49
+ let scCall1, scCall2, scCall3;
50
+
51
+ simulateRequestScope(() => {
52
+ const bParser = patchedKoaBodyparser(body);
53
+ bParser({ request: { body: {} } }, nextStub);
54
+
55
+ scCall1 = core.scopes.sources.getStore()?.assess;
56
+ });
57
+ simulateRequestScope(() => {
58
+ scCall2 = core.scopes.sources.getStore()?.assess;
59
+ scCall2.reqData.headers = {
60
+ 'content-type': 'application/json'
61
+ };
62
+
63
+ const bParser = patchedKoaBodyparser(body);
64
+ bParser({ request: {} }, nextStub);
65
+ });
66
+ simulateRequestScope(() => {
67
+ const bParser = patchedKoaBodyparser('non-object-body');
68
+ bParser({ request: {} }, nextStub);
69
+
70
+ scCall3 = core.scopes.sources.getStore()?.assess;
71
+ });
72
+
73
+
74
+ expect(core.patcher.patch).to.have.been.calledThrice;
75
+ expect(core.patcher.patch).to.have.been.calledWithMatch(sinon.match.func, {
76
+ name: 'koa-body',
77
+ patchType: 'assess-dataflow-source',
78
+ pre: sinon.match.func
79
+ });
80
+
81
+ expect(nextStub).to.have.been.calledThrice;
82
+ expect(sources.handle).to.have.been.calledThrice;
83
+ expect(sources.handle).to.have.been.calledWithMatch({
84
+ context: 'ctx.request.body',
85
+ name: 'koa-body',
86
+ stacktraceOpts: {
87
+ constructorOpt: sinon.match.func,
88
+ },
89
+ inputType: InputType.PARAMETER_VALUE,
90
+ data: { parameter: 'parsed' },
91
+ sourceContext: scCall1
92
+ });
93
+ expect(sources.handle).to.have.been.calledWithMatch({
94
+ context: 'ctx.request.body',
95
+ name: 'koa-body',
96
+ stacktraceOpts: {
97
+ constructorOpt: sinon.match.func,
98
+ },
99
+ inputType: InputType.JSON_VALUE,
100
+ data: { parameter: 'parsed' },
101
+ sourceContext: scCall2
102
+ });
103
+ expect(sources.handle).to.have.been.calledWithMatch({
104
+ context: 'ctx.request.body',
105
+ name: 'koa-body',
106
+ stacktraceOpts: {
107
+ constructorOpt: sinon.match.func,
108
+ },
109
+ inputType: InputType.BODY,
110
+ data: 'non-object-body',
111
+ sourceContext: scCall3
112
+ });
113
+ });
114
+
115
+ it('does not call `.handle` when not in context', function () {
116
+ simulateRequestScope(() => {
117
+ const cParser = patchedKoaBodyparser(body);
118
+ cParser({ request: {} }, nextStub);
119
+ }, {});
120
+
121
+ expect(sources.handle).not.to.have.been.called;
122
+ expect(nextStub).to.have.been.calledOnce;
123
+ });
124
+
125
+ it('does not call `.handle` when the values are already tracked', function () {
126
+ simulateRequestScope(() => {
127
+ const sourceContext = core.scopes.sources.getStore()?.assess;
128
+ sourceContext.parsedBody = true;
129
+
130
+ const cParser = patchedKoaBodyparser(body);
131
+ cParser({ request: {} }, nextStub);
132
+ });
133
+
134
+ expect(sources.handle).not.to.have.been.called;
135
+ expect(core.logger.trace).to.have.been.calledWith(
136
+ { funcKey: 'assess-dataflow-source:koa-body' },
137
+ 'values already tracked',
138
+ );
139
+ expect(nextStub).to.have.been.calledOnce;
140
+ });
141
+
142
+ it('handles a case with an error in the `.handle` method', function () {
143
+ const err = new Error('test');
144
+
145
+ core.assess.dataflow.sources.handle = () => {
146
+ throw err;
147
+ };
148
+
149
+ simulateRequestScope(() => {
150
+ const cParser = patchedKoaBodyparser(body);
151
+ cParser({ request: {} }, nextStub);
152
+ });
153
+
154
+ expect(core.logger.error).to.have.been.calledWith(
155
+ { err, inputType: InputType.PARAMETER_VALUE, funcKey: 'assess-dataflow-source:koa-body' },
156
+ 'unable to handle Koa source',
157
+ );
158
+ expect(nextStub).to.have.been.calledOnce;
159
+ expect(nextStub).not.to.have.been.calledWith(err);
160
+ });
161
+ });
@@ -0,0 +1,197 @@
1
+ 'use strict';
2
+
3
+ const sinon = require('sinon');
4
+ const { expect } = require('chai');
5
+ const koaMulter = require('./koa-multer');
6
+ const { InputType } = require('@contrast/common');
7
+ const { initAssessFixture } = require('@contrast/test/fixtures');
8
+
9
+ describe('assess dataflow sources Koa multer', function () {
10
+ let core,
11
+ koaMulterMock,
12
+ patchedKoaMulter,
13
+ simulateRequestScope;
14
+
15
+ ['koa-multer', '@koa/multer'].forEach((name) => {
16
+ describe(name, function() {
17
+ beforeEach(function () {
18
+ ({ core, simulateRequestScope } = initAssessFixture());
19
+
20
+ sinon.spy(core.patcher, 'patch');
21
+
22
+ core.assess.dataflow.sources.handle = sinon.stub();
23
+
24
+ koaMulterMock = function() {
25
+ const multer = {
26
+ _makeMiddleware() {
27
+ return function(req, res, next) {
28
+ next();
29
+ };
30
+ }
31
+ };
32
+
33
+ multer.any = function() {
34
+ const middleware = multer._makeMiddleware();
35
+
36
+ return (ctx, next) =>
37
+ new Promise((resolve, reject) => {
38
+ middleware(ctx.req, ctx.res, (err) => {
39
+ err ? reject(err) : resolve(ctx);
40
+ });
41
+ }).then(next);
42
+ };
43
+
44
+ return multer;
45
+ };
46
+
47
+ koaMulter(core).install();
48
+
49
+ [patchedKoaMulter] = core.depHooks.resolve
50
+ .withArgs({ name })
51
+ .yield(koaMulterMock);
52
+
53
+ });
54
+
55
+ it('skip instrumentation if it is our of scope', async function () {
56
+ const ctx = {
57
+ req: {},
58
+ res: {}
59
+ };
60
+ const next = sinon.stub();
61
+ const middleware = patchedKoaMulter({ dest: '/uploads' }).any('file');
62
+
63
+ await middleware(ctx, next);
64
+ expect(next).to.have.been.called;
65
+ expect(core.assess.dataflow.sources.handle).not.to.have.been.called;
66
+ });
67
+
68
+ it('skip instrumentation if there are no files ', function () {
69
+ simulateRequestScope(async () => {
70
+ const ctx = {
71
+ req: {},
72
+ res: {}
73
+ };
74
+ const next = sinon.stub();
75
+ const middleware = patchedKoaMulter({ dest: '/uploads' }).any('file');
76
+
77
+ await middleware(ctx, next);
78
+ expect(next).to.have.been.called;
79
+ expect(core.assess.dataflow.sources.handle).not.to.have.been.called;
80
+ });
81
+ });
82
+
83
+ it('handle sources (file)', function () {
84
+ simulateRequestScope(async () => {
85
+ const ctx = {
86
+ req: {
87
+ file: {
88
+ property: 'file'
89
+ }
90
+ },
91
+ res: {}
92
+ };
93
+ const next = sinon.stub();
94
+ const middleware = patchedKoaMulter({ dest: '/uploads' }).any('file');
95
+
96
+ await middleware(ctx, next);
97
+ expect(next).to.have.been.called;
98
+ expect(core.assess.dataflow.sources.handle).to.have.been.calledWithMatch({
99
+ context: 'req',
100
+ data: ctx.req,
101
+ keys: ['file'],
102
+ name: 'multer',
103
+ inputType: InputType.BODY,
104
+ });
105
+ });
106
+ });
107
+
108
+ it('handle sources (files)', function () {
109
+ simulateRequestScope(async () => {
110
+ const ctx = {
111
+ req: {
112
+ files: [
113
+ {
114
+ property: 'file0'
115
+ },
116
+ {
117
+ property: 'file1'
118
+ }
119
+ ]
120
+ },
121
+ res: {}
122
+ };
123
+
124
+ const next = sinon.stub();
125
+ const middleware = patchedKoaMulter({ dest: '/uploads' }).any('file');
126
+
127
+ await middleware(ctx, next);
128
+ expect(next).to.have.been.called;
129
+ expect(core.assess.dataflow.sources.handle).to.have.been.calledWithMatch({
130
+ context: 'req.files',
131
+ data: ctx.req.files[0],
132
+ keys: [0],
133
+ name: 'multer',
134
+ inputType: InputType.BODY,
135
+ });
136
+ expect(core.assess.dataflow.sources.handle).to.have.been.calledWithMatch({
137
+ context: 'req.files',
138
+ data: ctx.req.files[1],
139
+ keys: [1],
140
+ name: 'multer',
141
+ inputType: InputType.BODY,
142
+ });
143
+ });
144
+ });
145
+
146
+ it('handle sources (body)', function () {
147
+ simulateRequestScope(async () => {
148
+ const ctx = {
149
+ req: {
150
+ body: {
151
+ name: 'John'
152
+ }
153
+ },
154
+ res: {}
155
+ };
156
+
157
+ const next = sinon.stub();
158
+ const middleware = patchedKoaMulter({ dest: '/uploads' }).any('file');
159
+
160
+ await middleware(ctx, next);
161
+ expect(next).to.have.been.called;
162
+ expect(core.assess.dataflow.sources.handle).to.have.been.calledWithMatch({
163
+ context: 'req',
164
+ data: ctx.req,
165
+ keys: ['body'],
166
+ name: 'multer',
167
+ inputType: InputType.BODY,
168
+ });
169
+ });
170
+ });
171
+
172
+ it('should log error if there is an issue handling sources', function () {
173
+ simulateRequestScope(async () => {
174
+ const err = new Error();
175
+ const ctx = {
176
+ req: {
177
+ file: {
178
+ property: 'file'
179
+ }
180
+ },
181
+ res: {}
182
+ };
183
+ core.assess.dataflow.sources.handle.callsFake(() => {
184
+ throw err;
185
+ });
186
+
187
+ const next = sinon.stub();
188
+ const middleware = patchedKoaMulter({ dest: '/uploads' }).any('file');
189
+
190
+ await middleware(ctx, next);
191
+ expect(next).to.have.been.called;
192
+ expect(core.logger.error).to.have.been.calledWith({ err }, 'error handling Koa multer Assess dataflow %s.%s source', 'req', 'file');
193
+ });
194
+ });
195
+ });
196
+ });
197
+ });
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+
3
+ const sinon = require('sinon');
4
+ const { expect } = require('chai');
5
+ const { initAssessFixture } = require('@contrast/test/fixtures');
6
+ const { InputType } = require('@contrast/common');
7
+ const koaRouters = require('./koa-routers');
8
+
9
+ describe('assess dataflow sources koa-router and @koa/router', function () {
10
+ let core,
11
+ simulateRequestScope,
12
+ routerMock,
13
+ legacyRouterMock,
14
+ params,
15
+ sources;
16
+
17
+
18
+ beforeEach(function () {
19
+ ({ core, simulateRequestScope } = initAssessFixture());
20
+
21
+ sources = core.assess.dataflow.sources;
22
+ sinon.spy(sources, 'handle');
23
+ sinon.spy(core.patcher, 'patch');
24
+
25
+ params = { parameter: 'parsed-param' };
26
+ routerMock = {
27
+ prototype: {
28
+ params: (parameters) => parameters || {}
29
+ }
30
+ };
31
+
32
+ legacyRouterMock = {
33
+ prototype: {
34
+ params: (parameters) => parameters || {}
35
+ }
36
+ };
37
+ const mockDict = {
38
+ ['koa-router']: legacyRouterMock,
39
+ ['@koa/router']: routerMock,
40
+ };
41
+
42
+ core.depHooks.resolve.callsFake(function (desc, cb) {
43
+ const cbArg = mockDict[desc.name];
44
+ if (cbArg) {
45
+ cb(cbArg);
46
+ }
47
+ });
48
+
49
+ koaRouters(core).install();
50
+ core.patcher.patch.resetHistory();
51
+ });
52
+
53
+ it('calls patcher for every necessary instrumentation', function () {
54
+ koaRouters(core).install();
55
+ expect(core.patcher.patch).to.have.been.calledTwice;
56
+ expect(core.patcher.patch).to.have.been.calledWithMatch(legacyRouterMock.prototype, 'params', {
57
+ name: '[koa-router].layer.prototype',
58
+ patchType: 'assess-dataflow-source',
59
+ post: sinon.match.func
60
+ });
61
+ expect(core.patcher.patch).to.have.been.calledWithMatch(routerMock.prototype, 'params', {
62
+ name: '[@koa/router].layer.prototype',
63
+ patchType: 'assess-dataflow-source',
64
+ post: sinon.match.func
65
+ });
66
+ });
67
+
68
+ describe('koa routers post hook', function () {
69
+ let getParamsFn;
70
+ this.beforeEach(function () {
71
+ getParamsFn = function (routerName) {
72
+ return routerName == 'koa-router' ? legacyRouterMock.prototype.params : routerMock.prototype.params;
73
+ };
74
+ });
75
+ ['koa-router', '@koa/router'].forEach((router) => {
76
+ it(`[${router}] calls \`.handle\` when parsing is successful and in the right context`, function () {
77
+ const paramsFn = getParamsFn(router);
78
+ let sourceContext;
79
+
80
+ simulateRequestScope(() => {
81
+ paramsFn(params);
82
+
83
+ sourceContext = core.scopes.sources.getStore()?.assess;
84
+ });
85
+
86
+ expect(sources.handle).to.have.been.calledOnce;
87
+ expect(sources.handle).to.have.been.calledWithMatch({
88
+ context: 'ctx.params',
89
+ name: `[${router}].layer.prototype`,
90
+ stacktraceOpts: {
91
+ constructorOpt: sinon.match.func,
92
+ prependFrames: [sinon.match.func]
93
+ },
94
+ inputType: InputType.URL_PARAMETER,
95
+ data: { parameter: 'parsed-param' },
96
+ sourceContext
97
+ });
98
+ });
99
+
100
+ it(`[${router}] does not call \`.handle\` when there is no context`, function () {
101
+ const paramsFn = getParamsFn(router);
102
+
103
+ simulateRequestScope(() => {
104
+ paramsFn(params);
105
+ }, {});
106
+
107
+ expect(sources.handle).not.to.have.been.called;
108
+ });
109
+
110
+ it('does not call `.handle` when the values are already tracked', function () {
111
+ const paramsFn = getParamsFn(router);
112
+
113
+ simulateRequestScope(() => {
114
+ const sourceContext = core.scopes.sources.getStore()?.assess;
115
+ sourceContext.parsedParams = true;
116
+
117
+ paramsFn(params);
118
+ });
119
+
120
+ expect(sources.handle).not.to.have.been.called;
121
+ expect(core.logger.trace).to.have.been.calledWith(
122
+ { inputType: InputType.URL_PARAMETER, funcKey: `assess-dataflow-source:[${router}].layer.prototype` },
123
+ 'values already tracked',
124
+ );
125
+ });
126
+
127
+ it('handles a case with an error in the `.handle` method', function () {
128
+ const paramsFn = getParamsFn(router);
129
+ const err = new Error('test');
130
+
131
+ core.assess.dataflow.sources.handle = () => {
132
+ throw err;
133
+ };
134
+
135
+ simulateRequestScope(() => {
136
+ paramsFn(params);
137
+ });
138
+
139
+ expect(core.logger.error).to.have.been.calledWith(
140
+ { err, inputType: InputType.URL_PARAMETER, funcKey: `assess-dataflow-source:[${router}].layer.prototype` },
141
+ 'unable to handle Koa source',
142
+ );
143
+ });
144
+ });
145
+ });
146
+ });