我正在尝试为以下中间件编写一个测试,以防止JSON漏洞:
/**
* JSON vulnerability protection - prepend the data with ")]},\n",
*/
function protectJSON(req, res, next) {
res.send = (...args) => _prependAndSend(res, args);
return next();
}
module.exports = {
protectJSON,
};
function _prependAndSend(res, args) {
let body = args[0];
const statusCode = args[1];
const contentType = res.getHeader('Content-Type');
// EDIT: added _send
const _send = res.send;
console.log('body', JSON.stringify(body));
if (contentType && contentType.indexOf('application/json') !== -1) {
_send.call(res, `)]}',\n${body}`);
} else {
_send.apply(res, args);
}
}所以我写了下面的测试,但当我运行它时,我有一个疯狂的循环(res.send被无休止地调用)。
describe('Test suite for middlewares.protectJSON', () => {
let nextMock;
let responseStub;
beforeEach(() => {
nextMock = sinon.stub();
responseStub = {
getHeader: sinon.stub(),
};
});
it('should not prefix content type other than json', () => {
protectJSON(null, responseStub, nextMock);
responseStub.send({ data: 'test' });
expect(responseStub.send).to.have.been.calledWith( data: 'test' });
});
});当我运行测试时,我得到
body {"data":"test-data"}
body {"data":"test-data"}
body {"data":"test-data"}
body {"data":"test-data"}
// more logging
body {"data":"test-data"}我不知道为什么它会为了修复它而表现成这样。感谢您的帮助。
发布于 2018-03-13 02:15:31
修复了它
function protectJSON(req, res, next) {
const _send = res.send;
res.send = (...args) => _prependAndSend(res, _send, args);
return next();
}基本上,我从_prependAndSend方法中删除了_send的声明,而是在protectJSON方法中声明它,然后将其作为参数传递给prependAndSend方法。
function _prependAndSend(res, _send, args) {
let body = args[0];
const statusCode = args[1];
const contentType = res.getHeader('Content-Type');
if (contentType && contentType.indexOf('application/json') !== -1) {
_send.call(res, `)]}',\n${body}`);
} else {
_send.apply(res, args);
}
}https://stackoverflow.com/questions/49162786
复制相似问题