node-restify
node-restify copied to clipboard
fix: handle trailing slashes on root route and avoid crashes due to `AssertionError`s thrown by odd requests
Pre-Submission Checklist
- [x] Opened an issue discussing these changes before opening the PR
- [x] Ran the linter and tests via
make prepush - [x] Included comprehensive and convincing tests for changes
Issues
Closes:
- Issue #1959
- Issue #1953
Summarize the issues that discussed these changes
The issues demonstrate how restify can crash the node process when using server.pre(restify.pre.sanitizePath()) and a request with trailing slashes on root is received. I experienced this via intruder.io scanning against my production API application that uses restify. Please see the repro case here as referenced in #1959.
Changes
What does this PR do?
This PR makes 3 basic changes, each with at least one new unit test:
-
Changes the
sanitizePathmiddleware in lib/plugins/pre/prePath.js to return a root url (/) instead of an empty string in the case where the actual url consists of more than one slash e.g.//or///. This helps avoid numbers 2 and 3 below. -
Changes the
lookupmethod in lib/router.js to returnundefinedwhenreq.getUrl().pathnameis falsy. This helps avoid callingthis._registry.lookup(req.method, pathname)which will result in anAssertionErrorin the case that thepathnameis falsy, for whatever reason. -
Changes the
defaultRoutemethod in lib/router.js to expect/handle a falsypathnameby skipping registry lookup (which would throw anAssertionError) and raising the standardResourceNotFoundError(which results in 404 response) with the message "Requested path does not exist". This, along with number 2, allows restify to gracefully handle a falsypathnamefor whatever reason.
All changes are covered by unit tests, namely:
sanitizePathin test/plugins/plugins.test.jsGH-1959: lookup returns undefined when no handler foundin test/router.test.jsGH-1959: route handles 404 when pathname invalidin test/router.test.js
This is an attempt to make restify more robust and avoid crashes due to odd requests, if possible.
Please let me know if you have any questions or if you'd like me to change anything. Thanks!