PDI · Question #54
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…
The correct answer is 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. To prevent SOQL injection in a dynamic Apex query, a developer can either use variable binding with static SOQL or sanitize the user input string using the escapeSingleQuotes method before dynamic concatenation.
Question
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<Contact> 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
Options
- AUse variable binding and replace the dynamic query with a static SOQL.
- BUse the escapeSingleQuote method to sanitize the parameter before its use.
- CUse a regular expression on the parameter to remove special characters.
- DUse the @Readonly annotation and the with sharing keyword on the class.
How the community answered
(26 responses)- A77% (20)
- C8% (2)
- D15% (4)
Why each option
To prevent SOQL injection in a dynamic Apex query, a developer can either use variable binding with static SOQL or sanitize the user input string using the escapeSingleQuotes method before dynamic concatenation.
Variable binding (e.g., WHERE LastName Like :lastName) within a static SOQL query automatically sanitizes input by treating the variable's content as a literal, preventing it from being interpreted as executable code.
The String.escapeSingleQuotes() method explicitly sanitizes user input by escaping any single quote characters, which are a primary vector for SOQL injection, making it safe for use in dynamic SOQL queries.
While regular expressions can validate or remove characters, escapeSingleQuotes() is the standard and most direct method provided by Apex for preventing SOQL injection from single quotes, which are the main concern.
@ReadOnly and with sharing are security mechanisms related to record access and view-state, not directly to preventing SOQL injection from malicious query strings.
Concept tested: SOQL injection prevention
Source: https://developer.salesforce.com/docs/atlas.en-us.secure_coding_guide.meta/secure_coding_guide/secure_coding_soql_injection.htm
Topics
Community Discussion
No community discussion yet for this question.