Sub topic 8
Allowlisting Field Names, Object Names and Sort Direction
This chapter assumes you can write Apex classes, use Set and Map, and have read the previous chapter on bind variables.
Why bind variables are not enough
A bind variable carries a value. It cannot stand in for the parts that give a query its structure: the fields after SELECT, the object after FROM, the column after ORDER BY, and the ASC or DESC keyword.
Suppose a page lets users sort a list by a column they pick, and your code concatenates that choice into the query. An attacker can then send a value you never offered. They can sort by a sensitive field to learn about its contents, or send malformed text to make the query fail and read the error. The fix is an allowlist.
The allowlist rule
An allowlist is a fixed set of strings that your code considers legal. User input never enters the query. It only selects one of your strings, and if it matches none, you use a safe default.
| Part of the query | Can it be bound? | Defense |
|---|---|---|
| Value in `WHERE` | Yes | Bind variable |
| Field name | No | Allowlist or Schema describe |
| Object name | No | Allowlist or Schema describe |
| Sort direction | No | Accept only `ASC` or `DESC` |
Allowlisting sort fields and direction
This class accepts three sortable fields. The sort direction is never copied from the input. The code checks for DESC and otherwise uses ASC.
public with sharing class AccountList {
private static final Set<String> SORTABLE_FIELDS =
new Set<String>{ 'name', 'industry', 'createddate' };
public static List<Account> listAccounts(String sortField, String direction) {
String column = (String.isNotBlank(sortField) && SORTABLE_FIELDS.contains(sortField.trim().toLowerCase()))
? sortField.trim().toLowerCase()
: 'name';
String dir = (direction != null && direction.trim().equalsIgnoreCase('DESC')) ? 'DESC' : 'ASC';
return Database.query(
'SELECT Id, Name FROM Account ORDER BY ' + column + ' ' + dir + ' LIMIT 50',
AccessLevel.USER_MODE
);
}
}Apex field names are case-insensitive, so lowercasing the input before the lookup is safe. Anything outside the set, such as Owner.Email or name; DELETE, falls back to name.
Allowlisting object names
When one method serves several objects, map a short key from the caller to the real API name. The string in the query comes from your map, never from the caller.
public with sharing class RecordCounter {
private static final Map<String, String> OBJECTS = new Map<String, String>{
'account' => 'Account',
'contact' => 'Contact',
'opportunity' => 'Opportunity'
};
public static Integer countRecords(String objectKey) {
String apiName = OBJECTS.get(objectKey == null ? '' : objectKey.trim().toLowerCase());
if (apiName == null) {
throw new IllegalArgumentException('Object not supported');
}
return Database.countQuery('SELECT COUNT() FROM ' + apiName);
}
}For sort order, a default is friendly. For an object name, a default would silently return the wrong data, so this method throws.
Common mistakes
- Concatenating the user's string after the check. Use the value from your set or map, not the raw input.
- Checking for bad characters instead of good values. A blocklist of quotes or keywords always misses something.
- Forgetting to normalize.
Namewith a trailing space orNAMEwill miss a case-sensitive lookup and fall back to the default. That is safe, but it looks like a bug. - Allowing more than you intend. Every entry in the allowlist is a field or object any caller can now request.
If the set of allowed names is large or changes often, hard-coding it gets tedious. The next chapter shows how to validate names against Schema describe results instead.
Exercise
A method receives objectKey and sortDirection from a Lightning component. Which of the two can be handled with a bind variable, and how should each be made safe?
Show answer
Neither can be bound, because an object name and a sort keyword are part of the query structure. Map objectKey through a fixed Map of allowed keys to API names and throw if the key is missing. For sortDirection, compare it to DESC and otherwise use ASC, so only your own literal is added to the query.