I am working on an API in Node/JavaScript with a MySQL database. I think this is a question not related to Node/JavaScript, just SQL, but I'm not sure about that.
Here I have a minimal example. Lets say I have a stored procedure to create an user:
DROP PROCEDURE IF EXISTS users_create;
CREATE PROCEDURE users_create(
IN user JSON
)
BEGIN
-- Retrieve values from JSON
SET @name = JSON_EXTRACT(user, '$.name');
SET @email = JSON_EXTRACT(user, '$.email');
SET @password = JSON_EXTRACT(user, '$.password');
SET @uuid = uuid();
-- Insert new user
INSERT INTO user (`id`, `name`, `email`, `password`) VALUES (
@uuid,
JSON_UNQUOTE(@name),
JSON_UNQUOTE(@email),
JSON_UNQUOTE(@password)
);
-- Retrieve created user
SELECT `id`, `name`, `email`, `status`, `createdAt` FROM user
WHERE id = @uuid;
END
Now I have a new user object —Javascript—:
const newUser = {
name: "This is me",
email: "me@example.com",
password: "strong_password",
}
And I call the procedure:
const createUserQuery = `CALL users_create('${JSON.stringify(newUser)}')`;
My question is: given that I'm using JSON to pass the data, and I'm using JSON_EXTRACT
and JSON_UNQUOTE
, am I prone to SQL injection here?
No, you are not prone to SQL injection. You might have other problems with the code. And your code might be unsafe if -- say -- the password is not encrypted.
However, the only SQL code that will run is the SQL in the stored procedure.
SQL injection is associated with dynamic SQL. That is SQL that is constructed from a string. A SQL injection account alters ("enhances"?) the string to do dangerous things. Your code is just assigning values in an insert
. These might be wrong, but they will not cause any other statements to run.