Search safely with dynamic SOQL
Dynamic SOQL that glues in user input lets a quote rewrite the query.
Your task
Fix countByName(String nameFilter) so the name it gets cannot change its dynamic SOQL query.
Integer countByName(String nameFilter) {
String query = 'SELECT COUNT() FROM Account WHERE Name = \'' + nameFilter + '\'';
return Database.countQuery(query);
}
String tag = 'AS-Q313-' + UserInfo.getUserId() + '-' +
String.valueOf(Datetime.now().getTime());
insert new List<Account>{
new Account(Name = tag + '-Acme'),
new Account(Name = tag + '-Globex'),
new Account(Name = tag + '-O\'Brien')
};
System.debug('Acme matches: ' + countByName(tag + '-Acme'));
System.debug('Attack matches: ' + countByName(tag + '-Acme\' OR Name LIKE \'%'));Requirements
- Bind or
String.escapeSingleQuotesshould be present Acme matches:should be1Attack matches:should be0countByName(tag + '-Globex')should be1countByName(tag + '-Missing')should be0- Hidden attack input should be
0 - Hidden name with a quote should be
1