Skip to content

Commit

Permalink
Properly handle requests with malformed URIs (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
leo authored Jul 3, 2018
1 parent cd2c068 commit 361d2e4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -490,15 +490,26 @@ module.exports = async (request, response, config = {}, methods = {}) => {
const cwd = process.cwd();
const current = config.public ? path.join(cwd, config.public) : cwd;
const handlers = getHandlers(methods);
const relativePath = decodeURIComponent(url.parse(request.url).pathname);

let absolutePath = path.join(current, relativePath);
let relativePath = null;
let acceptsJSON = null;

if (request.headers.accept) {
acceptsJSON = request.headers.accept.includes('application/json');
}

try {
relativePath = decodeURIComponent(url.parse(request.url).pathname);
} catch (err) {
return sendError(response, acceptsJSON, current, handlers, config, {
statusCode: 400,
code: 'bad_request',
message: 'Bad Request'
});
}

let absolutePath = path.join(current, relativePath);

// Prevent path traversal vulnerabilities. We could do this
// by ourselves, but using the package covers all the edge cases.
if (!isPathInside(absolutePath, current)) {
Expand Down
16 changes: 16 additions & 0 deletions test/integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -956,3 +956,19 @@ test('allow dots in `public` configuration property', async t => {
t.is(response.status, 200);
t.is(content, text);
});

test('error for request with malformed URI', async t => {
const url = await getUrl();
const response = await fetch(`${url}/%E0%A4%A`);
const text = await response.text();

t.is(response.status, 400);

const content = errorTemplate({
statusCode: 400,
message: 'Bad Request'
});

t.is(text, content);
});

0 comments on commit 361d2e4

Please sign in to comment.