Sub topic 12
Writing tests that submit injection payloads
This chapter assumes you can write Apex test classes with @IsTest, insert test records, and use the Assert class. It also assumes you know the AccountSearch methods from the earlier chapters: findByName, searchByName, listAccounts and resolveAccountField.
What a payload test proves
A fix is only trustworthy if a test would have failed without it. An injection test follows the attacker's steps:
- Insert known records.
- Call your method with input that tries to change the query.
- Assert that the query behaved as if the input were plain text.
The last step matters. A test that passes against both the vulnerable and the fixed code protects nothing.
Testing a bind variable fix
The payload ' OR Name != ' turns the vulnerable query into WHERE Name = '' OR Name != '', which matches every account. With a bind variable, the whole payload is compared with the Name field as a value.
@IsTest
private class AccountSearchInjectionTest {
private static final List<String> PAYLOADS = new List<String>{
'\' OR Name != \'',
'\'',
'\' OR \'1\'=\'1',
'\\\' OR Id != null OR Name = \\\''
};
@TestSetup
static void setup() {
insert new List<Account>{
new Account(Name = 'Acme'),
new Account(Name = 'Beta')
};
}
@IsTest
static void findByNameTreatsPayloadsAsText() {
for (String payload : PAYLOADS) {
List<Account> result = AccountSearch.findByName(payload);
Assert.areEqual(0, result.size(), 'Payload matched rows: ' + payload);
}
}
@IsTest
static void searchByNameTreatsPayloadsAsText() {
for (String payload : PAYLOADS) {
List<Account> result = AccountSearch.searchByName(payload);
Assert.areEqual(0, result.size(), 'Payload matched rows: ' + payload);
}
}
}Keeping payloads in one list lets you add a new case in one line. A payload that is a lone quote also checks that the method does not throw a QueryException. A thrown exception on odd input means the input reached the query structure.
Testing allowlists
Sort fields cannot be bound, so test that unexpected values fall back to the default instead of failing or being used.
@IsTest
static void unknownSortFieldFallsBackToName() {
List<Account> result = AccountSearch.listAccounts(
'Name, (SELECT Id FROM Contacts) FROM Account --', 'DESC; DELETE'
);
Assert.areEqual(2, result.size());
Assert.areEqual('Acme', result[0].Name, 'Expected the default ASC order by Name');
}The direction 'DESC; DELETE' is not exactly DESC, so the method must use ASC. The first record being Acme shows both fallbacks worked.
For a describe-based validator, assert on the exception:
@IsTest
static void resolveAccountFieldRejectsInjectedNames() {
try {
AccountSearch.resolveAccountField('Name FROM User --');
Assert.fail('Expected IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.areEqual('Unknown or inaccessible field', e.getMessage());
}
Assert.areEqual('Name', AccountSearch.resolveAccountField('name'));
}Assert.fail throws an AssertException, not an IllegalArgumentException, so the catch block does not hide a missing exception. The last line also checks that a valid name in any case returns the canonical API name.
Testing wildcards and user mode
A % typed into a LIKE search is a wildcard, not an attack. Test that your code behaves the way you decided it should:
@IsTest
static void percentSignActsAsWildcard() {
Assert.areEqual(2, AccountSearch.searchByName('%').size());
}If your design says wildcards must be literal, escape them and change this assertion.
To test user mode, run the call with System.runAs as a user whose profile lacks access to a field or object, and assert that the query throws System.QueryException. User-mode errors depend on the org's permissions, so create the user and permission setup inside the test.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Asserting only that no exception occurs | A payload that returns all rows still passes | Assert the row count or the order |
| Testing with no seed data | An empty result proves nothing | Insert records the payload would match |
| Testing only the happy path | Fallbacks and rejections go unchecked | Add one case per defense |
| Never running against the vulnerable code | The test may not detect the bug | Temporarily revert the fix and confirm failure |
Exercise
A teammate writes a test that calls findByName with "' OR Name != '" and asserts no exception is thrown, with no records inserted. Why is this test weak, and how do you fix it?
Show answer
With no records, the query returns zero rows whether or not injection works, and the vulnerable version also throws no exception on this payload. Insert at least one account (for example 'Acme'), call the method with the payload, and assert that the result size is 0. Against the vulnerable code, the same test returns the account and fails, which shows it detects the bug.
Exercise
Write the assertion line for a test of listAccounts that passes sortField 'Secret__c' (not in the allowlist) and expects the default sort.
Show answer
Call AccountSearch.listAccounts('Secret__c', 'ASC') on seeded records 'Acme' and 'Beta', then assert Assert.areEqual('Acme', result[0].Name). The first record is Acme only if the query sorted by Name instead of failing or using the unknown field.