always check file checksum and ensure that in-url hash matches file contents. issue #31

This commit is contained in:
Lloyd Hilaiel 2013-04-24 16:59:13 -06:00
Родитель 9f879dc1c8
Коммит c9b04320ae
3 изменённых файлов: 31 добавлений и 5 удалений

Просмотреть файл

@ -67,6 +67,8 @@ exports.setup = function (assets, options) {
});
}
if (m && m.index === 0) {
// extract the hash
var hash = req.url.slice(prefix.length + 1, prefix.length + 11);
// 10 first characters of md5 + 1 for slash
var url = req.url.slice(prefix.length + 11);
var true_path = opts.url_to_paths[url] || path.join(opts.root, url);
@ -100,7 +102,17 @@ exports.setup = function (assets, options) {
}
}
}
if (exists === true) {
// determine actual current hash of the file, it's worth the disk
// read to ensure we never serve bogus resources and poison caches
// issue #31
var md5 = crypto.createHash('md5');
try {
md5.update(fs.readFileSync(true_path));
} catch(e) { }
var actualHash = md5.digest('hex').slice(0, 10);
if (exists === true && hash === actualHash) {
resp.setHeader('Cache-Control', 'public, max-age=31536000');
req.url = url;
if (opts.control_headers === true) {
@ -158,7 +170,6 @@ var hashify = function (resource, hash) {
var md5 = crypto.createHash('md5');
try {
var data = fs.readFileSync(filename);
md5.update(data);
// Expensive, maintain in-memory cache
if (! _cache[filename]) _cache[filename] = {exists: true};

Просмотреть файл

@ -34,7 +34,6 @@ function get_resp() {
this.state['header'] += 1;
},
on: function (name, cb) {
}
};
}
@ -236,7 +235,23 @@ exports.setup = nodeunit.testCase({
test.done();
});
},
"Production mode, mismatched checksum, not substituted": function (test) {
var assets = make_assets(),
req = {
url: '/e41d8cd98f/js/main.min.js'
},
resp = get_resp(),
mddlwr;
mddlwr = cachify.setup(
assets, {
root: '/tmp'
});
var before = req.url;
mddlwr(req, resp, function () {
test.ok(req.url == before);
test.done();
});
},
"Production - look up paths in url_to_paths table": function (test) {
var assets = make_assets(),
url_to_paths = {

Просмотреть файл

@ -77,7 +77,7 @@ exports.setup = nodeunit.testCase({
test.equal(resText, 'ok');
app.close ? app.close() : server.close();
if (1 === i) test.done();
});
});
});
req.end();
});