Sub topic 4
Fixing injection with bind variables
This chapter assumes you can write static SOQL, read basic Apex classes, and know that Database.query runs a query string at run time. The previous chapter showed how a quote in user input can rewrite a concatenated query. Here you fix it.
Why binds stop the attack
SOQL injection works because user input and query structure share one string. The parser cannot tell where your code ends and the attacker's text begins.
A bind variable separates the two. You write a placeholder such as :name in the query text, and Apex supplies the value of the variable name when the query runs. The value is treated as data. It is never parsed as SOQL, so a quote inside it cannot close a string literal.
The fix
Here is the vulnerable version from the last chapter, followed by the fixed one.
public with sharing class AccountSearch {
// VULNERABLE: input becomes part of the query text.
public static List<Account> findByNameUnsafe(String name) {
String soql = 'SELECT Id, Name FROM Account WHERE Name = \'' + name + '\'';
return Database.query(soql);
}
// SAFE: :name is a bind variable.
public static List<Account> findByName(String name) {
return Database.query('SELECT Id, Name FROM Account WHERE Name = :name');
}
}In the safe version, the payload ' OR Name != ' is compared as a literal account name. No account has that name, so the query returns no rows.
Notice what changed. The query string is now a constant. Nothing the user types ever reaches it.
How Apex resolves the bind
Database.query looks for a variable named name in the scope of the method that calls it. This explains the most common mistakes.
- No quotes around the placeholder. Write
Name = :name, notName = ':name'. With quotes, the query compares against the literal text:name. - The variable must be in scope. If you build the string in one method and call
Database.queryin another, the second method has nonamevariable. The query fails at run time with a "Variable does not exist" error. - Use plain variables. Binding to a local variable or a method parameter works reliably. Do not rely on expressions such as
:acc.Namein dynamic queries. Copy the value into a local variable first. - Names are not case sensitive.
:Nameand:namerefer to the same variable, so avoid two variables whose names differ only by case.
Binding collections
A bind can hold a list or set, which you use with IN. This is the safe way to filter on many values.
public static List<Account> findByIds(Set<Id> accountIds) {
return Database.query('SELECT Id, Name FROM Account WHERE Id IN :accountIds');
}
public static List<Account> findByIndustries(List<String> industries) {
return Database.query(
'SELECT Id, Name FROM Account WHERE Industry IN :industries LIMIT 100'
);
}Do not build IN ('a','b') by joining strings. That reintroduces the problem you just fixed.
Combining binds with conditions built at run time
Dynamic SOQL is often needed because the set of filters varies. You can still add conditions conditionally, as long as the text you append is fixed code and the values are binds.
public static List<Account> search(String name, String industry) {
String soql = 'SELECT Id, Name FROM Account WHERE IsDeleted = false';
if (String.isNotBlank(name)) {
soql += ' AND Name = :name';
}
if (String.isNotBlank(industry)) {
soql += ' AND Industry = :industry';
}
soql += ' LIMIT 50';
return Database.query(soql);
}Every string appended here is a literal written by you. The user controls only the values of name and industry.
What binds do not do
Binds remove injection through values. They do not enforce sharing, field-level security, or object permissions. They also do not stop a user from typing % or _ into a LIKE search, since these are wildcards in the value itself. Later chapters cover both topics.
Exercise
A developer writes Database.query('SELECT Id FROM Contact WHERE LastName = \':lastName\''). A user searches for Smith, and the query returns no rows even though Smith exists. What is wrong, and how do you fix it?
Show answer
The placeholder is wrapped in quotes, so SOQL compares LastName to the literal text :lastName instead of using the variable. Remove the quotes: Database.query('SELECT Id FROM Contact WHERE LastName = :lastName'). Make sure lastName is a variable in scope in the method that calls Database.query.
Exercise
Why is Database.query('SELECT Id FROM Account ORDER BY :sortField') not a valid fix for a user-chosen sort column?
Show answer
Bind variables supply values only. A field name is part of the query structure, so it cannot be bound. You must check the sort field against a fixed allowlist and then place the approved name in the query string.