Sub topic 12
Writing Tests That Submit Injection Payloads
This chapter assumes you can write Apex test classes with @IsTest and @TestSetup. It also assumes you know the defenses from the earlier chapters: bind variables, Database.queryWithBinds, allowlists, Schema describe checks and user mode. Here you will turn those defenses into automated tests that fail when someone weakens them.
Why injection needs its own tests
Salesforce requires 75% code coverage, and a normal test gives you that coverage. A test that calls findByName('Acme') runs the vulnerable query and the safe query equally well. Both return one row, so the test passes either way.
An injection test submits input that a safe implementation treats as plain text and a vulnerable one treats as query syntax. It then asserts the outcome that only the safe implementation produces. If a later change brings back string concatenation, the test fails in CI before the code ships.
The shape of an injection test
Each injection test follows the same steps:
- Insert known records, including at least one that the payload would reveal if it worked.
- Call the method under test with a hostile string.
- Assert on the result: the number of rows, the order of rows, or the exception type.
- Add a positive control, a legitimate input that must still work.
The positive control keeps the test honest. A method that always returns an empty list passes the payload test, and the control test catches it.
Testing a bind variable
The examples use the AccountSearch class from the earlier chapters. It has findByName, searchByName, listAccounts and resolveAccountField. The first test class covers the bind-variable method.
@IsTest
private class AccountSearchInjectionTest {
private static final List<String> PAYLOADS = new List<String>{
'\' OR Name != \'',
'\' OR Id != null OR Name = \'',
'Acme\' --',
'\\',
'\'\''
};
@TestSetup
static void makeData() {
insert new List<Account>{
new Account(Name = 'Acme'),
new Account(Name = 'Globex')
};
}
@IsTest
static void payloadsAreTreatedAsLiteralNames() {
for (String payload : PAYLOADS) {
List<Account> result;
try {
result = AccountSearch.findByName(payload);
} catch (Exception e) {
Assert.fail('Payload threw ' + e.getTypeName() + ': ' + payload);
}
Assert.areEqual(0, result.size(), 'Payload matched rows: ' + payload);
}
}
@IsTest
static void legitimateNameStillMatches() {
Assert.areEqual(1, AccountSearch.findByName('Acme').size());
}
@IsTest
static void nameWithApostropheIsFound() {
insert new Account(Name = 'O\'Brien Ltd');
Assert.areEqual(1, AccountSearch.findByName('O\'Brien Ltd').size());
}
}Several choices in this test matter.
- The payload list is data. Adding a new attack string means adding one line. Include the payload in every assertion message so a failure tells you which string got through.
- Two failure modes are caught. A concatenated query with a stray quote can throw a
QueryException(a malformed query). The payload' OR Name != 'instead matches both accounts. Thetry/catchcatches the first kind and theareEqualcatches the second. - The apostrophe test checks for over-correction. A "fix" that strips quotes from input would break customers named O'Brien. This test fails if someone does that.
| Payload | What it tries | Vulnerable code does |
|---|---|---|
| `' OR Name != '` | Add a condition that is true for every row | Returns every visible account |
| `' OR Id != null OR Name = '` | Same idea, using a different field | Returns every visible account |
| `Acme' --` | Close the string and comment out the rest | Throws `QueryException` |
| `\` | A lone backslash that escapes the closing quote | Throws `QueryException` |
| `''` | Two quotes, to check quote handling | Matches an empty name or throws |
SOQL has no comment syntax, so -- is not a real attack here. The payload is still worth keeping because it produces a malformed query, and the test then shows whether the code handles it.
Check that the test can fail
A test you have never seen fail proves little. After writing it, temporarily replace the body of findByName with the vulnerable concatenation from the first chapter and run the test. It should fail on the first payload. Then restore the safe version. Do this once per new injection test. It takes a minute and confirms the test checks something.
Testing LIKE searches
A bound LIKE value is safe from injection, but % and _ still work as wildcards. Whether that is acceptable depends on your design. A test records the decision so nobody changes it by accident.
@IsTest
static void likeSearchMatchesPartialNames() {
Assert.areEqual(1, AccountSearch.searchByName('Ac').size());
}
@IsTest
static void percentSignActsAsWildcardButStaysBound() {
// Documents current behavior: a user-typed % matches every account.
// If you decide wildcards must be literal, change searchByName and this test together.
Assert.areEqual(2, AccountSearch.searchByName('%').size());
}Add these to the same test class so they share the @TestSetup data. The second test passes because the query was not broken. A wildcard in a bound value changes which rows match, but it cannot change the shape of the query.
Testing allowlists
Field names and sort direction cannot be bound, so the allowlist is the only defense. The test submits something that is not on the list and checks that the method falls back to its safe default.
@IsTest
static void unknownSortFieldFallsBackToName() {
List<Account> result = AccountSearch.listAccounts(
'Name DESC, Id FROM Contact --',
'ASC; DELETE'
);
Assert.areEqual(2, result.size());
Assert.areEqual('Acme', result[0].Name);
Assert.areEqual('Globex', result[1].Name);
}
@IsTest
static void validSortFieldAndDirectionAreHonored() {
List<Account> result = AccountSearch.listAccounts('NAME', 'desc');
Assert.areEqual('Globex', result[0].Name);
}The first test asserts on order. If the payload had reached the query, it would have thrown a QueryException or changed the field list. If the method had dropped the sort entirely, the order would not be reliably ascending. The second test is the positive control. It also checks that matching is case-insensitive, because the allowlist code lowercases its input.
Test the boundaries of the allowlist too. Keep the tests short: one for null, one for an empty string, and one for a valid name with extra whitespace such as ' name '. Decide whether whitespace should be trimmed or rejected, then assert that decision.
Testing Schema describe validation
A describe-based method such as resolveAccountField either returns a canonical field name or throws. Test both outcomes.
@IsTest
private class FieldResolverTest {
@IsTest
static void returnsCanonicalApiName() {
Assert.areEqual('Name', AccountSearch.resolveAccountField('name'));
Assert.areEqual('CreatedDate', AccountSearch.resolveAccountField('CREATEDDATE'));
}
@IsTest
static void rejectsInjectionAndUnknownNames() {
List<String> bad = new List<String>{
'Name FROM Account --',
'Name, (SELECT Id FROM Contacts)',
'NoSuchField__c',
'',
' '
};
for (String candidate : bad) {
try {
AccountSearch.resolveAccountField(candidate);
Assert.fail('Accepted: ' + candidate);
} catch (IllegalArgumentException e) {
Assert.isTrue(e.getMessage().contains('Unknown'), 'Unexpected message: ' + e.getMessage());
}
}
}
}Assert.fail throws an AssertException. That is not an IllegalArgumentException, so the catch block does not swallow it and the test fails correctly. Do not catch bare Exception in this pattern, or the failure signal gets hidden.
Testing user mode with a limited user
Injection defenses and permission defenses are separate. A bound query still returns data the running user should not see unless you enforce permissions. To test that, run the call as a user whose profile lacks access.
@IsTest
private class AccountSearchUserModeTest {
@IsTest
static void userWithoutAccountAccessCannotQuery() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'limited',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Limited',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
Username = 'limited' + System.currentTimeMillis() + '@example.com'
);
insert u;
System.runAs(u) {
try {
AccountSearch.searchByName('Ac');
Assert.fail('Expected QueryException for a user without Account read access');
} catch (QueryException e) {
Assert.isNotNull(e.getMessage());
}
}
}
}The test relies on the Minimum Access - Salesforce profile, which exists in current orgs but can be renamed or absent in older ones. If your org lacks it, create a custom profile in the org or use a permission set approach. The username includes the current time so repeated runs do not collide.
A test like this also catches a regression where someone changes AccessLevel.USER_MODE to AccessLevel.SYSTEM_MODE. Without it, that change passes every other test in this chapter.
Common mistakes in injection tests
- Asserting only on the absence of an exception. A query that returns every row throws nothing. Always assert on the result as well.
- Using one payload. Different defenses fail against different strings. Keep a list and grow it as you learn of new bypasses.
- Skipping the positive control. Without it, an over-aggressive fix that rejects all input passes.
- Testing a copy of the logic. Call the real production method. Do not rebuild the query inside the test.
- Relying on org data. Insert the records the test needs, and keep
@IsTest(SeeAllData=true)out of these classes. - Never watching the test fail. Run each new test against a deliberately vulnerable version once.
What these tests do not cover
These tests detect regressions in code you know about. They do not find a dynamic query nobody tested. Pair them with a code search for Database.query( and Database.countQuery( calls whose strings contain a +, and review each one. Static analysis tools such as Salesforce Code Analyzer can flag concatenation into these calls and complement your tests. The tests stay valuable because they keep a fix fixed after the person who wrote it has moved on.
Exercise
A teammate writes this test for a method findByName and says it proves the method is safe from injection. Name two weaknesses and how you would fix each.
@IsTest
static void testFind() {
insert new Account(Name = 'Acme');
List<Account> r = AccountSearch.findByName('Acme');
Assert.areEqual(1, r.size());
}
Show answer
First, the test submits no hostile input. A concatenated query returns the same single row for "Acme", so the test passes on vulnerable code. Fix it by adding payloads such as ' OR Name != ' and asserting that zero rows come back. Second, it has no second record. With only one account in the org, a payload that matches every row is hard to tell apart from a correct match. Insert a control record such as Globex so a leaked row shows up in the count. Keep the "Acme" case as the positive control. Finally, run the new test once against a deliberately vulnerable version to confirm it fails.
Exercise
You add an allowlist for the direction in listAccounts, accepting only ASC and DESC. Write the three inputs you would test for direction and what you would assert for each.
Show answer
Test 'DESC' (and a lowercase 'desc') and assert that the first row is the record with the alphabetically last name, which confirms valid input is honored. Test 'ASC; DELETE' or 'DESC, Id' and assert that the call does not throw and that results are in ascending order, which confirms unknown input falls back to the default. Test null and assert the same default ascending order with no NullPointerException.