diff --git a/CHANGELOG.asciidoc b/CHANGELOG.asciidoc index c7d2cb9c32..3845bbb410 100644 --- a/CHANGELOG.asciidoc +++ b/CHANGELOG.asciidoc @@ -33,6 +33,25 @@ Notes: See the <> guide. +==== Unreleased + +[float] +===== Breaking changes + +[float] +===== Features + +[float] +===== Bug fixes + +* Fix path resolution for requests that contain invalid characters in its + host header. ({pull}3923[#3923]) +* Fix span names for `getMore` command of mongodb. ({pull}3919[#3919]) + +[float] +===== Chores + + [[release-notes-4.5.0]] ==== 4.5.0 - 2024/03/13 @@ -46,7 +65,6 @@ See the <> guide. [float] ===== Bug fixes -* Fix span names for `getMore` command of mongodb. ({pull}3919[#3919]) * Fix instrumentation of mongodb to not break mongodb@6.4.0. Mongodb v6.4.0 included changes that resulted in the APM agent's instrumentation breaking it. ({pull}3897[#3897]) diff --git a/lib/instrumentation/express-utils.js b/lib/instrumentation/express-utils.js index 0a2edb6520..fb82e47c35 100644 --- a/lib/instrumentation/express-utils.js +++ b/lib/instrumentation/express-utils.js @@ -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; } } diff --git a/test/instrumentation/express-utils.test.js b/test/instrumentation/express-utils.test.js index 3917d13284..50e563e6e8 100644 --- a/test/instrumentation/express-utils.test.js +++ b/test/instrumentation/express-utils.test.js @@ -26,6 +26,16 @@ 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', + 'invalid[hostname', + ); + const path = getPathFromRequest(req, false, true); + t.equals(path, '/foo/bar'); + t.end(); + }); }); function createRequest(url, host = 'example.com') {