SQL injection in Go
How GORM protects you, and how Sprintf undoes that protection.
Go and GORM make SQL injection hard to write by accident. They do not make it impossible, and the places it still gets in are specific and worth memorising, because they are the places where a parameter is not allowed and people reach for string concatenation instead.
The ordinary path is already safe
Every value you pass through a placeholder is sent to the database separately from the statement. The driver never builds one string out of both, so there is nothing for a quote to break out of:
// Safe. The ? is a bind parameter; the value never touches the SQL text.db.Where("title = ?", userInput).Find(&posts)// Safe for the same reason.db.Where(&models.Post{Title: userInput}).Find(&posts)// Also safe: Raw with placeholders is still parameterised.db.Raw("SELECT * FROM posts WHERE title = ?", userInput).Scan(&posts)
So Raw is not the villain. Concatenation is. The two get conflated, and the result is teams that ban Raw and then build strings somewhere else.
// Injectable. The value is part of the statement.db.Where("title = '" + userInput + "'").Find(&posts)// Injectable, and harder to spot in review because it looks formatted.db.Raw(fmt.Sprintf("SELECT * FROM posts WHERE title = '%s'", userInput)).Scan(&posts)
fmt.Sprintf next to SQL is the single highest-signal thing to grep for in a Go codebase. It is almost never the right way to put a value into a query.
Where it actually gets in: identifiers
A placeholder works for values. It does not work for column names, table names, or the direction of a sort, because those are part of the statement's structure rather than its data. The database will not accept ORDER BY ?.
Which means any feature that lets the caller choose a sort column or a filter field has to build SQL from input. That is the real injection surface in a modern Go app, and it is in almost every list endpoint ever written:
sortBy := c.Query("sort") // "created_at" ... or anythingdb.Order(sortBy).Find(&posts) // and now they choose the SQL
The fix is not escaping. It is an allow list, because you know the complete set of sortable columns and the caller does not get to invent one:
var sortable = map[string]string{"created": "created_at","title": "title","views": "view_count",}column, ok := sortable[c.Query("sort")]if !ok {column = "created_at"}dir := "ASC"if strings.EqualFold(c.Query("dir"), "desc") {dir = "DESC"}db.Order(column + " " + dir).Find(&posts)
Note what makes this safe: the strings that reach the query areyours. The caller's input is only ever used to pick one. An allow list fails closed, and it also gives you a stable public name for a column you may want to rename later.
Grit's generated list endpoints already do this, with the sortable set derived from the resource definition. The risk is in the endpoint you hand-write next to them, where the habit of the generated code does not automatically follow.
The other three
- LIKE.
Where("title LIKE ?", "%"+q+"%")is parameterised and safe from injection, but%and_in the input are still wildcards. A search for%matches everything, which is a performance problem rather than a breach. - IN with a slice.
Where("id IN ?", ids)is safe. Building the list by joining strings is not. - Migrations and admin tooling. The code that genuinely needs dynamic identifiers. It usually runs with the widest database privileges in the system, so it is the worst place to take a shortcut.
Try it
One. Add a sort parameter to a list endpoint the unsafe way, passing c.Query("sort") straight to Order.
Two. Call it with ?sort=(CASE WHEN (SELECT COUNT(*) FROM users) > 0 THEN title ELSE id END). It is a legal expression, so it sorts. Confirm it does, and note that you just ran a subquery the endpoint never offered.
Three. Replace it with an allow list. Try the same input and confirm it falls back to the default.
Quick check
Spot a typo? Have an idea?
Help us improve this lesson. One click opens a GitHub issue with the lesson URL pre-filled, suggest clearer wording, report a bug, or request more depth. The course keeps improving thanks to learners like you.
Suggest an improvement on GitHub