Sub topic 4
Fixing Injection with Bind Variables
What this chapter assumes
You should be able to read and write static SOQL and basic Apex classes. You should know what Database.query does and why concatenating user input into a query string is dangerous. The previous chapter showed the attack. This chapter shows the main fix.
By the end you will be able to:
- Explain why a bind variable stops injection.
- Rewrite a concatenated query to use bind variables.
- Bind strings, numbers, dates, and collections.
- Recognize what a bind variable cannot protect.
Why binding works
SOQL injection works because user input and query structure travel in the same string. The parser cannot tell where your code ends and the attacker's text begins. A quote in the input closes your string literal, and the rest of the input is parsed as query syntax.
A bind variable separates the two. You write a placeholder such as :name in the query text. Apex reads the value of the local variable name at run time and passes it to the query engine as data. The engine never parses that value as SOQL. If name contains ' OR Name != ', the engine looks for an account whose name is literally that text.
Here is the same idea as a diagram.
Rewriting the vulnerable query
This is the vulnerable version from the earlier chapter:
public with sharing class AccountSearch {
// VULNERABLE: user input is concatenated into the query string.
public static List<Account> findByName(String name) {
String soql = 'SELECT Id, Name FROM Account WHERE Name = \'' + name + '\'';
return Database.query(soql);
}
}The fix has two changes. Remove the quotes around the value, because a bound value needs no quoting. Replace the concatenation with :name.
public with sharing class AccountSearch {
public static List<Account> findByName(String name) {
return Database.query('SELECT Id, Name FROM Account WHERE Name = :name');
}
}The query string is now a constant. No caller can change it. Only the value of name varies, and the engine treats it as a value.
Static SOQL does the same thing when you write [SELECT Id FROM Account WHERE Name = :name]. Dynamic SOQL has the same protection if you use the same syntax inside the string.
How Apex finds the variable
Apex resolves each :placeholder when Database.query runs. It looks for a local variable or method parameter with that name in the scope of the method that makes the call.
This has some consequences:
- The variable must be declared in the method that calls
Database.query. A variable in another method or in a caller is not visible. If it is missing, the call throws aQueryExceptionwith a message likeVariable does not exist: name. - A simple variable name works. Dynamic SOQL does not support binding to a field of an object, such as
:acct.Name. Copy the value into a local variable first. - Names are not case sensitive, in the same way as other Apex identifiers.
- The query text can be built in a separate method and returned as a string. The bind variables are still read from the scope where
Database.queryis called.
public with sharing class ContactSearch {
public static List<Contact> byAccountName(Account filter) {
// :filter.Name is not supported in dynamic SOQL, so copy the value out.
String accountName = filter.Name;
return Database.query(
'SELECT Id, LastName FROM Contact WHERE Account.Name = :accountName'
);
}
}Binding more than strings
Bind variables accept the same types you would use in static SOQL. The value keeps its type, so the engine compares dates as dates and numbers as numbers.
public with sharing class OpportunitySearch {
public static List<Opportunity> find(
String stage,
Decimal minAmount,
Set<Id> accountIds,
Integer maxRows
) {
return Database.query(
'SELECT Id, Name, Amount FROM Opportunity ' +
'WHERE StageName = :stage ' +
'AND Amount >= :minAmount ' +
'AND AccountId IN :accountIds ' +
'LIMIT :maxRows'
);
}
}Points to notice:
IN :accountIdsaccepts aSetorList. This is the safe way to filter on many values. Do not buildIN ('a','b')by joining strings.LIMIT :maxRowstakes anInteger. A value from a request parameter should be converted toIntegerfirst. The next chapters cover that conversion.- Numbers, dates, and Booleans are not quoted in the query text. The placeholder alone is enough.
Building optional filters
Search forms often have optional fields. You can still keep the user's values out of the query text. Concatenate only fixed fragments that you wrote, and put every user value behind a placeholder.
public with sharing class ContactFilter {
public static List<Contact> search(String lastName, Date createdAfter) {
Datetime createdFrom = createdAfter == null
? null
: Datetime.newInstance(createdAfter, Time.newInstance(0, 0, 0, 0));
List<String> clauses = new List<String>();
if (String.isNotBlank(lastName)) {
clauses.add('LastName = :lastName');
}
if (createdFrom != null) {
clauses.add('CreatedDate >= :createdFrom');
}
String soql = 'SELECT Id, LastName FROM Contact';
if (!clauses.isEmpty()) {
soql += ' WHERE ' + String.join(clauses, ' AND ');
}
soql += ' LIMIT 100';
return Database.query(soql);
}
}Both variables are declared in the method, so they are in scope even when the query text does not mention them. Every string added to clauses is a literal that you wrote. This is the pattern to follow for any dynamic query. The text may vary, but only between fragments that you control.
What a bind variable does not protect
A bind variable replaces a value. It cannot replace other parts of a query. A placeholder is not allowed where SOQL expects a keyword or a name.
| Query part | Can you bind it? | What to do instead |
|---|---|---|
| Value in a `WHERE` comparison | Yes | Use `:variable` |
| Collection in `IN` | Yes | Use `IN :collection` |
| `LIMIT` and `OFFSET` count | Yes | Bind an `Integer` |
| Field name in `SELECT` or `WHERE` | No | Allowlist, then concatenate |
| Object name in `FROM` | No | Allowlist, then concatenate |
| `ORDER BY` field and `ASC` or `DESC` | No | Allowlist, then concatenate |
If user input chooses a field, an object, or a sort order, binding does not help. A later chapter covers allowlists for those parts.
Binding and LIKE
A bound value in a LIKE comparison is still safe from injection. The user cannot leave the value. But % and _ inside the value still act as wildcards, so the user can widen the match. A later chapter covers how to handle that.
public static List<Account> startsWith(String prefix) {
String pattern = prefix + '%';
return Database.query('SELECT Id, Name FROM Account WHERE Name LIKE :pattern');
}Build the pattern in Apex, store it in a variable, and bind the variable. Do not write LIKE '%' + prefix + '%' in the query string. That is concatenation again.
Common errors
These mistakes appear often in code reviews. Each one leaves a hole even though a bind variable is present somewhere in the code.
- Binding one value and concatenating another. A query with
Name = :nameandAND Industry = '+ industry +'is still injectable throughindustry. Check every user-controlled part. - Putting quotes around the placeholder.
Name = ':name'compares to the literal text:name. It is not injectable, but it is wrong. Remove the quotes. - Using a variable that is out of scope. The call throws a
QueryException. Declare the variable in the method that callsDatabase.query. - Binding a field of an object.
:record.Nameis not supported in dynamic SOQL. Copy the value into a local variable. - Passing null by accident.
Name = :namewith a nullnamematches records whoseNameis empty. Decide what a missing value should mean and check it before the query. - Trusting binding to enforce security. Binding prevents injection only. It does not check sharing, object permissions, or field permissions. A later chapter covers user mode for those.
// WRONG: name is bound, but industry is concatenated.
public static List<Account> mixed(String name, String industry) {
return Database.query(
'SELECT Id FROM Account WHERE Name = :name ' +
'AND Industry = \'' + industry + '\''
);
}
// RIGHT: both values are bound.
public static List<Account> bothBound(String name, String industry) {
return Database.query(
'SELECT Id FROM Account WHERE Name = :name AND Industry = :industry'
);
}Why a constant query string matters
If your query string is built only from literals you wrote, you can reason about it. You can read the code and list every query the method can produce. With concatenated input, the set of possible queries is unbounded, and no review can cover it.
This is also why bind variables are the first defense, ahead of escaping. Escaping tries to make hostile text harmless inside a string. Binding makes the question irrelevant, because the text never becomes query syntax.
Checking your work
Read each rewrite with these questions:
- Is every user-controlled value behind a
:placeholder? - Is each placeholder backed by a local variable of the right type?
- Are field, object, and sort names chosen by user input? If so, they need an allowlist, not a bind.
- Does the query need to run in user mode? If so, plan that separately.
Exercise
This method is vulnerable. Rewrite the query so that both user values are bound and the result is limited by a bound Integer. Explain why the quotes around the values disappear. public static List<Lead> findLeads(String company, String status, Integer maxRows) { String soql = 'SELECT Id, Name FROM Lead WHERE Company = \'' + company + '\' AND Status = \'' + status + '\' LIMIT ' + maxRows; return Database.query(soql); }
Show answer
Use placeholders and drop the quote characters: public static List<Lead> findLeads(String company, String status, Integer maxRows) { return Database.query( 'SELECT Id, Name FROM Lead WHERE Company = :company ' + 'AND Status = :status LIMIT :maxRows' ); } The quotes were only needed to build a string literal inside the query text. With a bind variable the value is passed as data and is not part of the text, so there is no literal to open or close. The values cannot change the query structure. Note that maxRows is an Integer, so a null value would cause an error. Check it for null or apply a default before the call.