Skip to content

Commit c42b270

Browse files
committed
Ensure deeply nested objects are sanitized properly. Fixes #2
1 parent 1df4fc5 commit c42b270

File tree

2 files changed

+38
-7
lines changed

2 files changed

+38
-7
lines changed

index.js

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ var withEach = function(target, cb) {
1111
} else if(obj instanceof Object) {
1212
Object.keys(obj).forEach(function(key) {
1313
var val = obj[key];
14-
var shouldRecurse = cb(obj, val, key);
15-
if(shouldRecurse) {
16-
act(obj[key]);
14+
var resp = cb(obj, val, key);
15+
if(resp.shouldRecurse) {
16+
act(obj[resp.key || key]);
1717
}
1818
});
1919
}
@@ -27,9 +27,9 @@ var has = function(target) {
2727
withEach(target, function(obj, val, key) {
2828
if(TEST_REGEX.test(key)) {
2929
hasProhibited = true;
30-
return false;
30+
return { shouldRecurse: false };
3131
} else {
32-
return true;
32+
return { shouldRecurse: true };
3333
}
3434
});
3535

@@ -50,13 +50,17 @@ var sanitize = function(target, options) {
5050
if(TEST_REGEX.test(key)) {
5151
delete obj[key];
5252
if(replaceWith) {
53-
obj[key.replace(REPLACE_REGEX, replaceWith)] = val;
53+
key = key.replace(REPLACE_REGEX, replaceWith);
54+
obj[key] = val;
5455
} else {
5556
shouldRecurse = false;
5657
}
5758
}
5859

59-
return shouldRecurse;
60+
return {
61+
shouldRecurse: shouldRecurse,
62+
key: key
63+
};
6064
});
6165

6266
return target;

test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,33 @@ describe('Express Mongo Sanitize', function() {
345345
}, done);
346346
});
347347
});
348+
349+
describe('Nested Object inside one with prohibited chars', function() {
350+
it('should sanitize a nested object inside one with prohibited chars in a JSON body', function(done) {
351+
request(app)
352+
.post('/body')
353+
.send({
354+
username: {
355+
$gt: 'foo',
356+
'dotted.data': {
357+
'more.dotted.data': 'some_data'
358+
}
359+
}
360+
})
361+
.set('Content-Type', 'application/json')
362+
.set('Accept', 'application/json')
363+
.expect(200, {
364+
body: {
365+
username: {
366+
_gt: 'foo',
367+
dotted_data: {
368+
'more_dotted_data': 'some_data'
369+
}
370+
}
371+
}
372+
}, done);
373+
});
374+
});
348375
});
349376

350377
describe('Preserve Data: prohibited characters', function() {

0 commit comments

Comments
 (0)