Sub topic 10
Building dynamic SOSL safely with Search.query
Static SOSL covers most searches. Sometimes the query text is not known until run time: the user picks which objects to search, a search box supplies the term, or a configuration record lists the fields to return. For those cases Apex provides Search.query, which takes a SOSL string and runs it.
This chapter assumes you can already write a static FIND ... RETURNING query in Apex, read its List<List<SObject>> result, and use bind variables. It also assumes you know what SOQL injection is. SOSL has the same weakness, with a few extra twists.
What Search.query does
Search.query(String) parses and runs a SOSL string. It returns the same List<List<SObject>> that a static query returns, with one inner list per object in RETURNING, in the same order.
String q = 'FIND \'Acme*\' IN NAME FIELDS RETURNING Account(Id, Name), Contact(Id, LastName)';
List<List<SObject>> results = Search.query(q);
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];Dynamic SOSL behaves like static SOSL at run time, with three differences:
- The compiler cannot check the string. A typo in an object or field name shows up as a
QueryExceptionwhen the code runs. - Anything you concatenate into the string becomes part of the query syntax.
- Search.query counts toward the same SOSL limit as static queries: 20 SOSL queries per synchronous transaction, and up to 2,000 rows returned from each query.
Use static SOSL with a bind variable whenever the shape of the query is fixed. Use Search.query only when the objects, fields, or clauses really vary.
How injection happens in SOSL
Consider a naive version:
public with sharing class UnsafeSearch {
public static List<Account> find(String userInput) {
String q = 'FIND \'' + userInput + '\' IN NAME FIELDS RETURNING Account(Id, Name)';
return (List<Account>) Search.query(q)[0];
}
}If userInput is x' IN ALL FIELDS RETURNING Account(Id, Name, AnnualRevenue) LIMIT 2000 //, the quote ends the search term early, and the caller controls the rest of the query. Even if the attacker cannot read data they are not allowed to see, because sharing still applies, they can change which fields are searched, which fields come back, and how many rows return. A malformed value also makes the query fail with an exception instead of returning an empty list.
The input has to be treated as a value inside a quoted term, never as query syntax.
Escaping the search term
String.escapeSingleQuotes adds a backslash before each single quote. It stops the term from closing early, and it is the minimum defense.
It does not neutralize SOSL's own special characters. These characters have meaning inside a search term:
? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -A user who types Acme OR * or a* gets wildcard and operator behavior, even though the query structure is intact. Sometimes that is acceptable, since a search box often supports wildcards. If you want the input treated as plain text, escape every reserved character with a backslash.
public with sharing class DynamicSearch {
private static final Set<String> ALLOWED_OBJECTS =
new Set<String>{ 'Account', 'Contact', 'Opportunity' };
private static final Integer MAX_ROWS = 50;
// Puts a backslash before every reserved character, including ' and \
public static String escapeTerm(String raw) {
return raw.trim().replaceAll('([\\\\?&|!{}\\[\\]()^~*:"\'+\\-])', '\\\\$1');
}
public static List<SObject> search(String userInput, String objectName) {
if (String.isBlank(userInput) || userInput.trim().length() < 2) {
throw new IllegalArgumentException('Enter at least two characters.');
}
if (!ALLOWED_OBJECTS.contains(objectName)) {
throw new IllegalArgumentException('Object not searchable: ' + objectName);
}
String query = 'FIND \'' + escapeTerm(userInput) + '*\''
+ ' IN NAME FIELDS RETURNING ' + objectName
+ '(Id, Name LIMIT ' + MAX_ROWS + ')';
try {
List<List<SObject>> results = Search.query(query);
return Security.stripInaccessible(AccessType.READABLE, results[0]).getRecords();
} catch (QueryException e) {
System.debug(LoggingLevel.ERROR, 'SOSL failed: ' + e.getMessage());
return new List<SObject>();
}
}
}Points to notice in this class:
- The escape runs once, in one pass, and handles the backslash and the single quote together. Do not run
escapeSingleQuotesfirst and thenescapeTerm, because the second pass would escape the backslashes the first pass added. - The wildcard
*is added after escaping, so only the trailing one is live. A*typed by the user arrives as\*. - Query text that is not a search term is never taken from the user. The object name is checked against an allow-list, and the row limit is a constant.
- Reserved-character rules are applied by the search parser, so test an input such as
O'Brienand one with-in a real org before relying on the behavior.
Letting the caller choose objects and fields
When a component lets users pick objects, accept names but rebuild the RETURNING clause from validated values only.
public with sharing class MultiObjectSearch {
public static List<List<SObject>> search(String term, List<String> objectNames) {
Map<String, Schema.SObjectType> global = Schema.getGlobalDescribe();
List<String> parts = new List<String>();
for (String name : objectNames) {
Schema.SObjectType t = global.get(name.toLowerCase());
if (t == null || !t.getDescribe().isAccessible()) {
continue; // skip unknown or hidden objects
}
parts.add(t.getDescribe().getName() + '(Id, Name LIMIT 20)');
}
if (parts.isEmpty() || String.isBlank(term) || term.trim().length() < 2) {
return new List<List<SObject>>();
}
String query = 'FIND \'' + DynamicSearch.escapeTerm(term) + '*\''
+ ' IN NAME FIELDS RETURNING ' + String.join(parts, ', ');
return Search.query(query);
}
}Here getDescribe().getName() returns the canonical API name from the schema, so only real, accessible object names reach the query. The result lists follow the order of parts, and skipped objects leave no gap. Keep the validated names in a list so you can map each inner list back to its object. Not every object has a Name field, so check Name exists, or use t.getDescribe().fields.getMap(), when you accept arbitrary objects.
Errors and edge cases
| Situation | What happens | What to do |
|---|---|---|
| Search term shorter than two characters | `QueryException` or empty results | Validate length before building the query |
| Unknown object or field name | `QueryException` at run time | Allow-list or schema lookup |
| Unescaped quote in the term | Syntax error, or changed query | Escape every term |
| More than 20 SOSL queries in a synchronous transaction | Limit exception | Search several objects in one `RETURNING` clause instead of one query per object |
| Inaccessible fields in the result | Sharing applies, but field-level security does not | Use `Security.stripInaccessible` |
Sharing and field access
Search.query respects record sharing according to the class that runs it. Declare the class with sharing, as the examples do. It does not enforce field-level security on the fields you return. A user without read access to a field can still get its value from a query that selects it, unless you strip it. Security.stripInaccessible(AccessType.READABLE, records) removes fields the user cannot read and returns a SObjectAccessDecision, whose getRecords() gives the cleaned records.
Testing dynamic SOSL
Newly inserted records are not reliably searchable inside a test, so use Test.setFixedSearchResults to control what the query returns. The query text is still built and parsed, so a malformed query fails the test.
@IsTest
private class DynamicSearchTest {
@IsTest
static void escapesReservedCharacters() {
System.assertEquals('O\\\'Brien', DynamicSearch.escapeTerm('O\'Brien'));
System.assertEquals('a\\*', DynamicSearch.escapeTerm('a*'));
}
@IsTest
static void returnsFixedResult() {
Account acc = new Account(Name = 'Acme Test');
insert acc;
Test.setFixedSearchResults(new List<Id>{ acc.Id });
Test.startTest();
List<SObject> found = DynamicSearch.search('Acme', 'Account');
Test.stopTest();
System.assertEquals(1, found.size());
}
@IsTest
static void rejectsUnknownObject() {
try {
DynamicSearch.search('Acme', 'User; DROP');
System.assert(false, 'Expected an exception');
} catch (IllegalArgumentException e) {
System.assert(e.getMessage().contains('not searchable'));
}
}
}The first test checks the escaping directly, with no query. Test escaping with hostile inputs: a quote, a backslash, }, and an operator word.
Exercise
A search box passes the user's text into 'FIND \'' + String.escapeSingleQuotes(text) + '*\' IN ALL FIELDS RETURNING Account(Id, Name)'. A user types a OR b. The query does not break. Is the code safe from injection, and what would you change if you wanted the input treated as literal text?
Show answer
The query structure is safe, because the single quote cannot close the term, so the user cannot add clauses. The input is still interpreted as search syntax, so OR works as a logical operator and * works as a wildcard. To treat the input as literal text, escape every reserved character with a backslash (not only the single quote), validate the length, and add the trailing * after escaping. Object and field names in the query stay fixed or come from an allow-list.