Skip to content

Commit

Permalink
Improve reliability of the test server
Browse files Browse the repository at this point in the history
- replace // with /
  (otherwise http://localhost:8888// links to e.g. http://src/ instead
   of http://localhost:8888/src).

- Solve XSS issue (file names should be sanitized, not output as-is).

- Prevent server from crashing if there is a stat error (e.g. permission
  error or file not found (e.g. broken symlink).
  • Loading branch information
Rob--W committed Nov 6, 2015
1 parent 2096a2a commit 027483a
Showing 1 changed file with 38 additions and 14 deletions.
52 changes: 38 additions & 14 deletions test/webserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ WebServer.prototype = {
this.server = null;
},
_handler: function (req, res) {
var url = req.url;
var url = req.url.replace(/\/\//g, '/');
var urlParts = /([^?]*)((?:\?(.*))?)/.exec(url);
var pathPart = decodeURI(urlParts[1]), queryPart = urlParts[3];
var verbose = this.verbose;
Expand Down Expand Up @@ -158,6 +158,17 @@ WebServer.prototype = {
serveRequestedFile(filePath);
}

function escapeHTML(untrusted) {
// Escape untrusted input so that it can safely be used in a HTML response
// in HTML and in HTML attributes.
return untrusted
.replace(/&/g, '&ampl;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}

function serveDirectoryIndex(dir) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
Expand All @@ -180,21 +191,34 @@ WebServer.prototype = {
res.write('<a href=\"..\">..</a><br>\n');
}
files.forEach(function (file) {
var stat = fs.statSync(path.join(dir, file));
var stat;
var item = pathPart + file;
if (stat.isDirectory()) {
res.write('<a href=\"' + encodeURI(item) + '\">' +
file + '</a><br>\n');
return;
var href = '';
var label = '';
var extraAttributes = '';
try {
stat = fs.statSync(path.join(dir, file));
} catch (e) {
href = item;
label = file + ' (' + e + ')';
extraAttributes = ' style="color:red"';
}
if (stat) {
if (stat.isDirectory()) {
href = item;
label = file;
} else if (path.extname(file).toLowerCase() === '.pdf') {
href = '/web/viewer.html?file=' + encodeURIComponent(item);
label = file;
extraAttributes = ' target="pdf"';
} else if (all) {
href = item;
label = file;
}
}
var ext = path.extname(file).toLowerCase();
if (ext === '.pdf') {
res.write('<a href=\"/web/viewer.html?file=' +
encodeURI(item) + '\" target=pdf>' +
file + '</a><br>\n');
} else if (all) {
res.write('<a href=\"' + encodeURI(item) + '\">' +
file + '</a><br>\n');
if (label) {
res.write('<a href=\"' + escapeHTML(encodeURI(href)) + '\"' +
extraAttributes + '>' + escapeHTML(label) + '</a><br>\n');
}
});
if (files.length === 0) {
Expand Down

0 comments on commit 027483a

Please sign in to comment.