Sub topic 8
Allowlisting Field Names, Object Names and Sort Direction
This chapter assumes you can write static SOQL, you know the basics of Apex classes, maps and sets, and you have seen why concatenating input into Database.query is dangerous. It also assumes you know that bind variables fix value injection. Here you handle the parts of a query that a bind variable cannot reach.
Why bind variables are not enough
A bind variable such as :name replaces a value. SOQL has no way to bind a name that the parser must resolve before it runs the query. These parts of a query are identifiers or keywords, so they cannot be bound:
| Query part | Example | Can it be bound? |
|---|---|---|
| Field in SELECT | `SELECT Id, Name` | No |
| Field on the left of a WHERE condition | `WHERE Industry = :value` | No (only the value is bound) |
| Object in FROM | `FROM Account` | No |
| ORDER BY field | `ORDER BY CreatedDate` | No |
| Sort direction | `ASC`, `DESC` | No |
| Value on the right of a condition | `WHERE Name = :name` | Yes |
| LIMIT and OFFSET value | `LIMIT :size` | Yes |
If a user-controlled string reaches any of the "No" positions, the attacker controls the structure of the query. Typical outcomes:
- Extra fields in SELECT. A parameter such as
Name, AnnualRevenuereturns data the screen was never meant to show. - A different object in FROM. The query reads Contacts or Cases instead of Accounts.
- Sorting by a sensitive field. The attacker never sees the field's value, but the order of the results leaks information about it.
- A nested subquery in the select list.
Name, (SELECT Id FROM Contacts)pulls related records into the result.
The fix is an allowlist. You decide in code which identifiers are acceptable, and anything else is rejected or replaced with a default.
The core rule: look up, then use your own value
Checking that the input is "safe" and then concatenating the input is fragile. Instead, use the input only as a key into a map that you wrote. The value you put into the query is the map's value, which is a string literal in your source code. Attacker-controlled text never reaches the query string.
public with sharing class AccountListService {
// User-facing key (lowercase) -> real API name.
private static final Map<String, String> SORT_FIELDS = new Map<String, String>{
'name' => 'Name',
'industry' => 'Industry',
'created' => 'CreatedDate'
};
public static List<Account> fetchAccounts(String sortKey, Boolean descending, Integer pageSize) {
String key = String.isBlank(sortKey) ? 'name' : sortKey.trim().toLowerCase();
String field = SORT_FIELDS.get(key);
if (field == null) {
throw new IllegalArgumentException('Unsupported sort option');
}
String direction = (descending == true) ? 'DESC' : 'ASC';
Integer size = Math.min(Math.max(pageSize == null ? 50 : pageSize, 1), 200);
String soql = 'SELECT Id, Name, Industry FROM Account'
+ ' ORDER BY ' + field + ' ' + direction
+ ' LIMIT :size';
return Database.queryWithBinds(
soql,
new Map<String, Object>{ 'size' => size },
AccessLevel.USER_MODE
);
}
}Four details in this class matter:
- The map keys are lowercase, and the input is lowercased before the lookup. Apex
MapandSetlookups with String keys are case-sensitive, so'Name'would not match'name'otherwise. trim()removes accidental whitespace. Whitespace is not a security risk here, because a key that is not in the map simply misses.- The sort direction comes from a
Boolean, not from a string. There are only two possible outputs, and both are literals. LIMITtakes a boundInteger, clamped to a sensible range. The query runs in user mode, so sharing, CRUD and field-level security still apply.
Reject or fall back?
The class above throws on an unknown sort key but defaults when the key is blank. You must choose a policy for each parameter.
| Policy | Use it when | Trade-off |
|---|---|---|
| Throw an exception | The caller is another developer or an API client, and a wrong key is a bug | Visible failures, but the UI must handle the error |
| Fall back to a default | The value comes from a user-facing control and an invalid value is unlikely | Quiet and friendly, but a bug in the client can go unnoticed |
| Log and fall back | You want a default but also want to detect probing | Needs a logging mechanism you trust |
Either policy is safe. The unsafe option is a third one: passing the unknown value through.
Allowlisting object names
The same pattern works for the object in FROM. This example counts records for a small set of objects:
public with sharing class RecordCounter {
private static final Map<String, String> COUNTABLE_OBJECTS = new Map<String, String>{
'account' => 'Account',
'contact' => 'Contact',
'opportunity' => 'Opportunity'
};
public static Integer countRecords(String objectKey) {
String key = (objectKey == null) ? '' : objectKey.trim().toLowerCase();
String objectName = COUNTABLE_OBJECTS.get(key);
if (objectName == null) {
throw new IllegalArgumentException('Object is not countable');
}
return Database.countQueryWithBinds(
'SELECT COUNT() FROM ' + objectName,
new Map<String, Object>(),
AccessLevel.USER_MODE
);
}
}Database.countQueryWithBinds takes a bind map even when the query has no binds, so you pass an empty map. If you must support many objects, validating against the schema is more practical than a hand-written map. The next chapter covers that.
Allowlisting several fields
Some features let the user choose which columns to show. Validate each requested name, de-duplicate, and build the list from your own values:
public with sharing class AccountColumns {
private static final Map<String, String> COLUMNS = new Map<String, String>{
'name' => 'Name',
'industry' => 'Industry',
'type' => 'Type',
'rating' => 'Rating'
};
public static List<Account> fetchColumns(List<String> requested) {
Set<String> chosen = new Set<String>{ 'Id' };
if (requested != null) {
for (String item : requested) {
String key = (item == null) ? '' : item.trim().toLowerCase();
String field = COLUMNS.get(key);
if (field == null) {
throw new IllegalArgumentException('Unsupported column: ' + key.left(40));
}
chosen.add(field);
}
}
String soql = 'SELECT ' + String.join(new List<String>(chosen), ', ')
+ ' FROM Account LIMIT 50';
return Database.queryWithBinds(soql, new Map<String, Object>(), AccessLevel.USER_MODE);
}
}The error message echoes the rejected key, but only its first 40 characters. Never echo unbounded user input into messages or logs without limiting it.
Common mistakes
These checks look like validation but do not prevent injection:
- Checking with
containsorstartsWith.'name desc, annualrevenue'.startsWith('name')is true. Use exact lookups in a map or set. - Using a regular expression like
^\w+$as the only check. It stops punctuation, but it accepts any field or object name, including ones you never meant to expose. Identifier syntax is not the same as permission to query. - Validating one string and using another. If you check the trimmed, lowercased value but concatenate the original, the check proves nothing. Concatenate only the map's value.
- Allowlisting by blocklist. Rejecting
;,--or the wordSELECTmisses cases. SOQL has no statement separator, and an attacker only needs a valid fragment such as a field name or a subquery. A list of allowed values is finite and a list of bad values is not. - Trusting hidden form fields or client-side dropdowns. Anything that arrives in a method parameter is attacker-controlled, including values from
@AuraEnabledmethods, REST resources and Visualforce parameters.
Keeping allowlists maintainable
Allowlists are easy to forget when requirements change. A few habits help:
- Keep each allowlist in one place, as a
private static finalconstant at the top of the class that owns the query. - Use the same key for the UI and the map. If the UI sends
created, the map key iscreated, and no translation code is needed elsewhere. - Store the real API names in the map values, not computed strings. A reviewer can read the map and see every identifier that can reach the query.
- If the allowed set is the same as the object's fields that the user may read, switch to Schema describe validation instead of maintaining a long map.
- Add a test per allowlist that sends an unlisted value and asserts the exception or default. The testing chapter shows how.
Edge cases
- Null input.
null.trim()throws aNullPointerException. Guard withString.isBlankor a ternary, as the examples do. - Mixed case. Users and clients send
Name,NAMEandname. Lowercase before the lookup. - Relationship paths. Allow a path such as
Owner.Nameby listing it in the map as a whole. Do not split on dots and validate the parts separately. - Sort options beyond direction. If you support
NULLS FIRSTorNULLS LAST, choose between literals the same way you chooseASCandDESC. - Large allowed sets. A map with hundreds of entries is hard to review. That is the signal to move to describe-based validation.
Exercise
A method receives String sortField and String sortDir from a Lightning component and builds '... ORDER BY ' + sortField + ' ' + sortDir. List two things an attacker could achieve, then rewrite the two lines that compute the identifiers so that neither value from the client reaches the query.
Show answer
The attacker could sort by a field the screen was never meant to expose, which leaks information through the ordering. They could also supply Name LIMIT 2000 or a similar fragment to change the query's shape, or send an invalid value to cause errors that reveal details. Rewrite: String field = SORT_FIELDS.get(String.isBlank(sortField) ? 'name' : sortField.trim().toLowerCase()); followed by a null check that throws or falls back, and String dir = 'desc'.equalsIgnoreCase(sortDir) ? 'DESC' : 'ASC';. The query then uses field and dir, which are literals from your code.
Exercise
Why is if (fieldName.startsWith('Name')) { soql += fieldName; } not a valid allowlist, and what is the smallest change that makes it one?
Show answer
startsWith accepts any string that begins with Name, such as Name, AnnualRevenue or Name, (SELECT Id FROM Contacts), and the unchecked input is then concatenated. The smallest fix is an exact lookup in a map keyed by lowercase names, then concatenating the map's value: String f = FIELDS.get(fieldName.trim().toLowerCase()); if (f == null) throw new IllegalArgumentException('Unsupported field'); soql += f;.