A developer is tasked to perform a security review of the ContactSearch Apex class that exists in the system. Whithin the class, the developer identifies the following method as a security threat: List performSearch(String lastName){ return Database.query('Select Id, FirstName, LastName FROM Contact WHERE LastName Like %'+lastName+'%); } What are two ways the developer can update the method to prevent a SOQL injection attack? Choose 2 answers
A. Use variable binding and replace the dynamic query with a static SOQL.
B. Use the escapeSingleQuote method to sanitize the parameter before its use.
C. Use a regular expression on the parameter to remove special characters.
D. Use the @Readonly annotation and the with sharing keyword on the class.
C. Use a regular expression on the parameter to remove special characters. D. Use the @Readonly annotation and the with sharing keyword on the class.
Explanation:
The provided method is vulnerable to SOQL injection because it directly includes untrusted user input (lastName) in a dynamic SOQL query. To fix this, the developer should sanitize the input and/or avoid dynamic queries when possible.
A. Use variable binding and replace the dynamic query with a static SOQL.
This is the best and most secure approach. Using variable binding (bind variables) ensures that input is treated as data, not executable code:
List results = [SELECT Id, FirstName, LastName FROM Contact WHERE LastName LIKE :('%' + lastName + '%')];
B. Use the escapeSingleQuote method to sanitize the parameter before its use.
If dynamic SOQL must be used, sanitizing input with String.escapeSingleQuotes(lastName) helps prevent injection by escaping special characters:
String safeInput = String.escapeSingleQuotes(lastName);
List results = Database.query('SELECT Id, FirstName, LastName FROM Contact WHERE LastName LIKE \'%' + safeInput + '%\'');