Sub topic 9
Validating dynamic field and object names with Schema describe
This chapter assumes you can read and write Apex classes, know static SOQL, and have seen Database.query and bind variables from earlier chapters. You should also know that field-level security (FLS) controls which fields a user may read.
Why bind variables are not enough
Bind variables protect values. A field name, an object name, or a sort column is not a value. It is part of the query structure, so the parser must see it as text. The query SELECT Id FROM Account WHERE Name = :name can bind name, but it cannot bind the word Account or Name.
The previous chapter's allowlist approach works when you know every legal name in advance. It breaks down in three cases:
- A reusable component lets an admin pick any object and any field, so the legal set is too large to list by hand.
- The names come from a UI configuration that changes without a code deployment.
- You want one check that also covers fields added to an object later.
In those cases you can ask the platform what exists. Schema describe is the metadata API built into Apex. It returns objects that represent sObject types and fields. If a name does not map to a real object or field, the lookup returns null, and you reject the request.
How the lookup protects the query
Describe results are only keys into a metadata map. The map holds real names, and the attacker's string is never pasted into the query. You use the string to look something up, and you paste in what the platform returns.
Suppose the input is Name FROM User --. The field map has no such key, so get returns null. The payload never reaches the query text.
Suppose the input is name, in any case. The map finds the field, and you read its canonical API name with getDescribe().getName(). That value comes from Salesforce, so it is safe to place in the query.
Describing fields
Every sObject type has a describe result. The path from a type to its fields is:
- Get a
Schema.SObjectType, for exampleAccount.SObjectTypeorSchema.SObjectType.Account. - Call
getDescribe()to get aSchema.DescribeSObjectResult. - Read
fields.getMap()to get aMap<String, Schema.SObjectField>. - Look up a name, then call
getDescribe()on the field to get aSchema.DescribeFieldResult.
The keys of this map are lowercase API names, and lookups ignore case. Custom fields appear with their __c suffix, and namespaced fields appear with their prefix. Fetching the map is not free, so avoid calling it inside a loop. Store it in a local variable or a static variable.
public with sharing class FieldResolver {
public static Schema.DescribeFieldResult resolveField(
Schema.SObjectType objectType,
String fieldName
) {
if (String.isBlank(fieldName)) {
throw new IllegalArgumentException('Field name is required');
}
Map<String, Schema.SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SObjectField field = fieldMap.get(fieldName.trim());
if (field == null) {
throw new IllegalArgumentException('Unknown field');
}
Schema.DescribeFieldResult describe = field.getDescribe();
if (!describe.isAccessible()) {
throw new IllegalArgumentException('Field is not accessible');
}
return describe;
}
}The error message says only "Unknown field" and does not echo the input. Echoing attacker text in an exception can leak into logs or UI messages.
Which describe checks to use
isAccessible() is not the only check. Different clauses of a query need different properties.
| Where the field is used | Describe method | What it tells you |
|---|---|---|
| `SELECT` list | `isAccessible()` | The running user can read the field. |
| `WHERE` clause | `isFilterable()` | The field can appear in a filter. Long text areas cannot. |
| `ORDER BY` clause | `isSortable()` | The field can be sorted. |
| `GROUP BY` clause | `isGroupable()` | The field can be grouped. |
If you skip these checks, a legal but unusable field produces a QueryException at run time. That is a correctness problem, not an injection problem, but it is still better to catch it early with a clear message.
Describing objects
For object names, Schema.getGlobalDescribe() returns a Map<String, Schema.SObjectType>. Its keys are lowercase object API names, and lookups ignore case.
public with sharing class ObjectResolver {
public static Schema.SObjectType resolveObject(String objectName) {
if (String.isBlank(objectName)) {
throw new IllegalArgumentException('Object name is required');
}
Schema.SObjectType objectType = Schema.getGlobalDescribe().get(objectName.trim());
if (objectType == null) {
throw new IllegalArgumentException('Unknown object');
}
Schema.DescribeSObjectResult describe = objectType.getDescribe();
if (!describe.isAccessible() || !describe.isQueryable()) {
throw new IllegalArgumentException('Object is not available');
}
return objectType;
}
}The object-level check uses isAccessible() for read access and isQueryable() for whether SOQL can run against the type at all.
The global describe is a large map, because it covers every object in the org. It is slower than a field lookup. Call it once per transaction when you can. If you only need a few objects, Schema.describeSObjects(new List<String>{ name }) describes just those names. It throws an InvalidParameterValueException for an unknown name, so wrap it in a try/catch.
A complete query builder
This class combines both resolvers. It takes an object name, a list of fields, a sort field, and a direction, and it returns records. Every identifier passes through describe. The sort direction comes from a fixed choice, and the limit is typed.
public with sharing class SafeQueryBuilder {
private static final Integer MAX_ROWS = 200;
public static List<SObject> query(
String objectName,
List<String> fieldNames,
String sortField,
String direction,
Integer maxRows
) {
Schema.SObjectType objectType = ObjectResolver.resolveObject(objectName);
if (fieldNames == null || fieldNames.isEmpty()) {
throw new IllegalArgumentException('At least one field is required');
}
List<String> selectList = new List<String>();
for (String fieldName : fieldNames) {
selectList.add(FieldResolver.resolveField(objectType, fieldName).getName());
}
String soql = 'SELECT ' + String.join(selectList, ', ')
+ ' FROM ' + objectType.getDescribe().getName();
if (String.isNotBlank(sortField)) {
Schema.DescribeFieldResult sortDescribe =
FieldResolver.resolveField(objectType, sortField);
if (!sortDescribe.isSortable()) {
throw new IllegalArgumentException('Field cannot be sorted');
}
String dir = (direction != null && direction.equalsIgnoreCase('DESC'))
? 'DESC' : 'ASC';
soql += ' ORDER BY ' + sortDescribe.getName() + ' ' + dir;
}
Integer rows = (maxRows == null || maxRows < 1) ? 50 : Math.min(maxRows, MAX_ROWS);
soql += ' LIMIT ' + rows;
return Database.query(soql, AccessLevel.USER_MODE);
}
}Here is how the code builds the query for SafeQueryBuilder.query('account', new List<String>{ 'NAME', 'industry' }, 'createddate', 'desc', 25):
SELECT Name, Industry FROM Account ORDER BY CreatedDate DESC LIMIT 25The caller used inconsistent casing, but the query uses the canonical names. That is a side benefit of building from getName() instead of the original input.
Edge cases and common errors
Relationship paths
A name like Owner.Name or Account.Industry is not a key in the field map. Describe rejects it, and in most cases that is the safe default. If you need relationship fields, resolve each segment separately. Split on the dot, look up the relationship field on the first object, follow getReferenceTo() to the parent type, and look up the next segment there. Keep the depth to a small fixed number, and validate every segment.
Object and field names are different attack surfaces
Validating the field against the wrong object is a common mistake. If you resolve the object first and then use Schema.SObjectType.Account.fields.getMap() out of habit, the check will pass for Account fields while the query runs against whatever object the user chose. Always pass the same Schema.SObjectType you resolved to the field resolver, as SafeQueryBuilder does.
Using the input instead of the result
The point of describe is that you paste in what the platform returned. This code looks safe but is not:
Schema.SObjectField f = fieldMap.get(fieldName);
if (f != null) {
soql += ' ORDER BY ' + fieldName; // still the attacker's string
}The lookup ignores case and might also tolerate whitespace in some code paths you add later. Use f.getDescribe().getName() so the query text can only be a known API name.
Dropping the check on null
Map.get returns null for a missing key, and calling getDescribe() on null throws a NullPointerException. That error is not an injection, but it is a bad failure mode for a public endpoint. Check for null first and throw a clear exception, as shown above.
Hidden and managed-package fields
Describe can return fields from managed packages that the org's users cannot see. The isAccessible() check covers this for the running user. A field that exists but is hidden by FLS fails the check, which is correct.
Describe results are not cached across transactions
Each transaction builds its own results. If a service is called many times in one transaction, keep a static Map<String, Map<String, Schema.SObjectField>> keyed by object name so the field map is fetched once per object.
Enforcing access at query time
Describe validation answers one question: is this name legitimate? It does not stop a user from reading rows or fields they should not see, and it runs in code you control. Run the query in user mode too. AccessLevel.USER_MODE applies sharing rules, object permissions, and FLS to the query itself. The builder above already passes it to Database.query.
The two layers do different jobs:
- Describe checks reject bad names early with a clear message, and keep injected text out of the query.
- User mode makes the database enforce permissions even if a describe check is missed or an edge case slips through.
Testing the validators
Tests should cover three groups: valid names, names with the wrong case, and attack strings. The test below uses standard Account fields, so it needs no setup data.
@IsTest
private class SafeQueryBuilderTest {
@IsTest
static void validNamesRunWithCanonicalCase() {
insert new Account(Name = 'Acme', Industry = 'Energy');
List<SObject> rows = SafeQueryBuilder.query(
'account', new List<String>{ 'NAME', 'industry' }, 'name', 'desc', 10
);
Assert.areEqual(1, rows.size());
}
@IsTest
static void injectedFieldNameIsRejected() {
try {
SafeQueryBuilder.query(
'Account', new List<String>{ 'Name FROM User --' }, null, null, 10
);
Assert.fail('Expected IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.areEqual('Unknown field', e.getMessage());
}
}
@IsTest
static void injectedSortFieldIsRejected() {
try {
SafeQueryBuilder.query(
'Account', new List<String>{ 'Name' }, 'Name; DELETE', 'ASC', 10
);
Assert.fail('Expected IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.areEqual('Unknown field', e.getMessage());
}
}
@IsTest
static void unknownObjectIsRejected() {
try {
SafeQueryBuilder.query(
'Account WHERE Id != null', new List<String>{ 'Name' }, null, null, 10
);
Assert.fail('Expected IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.areEqual('Unknown object', e.getMessage());
}
}
}Place Assert.fail inside the try block, as shown. When the validator wrongly accepts the payload, the failure message tells you so. One subtlety is that Assert.fail throws an AssertException, which is not an IllegalArgumentException. The catch clause lets it propagate and fail the test, which is what you want.
Summary of the pattern
- Treat object, field, and sort names as untrusted input, even when they come from your own UI.
- Resolve the object first with a describe lookup. Reject
null. - Resolve each field against that object. Reject
null, and check the property the clause needs:isAccessible,isFilterable, orisSortable. - Build the query from
getName()values, not from the raw input. - Choose the sort direction from two literals, and convert limits to
Integer. - Run with
AccessLevel.USER_MODEand bind variables for values.
Exercise
A developer validates a sort field with Map<String, Schema.SObjectField> m = Account.SObjectType.getDescribe().fields.getMap(); if (m.containsKey(sortField)) { soql += ' ORDER BY ' + sortField; }. The input Name passes and Name; DELETE fails. What weakness remains, and how do you fix it?
Show answer
The query uses the raw input string instead of the platform's canonical name, and it does not check isSortable(). A field that is in the map but not sortable, such as a long text area, causes a run-time QueryException. Case or other differences between the input and the real name also flow into the query text. Fix it by getting the field with m.get(sortField), rejecting null, checking getDescribe().isSortable(), and appending getDescribe().getName() to the query.
Exercise
Why can a dynamic query builder that accepts an object name from the user still be unsafe if it validates the field names against Schema.SObjectType.Account.fields.getMap()?
Show answer
The field check is tied to Account, but the query runs against the object the user named. Fields valid on Account say nothing about the chosen object, and the object name itself has not been validated. The fix is to resolve the object name through describe first, reject null, and validate each field against the Schema.SObjectType that was resolved.
Exercise
Name two things user mode (AccessLevel.USER_MODE) does that describe checks alone do not.
Show answer
User mode makes the query itself enforce sharing rules, so the user sees only the rows they are allowed to see. It also enforces object permissions and field-level security inside the query, even if a describe check was missed or skipped. Describe checks only run where your code calls them and do not apply sharing.