I am trying to follow the security guideline which says "parameters of an @AuraEnabled method should not be placed into a SOQL query unsanitized". What is the process to sanitize an Id that is passed to an AuraEnabled method that will be used in a SOQL query.
1 Answer
There's nothing particularly different from sanitizing input for an @AuraEnabled
method than sanitizing input to defend against SOQL injection in general.
Using escapeSingleQuotes
is recommended practice if you're using dynamic queries. In the case of an Id that you're talking about - if you really want to be safe, you could also check that the input is 15 or 18-characters long, and is only composed of letters and numbers - no spaces, % characters, or backslashes.
public static Boolean isValidId(String s) {
return (
(s.length() == 15 || s.length() == 18)
&&
(s.isAlphanumeric())
);
}
The docs provide more information.
EDIT: @sfdcfox informed me, if the parameter type is already the Id
type, the system Id.valueOf method is superior to the snippet I provided - @sfdcfox said: "for example, it verifies the checksum characters (if present) match the rest of the ID, etc. The correct answer is 'use the correct data type, and validation will happen automatically.'"
-
1Good answer but could be better. Dynamic SOQL still lets you use bind variables so you can go
'where id = :myid'
. Don't escape stuff unless you absolutely have to. Bound var must be "standalone" though, without dots.':someobject.someId'
won't pass value properly. Sep 27, 2017 at 17:38 -
2Assuming the parameter is type Id, the system Id.valueOf is already more particular than your isValidId method. For example, it verifies the checksum characters (if present) match the rest of the ID, etc. The correct answer is "use the correct data type, and validation will happen automatically."– sfdcfoxSep 27, 2017 at 23:33
-