Sub topic 7
Safe LIKE searches and user-supplied wildcards
This chapter assumes you can write static SOQL with WHERE and LIMIT, and that you know why bind variables stop SOQL injection. The previous chapters covered both. Here the concern is different. A bind variable keeps input from changing the structure of a query, but it does not stop the input from changing what a LIKE pattern matches.
What a bind variable does not protect
Consider the safe version of a name search:
public static List<Account> searchByName(String input) {
String term = '%' + input + '%';
return [SELECT Id, Name FROM Account WHERE Name LIKE :term LIMIT 50];
}The query is not injectable. If a user types ' OR Name != ', the text is compared as a literal pattern, and it matches nothing.
The LIKE operator gives some characters special meaning inside the pattern. The bind variable delivers the whole string to the pattern matcher as a value, and the matcher still interprets those characters. If a user types %, the pattern becomes %%%, which matches every account the user can see. The user did not break out of the string. They used a feature of the string.
This is a smaller problem than injection, but it has real consequences:
- A user can list every record they can see through a search box that was meant to need a specific term.
- A pattern with many wildcards forces a full scan on a large object, which wastes limits and slows the org.
- A search field that is meant to match a literal value, such as a part number containing
_, returns wrong results.
The two wildcard characters
SOQL LIKE treats two characters specially, and it uses the backslash as the escape character.
| Character | Meaning in a LIKE pattern | Escaped form in the pattern |
|---|---|---|
| `%` | Zero or more of any character | `\%` |
| `_` | Exactly one of any character | `\_` |
| `\` | Escape character | `\\` |
The backslash is itself special, so it must be escaped too. If you skip it, a user can type \ before a character you escaped and cancel your escaping. The next sections show how.
In an Apex string literal, a backslash is also the string escape character. To write one backslash in a string you type '\\'. To write two you type '\\\\'. This is why the code below looks like it has too many backslashes.
Escaping user wildcards
Write a small helper that turns user text into a literal fragment for a LIKE pattern:
public with sharing class LikeSupport {
public static String escapeLike(String input) {
if (input == null) {
return '';
}
return input
.replace('\\', '\\\\')
.replace('%', '\\%')
.replace('_', '\\_');
}
}String.replace treats both arguments as plain text, not as regular expressions. That is why it is the right method here. replaceAll would read its first argument as a regex and make the code harder to get right.
The order of the three calls matters. The backslash must be handled first. If you escaped % first, you would produce \%, and the backslash step would then double that backslash and turn it into \\%. That pattern means "a literal backslash, then any characters", which is wrong.
| User types | After escapeLike | Matches |
|---|---|---|
| `100%` | `100\%` | The text `100%` only |
| `A_C` | `A\_C` | The text `A_C` only |
| `C:\temp` | `C:\\temp` | The text `C:\temp` only |
| `%` | `\%` | A literal percent sign only |
Building the full search method
The next example combines escaping, a minimum length, a prefix or contains choice, a bind map, and user mode. The caller picks the match mode from a fixed set, so the pattern layout is never user text.
public with sharing class AccountLikeSearch {
private static final Integer MIN_TERM_LENGTH = 3;
private static final Integer MAX_ROWS = 50;
public enum MatchMode { STARTS_WITH, CONTAINS }
public static List<Account> searchByName(String input, MatchMode mode) {
String trimmed = input == null ? '' : input.trim();
if (trimmed.length() < MIN_TERM_LENGTH) {
throw new IllegalArgumentException(
'Enter at least ' + MIN_TERM_LENGTH + ' characters.'
);
}
String literal = LikeSupport.escapeLike(trimmed);
String pattern = (mode == MatchMode.CONTAINS)
? '%' + literal + '%'
: literal + '%';
Map<String, Object> binds = new Map<String, Object>{ 'pattern' => pattern };
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name LIKE :pattern ORDER BY Name LIMIT ' + MAX_ROWS,
binds,
AccessLevel.USER_MODE
);
}
}Points to check in this code:
- The query string contains no user text.
MAX_ROWSis a constant integer that the code controls, so concatenating it is safe. - The
%characters that make the search a "contains" search are added after escaping. Only the user's text is escaped. Your own wildcards must stay unescaped. - The length check runs on the trimmed text, before escaping. Escaping can lengthen a string, so checking afterwards would let
%%pass as four characters. AccessLevel.USER_MODEapplies the running user's sharing, object permissions, and field-level security. The user-mode chapter covers it in more detail.
The same helper works with static SOQL, because the escaping concerns the pattern and not the query style:
String pattern = LikeSupport.escapeLike(trimmed) + '%';
List<Account> accounts = [
SELECT Id, Name FROM Account WHERE Name LIKE :pattern WITH USER_MODE LIMIT 50
];Following the data through the code
Why the escape order and the escape character both matter
Suppose you wrote a helper that escaped % and _ but not the backslash. A user types \%. Your helper turns it into \\%. In the pattern, \\ is a literal backslash, and the % after it is a live wildcard again. The user has switched your escaping off with one extra character. Escaping the backslash first closes this gap, because the user's \% becomes \\\%, which means a literal backslash followed by a literal percent sign.
This is the same lesson as String.escapeSingleQuotes: an escaping scheme only works if it also escapes the escape character.
Minimum length, selectivity, and result limits
Escaping makes the search correct. It does not make it cheap. Three more habits help.
- Require a minimum term length. A one-letter contains search can match most of an object. Three characters is a common floor, but pick one that fits your data volume.
- Prefer starts-with patterns where the business allows it. A pattern such as
Acme%can use an index on the field, which keeps the query selective. A pattern with a leading wildcard such as%Acme%generally cannot, and on objects with large data volumes it can fail the selectivity requirements for queries run in triggers or other non-selective contexts. Salesforce Object Search Language (SOSL) or a search index is often a better fit for contains searches on large objects. - Always set a
LIMIT. Decide the cap in code, not from user input. If the user chooses a page size, convert it to anIntegerand clamp it, as in the typed-input chapter.
A caller who passes % and gets an error learns nothing sensitive. A caller who gets 50,000 rows learns a lot. Fail closed.
Testing wildcards
Test two behaviors: wildcards are treated as text, and short terms are rejected.
@IsTest
private class AccountLikeSearchTest {
@IsTest
static void percentSignIsTreatedAsLiteral() {
insert new List<Account>{
new Account(Name = 'Alpha100'),
new Account(Name = '100% Pure')
};
List<Account> result = AccountLikeSearch.searchByName(
'100%', AccountLikeSearch.MatchMode.CONTAINS
);
Assert.areEqual(1, result.size(), 'Only the name containing a literal percent sign should match');
Assert.areEqual('100% Pure', result[0].Name);
}
@IsTest
static void underscoreIsTreatedAsLiteral() {
insert new List<Account>{
new Account(Name = 'Plan_A'),
new Account(Name = 'PlanXA')
};
List<Account> result = AccountLikeSearch.searchByName(
'Plan_A', AccountLikeSearch.MatchMode.STARTS_WITH
);
Assert.areEqual(1, result.size(), 'Underscore must not match any single character');
Assert.areEqual('Plan_A', result[0].Name);
}
@IsTest
static void wildcardOnlyInputIsRejected() {
Boolean thrown = false;
try {
AccountLikeSearch.searchByName('%', AccountLikeSearch.MatchMode.CONTAINS);
} catch (IllegalArgumentException e) {
thrown = true;
}
Assert.isTrue(thrown, 'A one-character wildcard must be rejected');
}
}The first test would fail without escaping. The unescaped pattern %100%% also matches Alpha100, so the result would contain two rows. That is the evidence that the escaping does something. When you write security tests, run them once against the unprotected version of the code and confirm they fail. A test that passes both ways proves nothing.
Common mistakes
- Escaping first and then adding your own wildcards in the wrong order. Add
%for the match mode after you callescapeLike. - Escaping and then also calling
String.escapeSingleQuoteson a bound value. Bound values do not need quote escaping, and the extra backslashes change what matches. - Using
replaceAllwith an unescaped%or\. The backslash is special in regular expressions, so the code either fails or does something other than you intended. - Escaping the whole bound pattern after the
%signs are added. This turns your own wildcards into literals and the search stops working. - Skipping the minimum-length check because "the bind variable makes it safe". Binding stops injection. It does not limit how much data a pattern returns.
Summary
User text placed in a LIKE pattern needs two separate defenses. Bind variables protect the query structure. Escaping \, %, and _ protects the meaning of the pattern. Add your own wildcards after escaping, require a minimum term length, set a row limit, run in user mode, and write tests that submit wildcard input and check which rows come back.
Exercise
A developer writes String pattern = '%' + input.replace('%', '\\%') + '%'; and binds pattern in a LIKE query. A user types \% into the search box. What does the user's input do, and how do you fix the helper?
Show answer
The helper turns \% into \\%. In a LIKE pattern, \\ is a literal backslash, so the % that follows is an unescaped wildcard again, and the search matches every row that contains a backslash. The fix is to escape the backslash first, then the other special characters: input.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_'). With that helper, \% becomes \\\%, which matches only the literal text \%.