Path traversal
A path traversal attack aims to access files and folders outside of the root folder of the project when these should not be accessible at all. This is done by trying to traverse the folder structure with for instance ../ sequences and absolute file paths. When a user for instance has ../logs as input (https://my-blog.com/posts?category=../logs), it would cause the application to read the filepath ../logs. If we were to have a folder called logs at that level, users would be able access that folder and all the files inside.
Solution - encodeURIComponent
encodeURIComponent encodes special characters. User input should always be encoded in the backend. For instance
`https://my-blog-api.com/v1/posts?category=${encodeURIComponent(userInput)}`
assuming the userInput is ../logs, this would return
https://my-blog-api.com/v1/posts?category=..%2Flogs
The user input is now encoded and thus the endpoint is safe from malicious input.
Encoding our URI components by overriding the resolveUrl
If an API uses a RESTDataSource (for instance with Apollo REST Data Source) it's possible to override the resolveUrl function. This allows us to encode the URI components in our function, thus we would not have to worry about it in the resolvers themselves.
An example of such a function (credits to Wout):
resolveURL(req) {
const { path } = req;
const urlParams = req.urlParams || {};
const newPath = Object.keys(urlParams).reduce((acc, param) => {
return acc.replace(`:${param}/`, `${encodeURIComponent(urlParams[param])}/`);
}, path);
return super.resolveURL({ ...req, path: newPath });
}