Skip to content

Commit

Permalink
fix(express): handle invalid chars in host header
Browse files Browse the repository at this point in the history
  • Loading branch information
david-luna committed Mar 19, 2024
1 parent 9b031ff commit ed46578
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/instrumentation/express-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,23 @@ function getPathFromRequest(req, useBase, usePathAsTransactionName) {
//
// Assuming 'http://' for the `base` URL is fine, because we don't use the
// protocol.
const base = 'http://' + (req.headers && req.headers.host);
let base;
try {
// Host header may contain invalid characters therefore the URL
// parsing will fail and break the app. This try block is to avoid it
// Ref: https://github.com/elastic/apm-agent-nodejs/issues/3874
const url = new url.URL('http://' + (req.headers && req.headers.host));
base = 'http://' + url.hostname;
} catch (err) {
base = 'http://undefined';
}

// We may receive invalid chars in the path also but the URL
// constructor escapes them without throwing.
const parsed = req.url.startsWith('/')
? new url.URL(base + req.url)
: new url.URL(req.url, base);

return parsed && parsed.pathname;
}
}
Expand Down
11 changes: 11 additions & 0 deletions test/instrumentation/express-utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ test('#getPathFromRequest', function (t) {
t.equals(path, '/foo/bar');
t.end();
});

t.test('should return path for an invalid host header', function (t) {
const req = createRequest(
'https://test.com/foo/bar?query=value#hash',
// eslint-disable-next-line prettier/prettier, no-useless-escape
'invalid\host\name',
);
const path = getPathFromRequest(req, false, true);
t.equals(path, '/foo/bar');
t.end();
});
});

function createRequest(url, host = 'example.com') {
Expand Down

0 comments on commit ed46578

Please sign in to comment.