Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/middlewares/csp.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,12 @@ module.exports = options => {
}
}
const headerString = bufArray.join(';');
ctx.set(finalHeader, headerString);
ctx.set('x-csp-nonce', ctx.nonce);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

应该在设置 nonce 的时候做参数校验逻辑,而不是在响应返回的时候,这个时机太晚了


if (!utils.checkInvalidHeaderChar(headerString)) {
ctx.set(finalHeader, headerString);
ctx.set('x-csp-nonce', ctx.nonce);
} else {
console.warn('Invalid character in header content :', finalHeader);
}
};
};
6 changes: 6 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,9 @@ function getContains(ip) {
}
return IP.cidrSubnet(ip).contains;
}

const HEADER_CHAR_REGEX = /[^\t\x20-\x7e\x80-\xff]/;

exports.checkInvalidHeaderChar = function(val) {
return HEADER_CHAR_REGEX.test(val);
};
13 changes: 13 additions & 0 deletions test/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,4 +251,17 @@ describe('test/utils.test.js', function() {
});
});
});

describe('utils.checkInvalidHeaderChar', function() {
it('Invalid character return true', function() {
utils.checkInvalidHeaderChar('aaaaa\naaaaaa').should.equal(true);
utils.checkInvalidHeaderChar('aaaa\raaaaa').should.equal(true);
});

it('character return false', function() {
utils.checkInvalidHeaderChar('aaaaa').should.equal(false);
utils.checkInvalidHeaderChar('aaaa aaaaa').should.equal(false);
utils.checkInvalidHeaderChar('aaaaaaaaa').should.equal(false);
});
});
});