-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathpredicates.js
More file actions
459 lines (392 loc) · 16.4 KB
/
predicates.js
File metadata and controls
459 lines (392 loc) · 16.4 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
'use strict';
const stringify = require('safe-stable-stringify'),
safeRegex = require('safe-regex'),
jsonpath = require('./jsonpath.js'),
helpers = require('../util/helpers.js'),
xPath = require('./xpath.js'),
combinators = require('../util/combinators.js'),
errors = require('../util/errors.js'),
compatibility = require('./compatibility.js');
/**
* All the predicates that determine whether a stub matches a request
* @module
*/
function sortObjects (a, b) {
const isObject = helpers.isObject;
if (isObject(a) && isObject(b)) {
// Make best effort at sorting arrays of objects to make
// deepEquals order-independent
return sortObjects(stringify(a), stringify(b));
}
else if (a < b) {
return -1;
}
else {
return 1;
}
}
function forceStrings (value) {
const isObject = helpers.isObject;
if (value === null) {
return 'null';
}
else if (Array.isArray(value)) {
return value.map(forceStrings);
}
else if (isObject(value)) {
return Object.keys(value).reduce((accumulator, key) => {
accumulator[key] = forceStrings(value[key]);
return accumulator;
}, {});
}
else if (typeof value.toString === 'function') {
return value.toString();
}
else {
return value;
}
}
function select (type, selectFn, encoding) {
if (encoding === 'base64') {
throw errors.ValidationError(`the ${type} predicate parameter is not allowed in binary mode`);
}
const nodeValues = selectFn();
// Return either a string if one match or array if multiple
// This matches the behavior of node's handling of query parameters,
// which allows us to maintain the same semantics between deepEquals
// (all have to match, passing in an array if necessary) and the other
// predicates (any can match)
if (nodeValues && nodeValues.length === 1) {
return nodeValues[0];
}
else {
return nodeValues;
}
}
function orderIndependent (possibleArray) {
if (Array.isArray(possibleArray)) {
return possibleArray.sort(sortObjects);
}
else {
return possibleArray;
}
}
function transformObject (obj, transform) {
Object.keys(obj).forEach(key => {
obj[key] = transform(obj[key]);
});
return obj;
}
function selectXPath (config, encoding, text) {
const selectFn = combinators.curry(xPath.select, config.selector, config.ns, text);
return orderIndependent(select('xpath', selectFn, encoding));
}
function selectTransform (config, options, logger) {
const cloned = helpers.clone(config);
if (config.jsonpath) {
const stringTransform = options.shouldForceStrings ? forceStrings : combinators.identity;
// use keyCaseSensitive instead of caseSensitive to help "matches" predicates too
// see https://github.com/bbyars/mountebank/issues/361
if (!cloned.keyCaseSensitive) {
cloned.jsonpath.selector = cloned.jsonpath.selector.toLowerCase();
}
return combinators.curry(selectJSONPath, cloned.jsonpath, options.encoding, config, stringTransform, logger);
}
else if (config.xpath) {
if (!cloned.caseSensitive) {
cloned.xpath.ns = transformObject(cloned.xpath.ns || {}, lowercase);
cloned.xpath.selector = cloned.xpath.selector.toLowerCase();
}
return combinators.curry(selectXPath, cloned.xpath, options.encoding);
}
else {
return combinators.identity;
}
}
function lowercase (text) {
return text.toLowerCase();
}
function caseTransform (config) {
return config.caseSensitive ? combinators.identity : lowercase;
}
function exceptTransform (config, logger) {
const exceptRegexOptions = config.caseSensitive ? 'g' : 'gi';
if (config.except) {
if (!safeRegex(config.except)) {
logger.warn(`If mountebank becomes unresponsive, it is because of this unsafe regular expression: ${config.except}`);
}
return text => text.replace(new RegExp(config.except, exceptRegexOptions), '');
}
else {
return combinators.identity;
}
}
function encodingTransform (encoding) {
if (encoding === 'base64') {
return text => Buffer.from(text, 'base64').toString();
}
else {
return combinators.identity;
}
}
function tryJSON (value, predicateConfig, logger) {
try {
const keyCaseTransform = predicateConfig.keyCaseSensitive === false ? lowercase : caseTransform(predicateConfig),
valueTransforms = [exceptTransform(predicateConfig, logger), caseTransform(predicateConfig)];
// We can't call normalize because we want to avoid the array sort transform,
// which will mess up indexed selectors like $..title[1]
return transformAll(JSON.parse(value), [keyCaseTransform], valueTransforms, []);
}
catch (e) {
return value;
}
}
// eslint-disable-next-line max-params
function selectJSONPath (config, encoding, predicateConfig, stringTransform, logger, text) {
const possibleJSON = stringTransform(tryJSON(text, predicateConfig, logger)),
selectFn = combinators.curry(jsonpath.select, config.selector, possibleJSON);
return orderIndependent(select('jsonpath', selectFn, encoding));
}
function transformAll (obj, keyTransforms, valueTransforms, arrayTransforms) {
const apply = fns => combinators.compose.apply(null, fns),
isObject = helpers.isObject;
if (Array.isArray(obj)) {
return apply(arrayTransforms)(obj.map(element => transformAll(element, keyTransforms, valueTransforms, arrayTransforms)));
}
else if (isObject(obj)) {
return Object.keys(obj).reduce((accumulator, key) => {
accumulator[apply(keyTransforms)(key)] = transformAll(obj[key], keyTransforms, valueTransforms, arrayTransforms);
return accumulator;
}, {});
}
else if (typeof obj === 'string') {
return apply(valueTransforms)(obj);
}
else {
return obj;
}
}
function normalize (obj, config, options, logger) {
// Needed to solve a tricky case conversion for "matches" predicates with jsonpath/xpath parameters
if (typeof config.keyCaseSensitive === 'undefined') {
config.keyCaseSensitive = config.caseSensitive;
}
const keyCaseTransform = config.keyCaseSensitive === false ? lowercase : caseTransform(config),
sortTransform = array => array.sort(sortObjects),
transforms = [];
if (options.withSelectors) {
transforms.push(selectTransform(config, options, logger));
}
transforms.push(exceptTransform(config, logger));
transforms.push(caseTransform(config));
transforms.push(encodingTransform(options.encoding));
// sort to provide deterministic comparison for deepEquals,
// where the order in the array for multi-valued querystring keys
// and xpath selections isn't important
return transformAll(obj, [keyCaseTransform], transforms, [sortTransform]);
}
function testPredicate (expected, actual, predicateConfig, predicateFn) {
if (!helpers.defined(actual)) {
actual = '';
}
if (helpers.isObject(expected)) {
return predicateSatisfied(expected, actual, predicateConfig, predicateFn);
}
else {
return predicateFn(expected, actual);
}
}
function bothArrays (expected, actual) {
return Array.isArray(actual) && Array.isArray(expected);
}
function allExpectedArrayValuesMatchActualArray (expectedArray, actualArray, predicateConfig, predicateFn) {
return expectedArray.every(expectedValue =>
actualArray.some(actualValue => testPredicate(expectedValue, actualValue, predicateConfig, predicateFn)));
}
function onlyActualIsArray (expected, actual) {
return Array.isArray(actual) && !Array.isArray(expected);
}
function expectedMatchesAtLeastOneValueInActualArray (expected, actualArray, predicateConfig, predicateFn) {
return actualArray.some(actual => testPredicate(expected, actual, predicateConfig, predicateFn));
}
function expectedLeftOffArraySyntaxButActualIsArrayOfObjects (expected, actual, fieldName) {
return !Array.isArray(expected[fieldName]) && !helpers.defined(actual[fieldName]) && Array.isArray(actual);
}
function predicateSatisfied (expected, actual, predicateConfig, predicateFn) {
if (!actual) {
return false;
}
// Support predicates that reach into fields encoded in JSON strings (e.g. HTTP bodies)
if (typeof actual === 'string') {
actual = tryJSON(actual, predicateConfig);
}
return Object.keys(expected).every(fieldName => {
const isObject = helpers.isObject;
if (bothArrays(expected[fieldName], actual[fieldName])) {
return allExpectedArrayValuesMatchActualArray(
expected[fieldName], actual[fieldName], predicateConfig, predicateFn);
}
else if (onlyActualIsArray(expected[fieldName], actual[fieldName])) {
if (predicateConfig.exists && expected[fieldName]) {
return true;
}
else {
return expectedMatchesAtLeastOneValueInActualArray(
expected[fieldName], actual[fieldName], predicateConfig, predicateFn);
}
}
else if (expectedLeftOffArraySyntaxButActualIsArrayOfObjects(expected, actual, fieldName)) {
// This is a little confusing, but predated the ability for users to specify an
// array for the expected values and is left for backwards compatibility.
// The predicate might be:
// { equals: { examples: { key: 'third' } } }
// and the request might be
// { examples: '[{ "key": "first" }, { "different": true }, { "key": "third" }]' }
// We expect that the "key" field in the predicate definition matches any object key
// in the actual array
return expectedMatchesAtLeastOneValueInActualArray(expected, actual, predicateConfig, predicateFn);
}
else if (isObject(expected[fieldName])) {
return predicateSatisfied(expected[fieldName], actual[fieldName], predicateConfig, predicateFn);
}
else {
return testPredicate(expected[fieldName], actual[fieldName], predicateConfig, predicateFn);
}
});
}
function create (operator, predicateFn) {
return (predicate, request, encoding, logger) => {
const expected = normalize(predicate[operator], predicate, { encoding: encoding }, logger),
actual = normalize(request, predicate, { encoding: encoding, withSelectors: true }, logger);
return predicateSatisfied(expected, actual, predicate, predicateFn);
};
}
function deepEquals (predicate, request, encoding, logger) {
const expected = normalize(forceStrings(predicate.deepEquals), predicate, { encoding: encoding }, logger),
actual = normalize(forceStrings(request), predicate, { encoding: encoding, withSelectors: true, shouldForceStrings: true }, logger),
isObject = helpers.isObject;
return Object.keys(expected).every(fieldName => {
// Support predicates that reach into fields encoded in JSON strings (e.g. HTTP bodies)
if (isObject(expected[fieldName]) && typeof actual[fieldName] === 'string') {
const possibleJSON = tryJSON(actual[fieldName], predicate);
actual[fieldName] = normalize(forceStrings(possibleJSON), predicate, { encoding: encoding }, logger);
}
return stringify(expected[fieldName]) === stringify(actual[fieldName]);
});
}
function matches (predicate, request, encoding, logger) {
// We want to avoid the lowerCase transform on values so we don't accidentally butcher
// a regular expression with upper case metacharacters like \W and \S
// However, we need to maintain the case transform for keys like http header names (issue #169)
// eslint-disable-next-line no-unneeded-ternary
const caseSensitive = predicate.caseSensitive ? true : false, // convert to boolean even if undefined
clone = helpers.merge(predicate, { caseSensitive: true, keyCaseSensitive: caseSensitive }),
noexcept = helpers.merge(clone, { except: '' }),
expected = normalize(predicate.matches, noexcept, { encoding: encoding }, logger),
actual = normalize(request, clone, { encoding: encoding, withSelectors: true }, logger),
options = caseSensitive ? '' : 'i';
if (encoding === 'base64') {
throw errors.ValidationError('the matches predicate is not allowed in binary mode');
}
return predicateSatisfied(expected, actual, clone, (a, b) => {
if (!safeRegex(a)) {
logger.warn(`If mountebank becomes unresponsive, it is because of this unsafe regular expression: ${a}`);
}
return new RegExp(a, options).test(b);
});
}
function not (predicate, request, encoding, logger, imposterState) {
return !evaluate(predicate.not, request, encoding, logger, imposterState);
}
function evaluateFn (request, encoding, logger, imposterState) {
return subPredicate => evaluate(subPredicate, request, encoding, logger, imposterState);
}
function or (predicate, request, encoding, logger, imposterState) {
return predicate.or.some(evaluateFn(request, encoding, logger, imposterState));
}
function and (predicate, request, encoding, logger, imposterState) {
return predicate.and.every(evaluateFn(request, encoding, logger, imposterState));
}
function inject (predicate, request, encoding, logger, imposterState) {
if (request.isDryRun === true) {
return true;
}
const config = {
request: helpers.clone(request),
state: imposterState,
logger: logger
};
compatibility.downcastInjectionConfig(config);
const injected = `(${predicate.inject})(config, logger, imposterState);`;
try {
return eval(injected);
}
catch (error) {
logger.error(`injection X=> ${error}`);
logger.error(` source: ${JSON.stringify(injected)}`);
logger.error(` config.request: ${JSON.stringify(config.request)}`);
logger.error(` config.state: ${JSON.stringify(config.state)}`);
throw errors.InjectionError('invalid predicate injection', { source: injected, data: error.message });
}
}
function toString (value) {
if (value !== null && typeof value !== 'undefined' && typeof value.toString === 'function') {
return value.toString();
}
else {
return value;
}
}
function contains (actual, expected) {
if (typeof actual === 'string') {
return actual.indexOf(expected) >= 0;
}
return actual.toString().indexOf(expected) >= 0;
}
function startsWith (actual, expected) {
if (typeof actual === 'string') {
return actual.indexOf(expected) === 0;
}
return actual.toString().indexOf(expected) === 0;
}
function endsWith (actual, expected) {
if (typeof actual === 'string') {
return actual.indexOf(expected, actual.length - expected.length) >= 0;
}
return actual.toString().indexOf(expected, actual.length - expected.length) >= 0;
}
const predicates = {
equals: create('equals', (expected, actual) => toString(expected) === toString(actual)),
deepEquals,
contains: create('contains', (expected, actual) => contains(actual, expected)),
startsWith: create('startsWith', (expected, actual) => startsWith(actual, expected)),
endsWith: create('endsWith', (expected, actual) => endsWith(actual, expected)),
matches,
exists: create('exists', function (expected, actual) {
return expected ? (typeof actual !== 'undefined' && actual !== '') : (typeof actual === 'undefined' || actual === '');
}),
not,
or,
and,
inject
};
/**
* Resolves all predicate keys in given predicate
* @param {Object} predicate - The predicate configuration
* @param {Object} request - The protocol request object
* @param {string} encoding - utf8 or base64
* @param {Object} logger - The logger, useful for debugging purposes
* @param {Object} imposterState - The current state for the imposter
* @returns {boolean}
*/
function evaluate (predicate, request, encoding, logger, imposterState) {
const predicateFn = Object.keys(predicate).find(key => Object.keys(predicates).indexOf(key) >= 0),
clone = helpers.clone(predicate);
if (predicateFn) {
return predicates[predicateFn](clone, request, encoding, logger, imposterState);
}
else {
throw errors.ValidationError('missing predicate', { source: predicate });
}
}
module.exports = { evaluate };