2023-03-07 17:16:47 +01:00
|
|
|
== How to fix it in Express.js
|
|
|
|
|
|
|
|
=== Code examples
|
2022-10-24 10:50:44 +02:00
|
|
|
|
|
|
|
:code_impact: read
|
2023-06-22 10:38:01 +02:00
|
|
|
|
2022-10-24 10:50:44 +02:00
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
|
|
|
|
==== Noncompliant code example
|
|
|
|
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
|
|
----
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
function (req, res) {
|
2023-08-07 16:18:28 +02:00
|
|
|
const targetDirectory = "/data/app/resources/";
|
2022-10-24 10:50:44 +02:00
|
|
|
const userFilename = path.join(targetDirectory, req.query.filename);
|
|
|
|
|
|
|
|
res.sendFile(userFilename); // Noncompliant
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
|
|
----
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
function (req, res) {
|
|
|
|
const targetDirectory = "/data/app/resources/";
|
|
|
|
const userFilename = req.query.filename;
|
|
|
|
|
|
|
|
res.sendFile(userFilename, { root: targetDirectory });
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
=== How does this work?
|
|
|
|
|
|
|
|
:auto_canonicalization_function: res.sendFile() (used with options.root)
|
|
|
|
|
|
|
|
include::../../common/fix/function-based-validation.adoc[]
|
|
|
|
|
|
|
|
include::../../common/fix/self-validation.adoc[]
|
2022-11-08 10:13:52 +01:00
|
|
|
|
|
|
|
=== Pitfalls
|
|
|
|
|
|
|
|
:joining_docs: https://nodejs.org/api/path.html#pathresolvepaths
|
|
|
|
:joining_func: path.resolve
|
2023-06-22 10:38:01 +02:00
|
|
|
|
2022-11-08 10:13:52 +01:00
|
|
|
include::../../common/pitfalls/path-joining.adoc[]
|
|
|
|
|
|
|
|
|