Sub topic 10
Building dynamic SOSL safely with Search.query
This chapter assumes you can write static SOSL in Apex with a FIND and a RETURNING clause, and that you know how bind variables work. Here you will build a SOSL query as a string at run time. You will run it with Search.query, and you will keep user input from changing the meaning of the query.
When to build the query as a string
A static query in square brackets is checked when the code is saved. It can take values through bind variables, which cannot change the query's structure. Prefer it whenever the objects, fields, and clauses are known in advance.
Use Search.query when the shape of the query itself changes at run time. Examples are a search box where the user picks the objects to search, or a configurable list of fields to return. Search.query takes a SOSL string and returns the same List<List<SObject>> as a static query.
The cost is that the compiler no longer checks the query. Errors show up at run time, and any user text you concatenate into the string becomes part of the query.
How unsafe input reaches the query
Suppose a user types Acme' IN ALL FIELDS RETURNING User(Id, Name) --. If you concatenate it into the string as it is, the quote closes your search term early. The rest of the text is then read as SOSL. This is SOSL injection. It works like SQL injection, though the damage is usually limited to searching objects or fields you did not intend.
A safe dynamic search
The class below escapes the search term. It also checks the object name against an allowlist, because object and field names cannot be escaped.
public with sharing class DynamicSearch {
private static final Set<String> ALLOWED_OBJECTS =
new Set<String>{ 'Account', 'Contact', 'Lead' };
public static List<SObject> search(String userInput, String objectName) {
if (String.isBlank(userInput) || userInput.length() < 2) {
return new List<SObject>();
}
if (!ALLOWED_OBJECTS.contains(objectName)) {
throw new IllegalArgumentException('Unsupported object: ' + objectName);
}
String safe = String.escapeSingleQuotes(userInput);
String query = 'FIND \'' + safe + '\' IN NAME FIELDS '
+ 'RETURNING ' + objectName + '(Id, Name LIMIT 20)';
List<List<SObject>> results = Search.query(query);
return results[0];
}
}Points to notice:
String.escapeSingleQuotesadds a backslash before each single quote, so the user's text stays inside the quoted search term.- The allowlist guards the part of the query that escaping cannot protect.
- The
LIMITis a literal you control. If a limit comes from the caller, take it as anIntegerand concatenate that value, not a string. - The method returns early when the term is blank or shorter than two characters. SOSL rejects search terms that are too short.
What escaping does not do
Escaping prevents the user from leaving the quoted term. It does not remove SOSL search syntax inside the term. A user can still type *, ?, double quotes, or AND and OR. These change how the search matches, but they cannot add clauses.
If you want the input treated as plain text, strip or backslash-escape those characters before searching. SOSL reserves characters such as ? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -.
Sharing and field access
Declare the class with sharing so record visibility follows the running user. Sharing does not enforce field-level security. In recent API versions you can pass an access level, as in Search.query(query, AccessLevel.USER_MODE), so the search respects the user's object and field permissions.
Exercise
A search page lets users type any text and choose Account or Contact from a picklist. Which parts of the dynamic SOSL string need escaping, and which need an allowlist?
Show answer
The typed search text needs String.escapeSingleQuotes, because it is a string value placed inside quotes. The object name from the picklist cannot be escaped, so check it against an allowlist such as a Set of Account and Contact before adding it to RETURNING.