ApexSensei

Drills SOQL queries

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

  1. Bind or String.escapeSingleQuotes should be present
  2. Acme matches: should be 1
  3. Attack matches: should be 0
  4. countByName(tag + '-Globex') should be 1
  5. countByName(tag + '-Missing') should be 0
  6. Hidden attack input should be 0
  7. Hidden name with a quote should be 1

Sign in to open this drill