Search code examples
sqlnode.jspostgresqlsql-injection

Is this parameterized query open to SQL injection?


Someone looking at my code said that the SQL query below (SELECT * FROM...) was obviously open to attack. I have researched this and it seems I'm doing this correctly by using a parameterized query, but clearly I'm missing something.

app.get("/api/v1/:userId", async (req, res) => {
    try {
        const teammate = await db.query("SELECT * FROM teammates WHERE uid = $1", [
            req.params.userId,
        ]);

Solution

  • This query is not open to SQL injection, because it uses a parameterized query. The data is not substituted for the parameter ($1), but sent separately in a “bind” message, so no matter what the data contain, it is not interpreted as part of the SQL statement.

    Moreover, it looks like the argument is an integer, and SQL injection can only happen with string arguments.