Skip to content

Commit 7d801e0

Browse files
committed
add an example of using dollar eq
1 parent e24b45b commit 7d801e0

File tree

3 files changed

+33
-8
lines changed

3 files changed

+33
-8
lines changed

javascript/ql/src/Security/CWE-089/SqlInjection.inc.qhelp

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,16 @@ object, so this code is vulnerable to a NoSQL injection attack.
6969
<sample src="examples/NoSqlInjection.js" />
7070

7171
<p>
72-
To fix this vulnerability, we can check that the user input is a
73-
literal value and not a query object before using it in a query.
72+
To fix this vulnerability we can use the <code>$eq</code> operator
73+
to ensure that the user input is interpreted as a literal value
74+
and not as a query object:
75+
</p>
76+
77+
<sample src="examples/NoSqlInjectionFix2.js" />
78+
79+
<p>
80+
Alternatively check that the user input is a
81+
literal value and not a query object before using it:
7482
</p>
7583

7684
<sample src="examples/NoSqlInjectionFix.js" />

javascript/ql/src/Security/CWE-089/examples/NoSqlInjectionFix.js

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,7 @@ app.use(express.urlencoded({ extended: false }));
1111

1212
app.delete("/api/delete", async (req, res) => {
1313
let id = req.body.id;
14-
if (typeof id !== "string") {
15-
res.status(400).json({ status: "error" });
16-
return;
17-
}
18-
await Todo.deleteOne({ _id: id }); // GOOD: id is guaranteed to be a string
14+
await Todo.deleteOne({ _id: { $eq: id } }); // GOOD: using $eq operator for the comparison
1915

2016
res.json({ status: "ok" });
21-
});
17+
});
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const express = require("express");
2+
const mongoose = require("mongoose");
3+
const Todo = mongoose.model(
4+
"Todo",
5+
new mongoose.Schema({ text: { type: String } }, { timestamps: true })
6+
);
7+
8+
const app = express();
9+
app.use(express.json());
10+
app.use(express.urlencoded({ extended: false }));
11+
12+
app.delete("/api/delete", async (req, res) => {
13+
let id = req.body.id;
14+
if (typeof id !== "string") {
15+
res.status(400).json({ status: "error" });
16+
return;
17+
}
18+
await Todo.deleteOne({ _id: id }); // GOOD: id is guaranteed to be a string
19+
20+
res.json({ status: "ok" });
21+
});

0 commit comments

Comments
 (0)