I'm using ActiveRecord::Base.connection.execute to insert data to database. After running brakeman report I get this warning : "Possible SQL injection"
sql = "INSERT INTO `students` (`student_id`,`level') VALUES (1, #{Student.get_level_name(1)});"
ActiveRecord::Base.connection.execute sql
And tried a couple of other stuff which didn't work not even worth mentioning. Does anybody have an idea how to fix this?
The problem is the interpolation you're doing to create the statement.
".. (1, #{Student.get_level_name(1)});"
Despite Brakeman doesn't know where that value is coming from if you pass any value there, you're vulnerable to SQLi.
That's why you should be using ActiveRecord to handle database inserts. It allows you to pass the values for the records and it deals with the bindings and sanitization:
INSERT INTO "students" ("student_id", "created_at", "updated_at")
VALUES ($1, $2, $3)
RETURNING "id"
[["student_id", "1"], ["created_at", "2019-09-27 07:06:57.198752"], ["updated_at", "2019-09-27 07:06:57.198752"]]
There you can see ($1, $2, $3)
correspondingly as the "student_id", "created_at", "updated_at" values, which aren't passed in RAW form to your query (timestamps are generated automatically if you added them).
So, for the insert:
Student.create(student_id: 1, level: Student.get_level_name(1))