Sub topic 9
Validating dynamic field and object names with Schema describe
This chapter assumes you can write Apex classes, know that bind variables can't hold field or object names, and have seen a fixed allowlist of sort fields. The goal here is a check that works when the allowed names can't be listed ahead of time.
Why an allowlist is sometimes not enough
A hard-coded Set<String> of sortable fields is the strictest option. It doesn't fit generic components, such as a list view or an admin tool, where the caller picks the object and the fields. Listing every valid name by hand would be impractical and would go stale as the schema changes.
Schema describe gives you the list of valid names directly from the org. You look up the user's text in the describe results and use only what the lookup returns. The query string never contains the raw input.
How the check works
Every Schema.SObjectType exposes its fields through fields.getMap(). The map keys are field API names, and get() on it is case-insensitive. An injection payload such as Name FROM User-- is not a field name, so the lookup returns null.
Resolving objects and fields
The class below resolves an object name first, then field names on that object. It returns the canonical names from the describe results, not the user's text.
public with sharing class DescribeGuard {
public static Schema.SObjectType resolveObject(String objectName) {
if (String.isBlank(objectName)) {
throw new IllegalArgumentException('Object name is required');
}
Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName.trim());
if (objType == null || !objType.getDescribe().isAccessible()) {
throw new IllegalArgumentException('Unknown or inaccessible object');
}
return objType;
}
public static String resolveField(Schema.SObjectType objType, String fieldName) {
if (String.isBlank(fieldName)) {
throw new IllegalArgumentException('Field name is required');
}
Map<String, Schema.SObjectField> fields = objType.getDescribe().fields.getMap();
Schema.SObjectField f = fields.get(fieldName.trim());
if (f == null || !f.getDescribe().isAccessible()) {
throw new IllegalArgumentException('Unknown or inaccessible field');
}
return f.getDescribe().getName();
}
}Both methods throw one generic message. Don't echo the raw input back in an error, because it may end up in a page or a log.
Using the resolved names in a query
The next method picks a field to filter on and binds the value. Only the identifiers come from describe, and the value stays a bind variable.
public with sharing class RecordSearch {
public static List<SObject> search(String objectName, String fieldName, String value) {
Schema.SObjectType objType = DescribeGuard.resolveObject(objectName);
String objApi = objType.getDescribe().getName();
String fieldApi = DescribeGuard.resolveField(objType, fieldName);
Map<String, Object> binds = new Map<String, Object>{ 'val' => value };
String soql = 'SELECT Id, ' + fieldApi
+ ' FROM ' + objApi
+ ' WHERE ' + fieldApi + ' = :val LIMIT 50';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}The Id field is added by the code, and the user does not supply it. The result is a List<SObject>, so callers read values with record.get(fieldApi).
What describe validation does not do
The check proves a name exists and that the running user can read it. It does not do everything an allowlist does.
- It allows every readable field. If users should only sort by three fields, a fixed allowlist is stricter. Describe validation accepts any field they can see.
- It does not understand relationship paths.
Owner.Nameis not ingetMap(), so it is rejected. If you need such paths, split on the dot and resolve each part yourself, or keep an allowlist for them. - It does not enforce row access.
isAccessible()covers object and field permissions. Sharing rules are a separate layer, which is why the query above also runs in user mode. - It is not free.
Schema.getGlobalDescribe()builds a large map. If you call it often in one transaction, cache the result in a static variable. For a single lookup,Schema.describeSObjects(new List<String>{ name })is lighter, but it throws an exception for an unknown name, so wrap it in a try/catch.
Testing the guard
A test should check that real names pass and that payloads are rejected.
@IsTest
private class DescribeGuardTest {
@IsTest
static void rejectsInjectedFieldName() {
try {
DescribeGuard.resolveField(Account.SObjectType, 'Name FROM User--');
Assert.fail('Expected an exception');
} catch (IllegalArgumentException e) {
Assert.areEqual('Unknown or inaccessible field', e.getMessage());
}
}
@IsTest
static void returnsCanonicalName() {
Assert.areEqual('Name', DescribeGuard.resolveField(Account.SObjectType, 'name'));
}
}Exercise
A caller passes the field name "industry " (lowercase, with a trailing space) to resolveField on Account. What does the method return, and why is that safer than using the input in the query?
Show answer
It returns "Industry". The method trims the input, the describe map lookup is case-insensitive, and getName() returns the canonical API name. The query then contains text produced by Salesforce, not text typed by the user.