We are going to design a GraphQL security guardhouse that:
- Enforces auth directives: meaning that certain fields or types require authentication/authorization.
- Implements depth limits: to prevent overly nested queries that could be used for DoS attacks.
- Query cost analytics: to track and limit the cost of a query (based on field complexity and depth).
We'll assume we are using Apollo Server (or a similar GraphQL server) and we'll write the necessary middleware/plugins.
Steps:
-
Auth Directives:
- We can define a custom directive, e.g.,
@auth(requires: UserRole!), and then use it in the schema.
- We'll need to implement a directive transformation that checks the user's role (or authentication status) and throws an error if not allowed.
-
Depth Limit:
- We can use a validation rule that limits the depth of the query. We'll calculate the depth of the query and if it exceeds a threshold, we reject it.
-
Query Cost Analytics:
- We can assign a cost to each field (maybe by default 1, but can be customized) and then calculate the total cost of the query by summing the costs along the way, taking into account the depth (nested fields are multiplied by a factor?).
- We can also set a maximum cost per query and reject if exceeded.
Implementation:
We'll create:
- A custom directive for auth.
- A validation rule for depth.
- A validation rule (or a plugin) for query cost.
However, note that Apollo Server allows us to write plugins for request/response lifecycle and also to extend the validation phase.
Let's break it down:
Part 1: Auth Directive
We'll define a directive in the schema:
directive @auth(requires: UserRole = ADMIN) on FIELD_DEFINITION | OBJECT
Then, we'll implement a transformer for the schema that adds the appropriate checks.
But note: Apollo Server does not have built-in support for custom directives in the same way as, say, Graphene (Python). We can use the graphql-tools to transform the schema.
Alternatively, we can use field-level middleware (resolver wrappers) but we want a directive-based approach.
Since we are using Apollo Server, we can use the SchemaDirectiveVisitor from apollo-server-plugin-base? Actually, Apollo Server 2 and 3 have different ways.
However, the user's request does not specify the version. Let's assume we are using Apollo Server 3 or 4, which uses @graphql-tools for schema transformations.
Alternatively, we can do:
- Define the directive in the SDL.
- Then, when creating the schema, use
mapSchema and getDirective to modify the resolvers.
But note: the user's request says "enforcing auth directives", so we want to enforce at the schema level.
Another approach: use a validation rule that checks for fields with @auth and then in the resolver, we check the context for the user.
However, we want the directive to be enforceable in the schema, meaning that even if someone bypasses the resolver (by using a different tool) the validation should catch it.
Actually, the directive is part of the schema, so if we don't implement the resolver for the directive, it won't do anything. So we must implement the directive's behavior.
Let's choose the schema transformation approach:
We'll create a function that transforms the schema by visiting each field (or object) that has the @auth directive and then wrap the resolver with an auth check.
Steps for auth:
For each field (or object) with @auth directive, we'll replace its resolver with a function that:
1. Checks the context for the user (or whatever we use for authentication).
2. Checks if the user has the required role (from the directive argument).
3. If yes, call the original resolver, else throw an error.
But note: the directive can be on an object, meaning that all fields in that object require auth. So we have to handle both.
We can use mapSchema from @graphql-tools/utils to traverse the schema and modify.
Example code for auth directive transformation:
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
const authDirectiveTransformer = (schema) => mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (field) => {
const authDirective = getDirective(schema, field, 'auth');
if (authDirective) {
const { resolve = field.resolve } = field;
const requires = authDirective[0].requires;
field.resolve = async function (...args) {
const { context } = args[2];
// Assume context.user exists and has a role
if (!context.user || !context.user.roles.includes(requires)) {
throw new Error('Not authorized');
}
return resolve.apply(this, args);
};
}
return field;
},
[MapperKind.OBJECT_TYPE]: (objectType) => {
const authDirective = getDirective(schema, objectType, 'auth');
if (authDirective) {
// For an object type, we want to wrap every field of that type?
// Actually, the directive on an object type means that all fields of that type require auth.
// We can modify the object type's fields by returning a new object type with modified fields?
// Alternatively, we can loop over the fields and apply the same logic as above.
// But note: the object type's fields are not visited by the field mapper if we are in the object type mapper?
// We can return the object type as is and rely on the field mapper to pick up the directive on the object type?
// Actually, the directive on an object type is attached to the object type, not to each field.
// We need to change the behavior for every field of this object type. So we have to modify each field.
// However, the `mapSchema` function will visit each field anyway, and when we visit a field, we can check if its parent type has the directive.
// So in the field mapper, we can also check:
// const parentAuthDirective = getDirective(schema, field.parentType, 'auth');
// if (parentAuthDirective) { ... }
// But note: the field might have its own auth directive, which overrides? We can decide: if the field has its own, use that, else if the parent type has, use that.
// Alternatively, we can handle the object type by modifying its fields here.
// Let's do: in the field mapper, we check both the field and the parent type for the directive.
// So we don't need to handle the object type in this mapper? Actually, we can skip the object type mapper and only use the field mapper.
// But the directive can be on the object type and we want it to apply to all fields. So in the field mapper:
// const fieldAuth = getDirective(schema, field, 'auth');
// const parentAuth = getDirective(schema, field.parentType, 'auth');
// const authDirective = fieldAuth || parentAuth;
// Then if authDirective exists, we wrap.
// So we can skip the object type mapper.
// However, the user might put the directive on the object type and then override on a specific field? Then we should use the field's directive if present.
// So in the field mapper:
// const authDirective = getDirective(schema, field, 'auth') || getDirective(schema, field.parentType, 'auth');
// But note: the directive might be on the object type and the field might not have it. Then we use the object's.
// So we'll only use the field mapper.
// Therefore, we can remove the object type mapper and only handle fields.
// However, the directive might be on the object type and we are not visiting the object type, but we are visiting its fields, so we can get the parent type.
// So we'll just use the field mapper and check both.
}
return objectType;
}
});
But note: the object type mapper is not needed if we handle it in the field mapper.
Let's change: we'll only use the field mapper and check for the directive on the field and on the parent type.
However, what about interfaces? The directive might be on an interface. Then any object that implements the interface should have the same auth?
We can also check the interfaces of the parent type.
But to keep it simple, let's assume the directive is only on fields and object types (and we only check the immediate parent type).
We can extend to interfaces by:
const parentType = field.parentType;
const interfaces = parentType.interfaces || [];
const interfaceAuth = interfaces.map(iface => getDirective(schema, iface, 'auth')).find(d => d);
But the user might have put the directive on an interface and then implemented by an object. We want the directive from the interface to apply?
Actually, the directive on an interface should apply to all fields of the implementing object? Or only the fields that are in the interface?
This gets complex. Let's stick to field and object type for now.
So in the field mapper:
const authDirective = getDirective(schema, field, 'auth') || getDirective(schema, field.parentType, 'auth');
Then if authDirective exists, we wrap the resolver.
But note: the field might already have a resolver. We are going to wrap the existing resolver.
However, what if the field is from an interface? Then the parent type is the implementing object type? Actually, the field.parentType is the object type that defines the field, not the interface.
So if the directive is on the interface, we won't pick it up because the field's parentType is the object type.
We would have to check the interfaces of the parent type.
Alternatively, we can change the way we get the directive: we can look for the directive on the field, then on the field's parent type, then on every interface of the parent type.
But to avoid complexity, let's assume the directive is only on the field or the object type that defines the field.
So:
const authDirective = getDirective(schema, field, 'auth') || getDirective(schema, field.parentType, 'auth');
Then, if we find it, we wrap.
But note: the directive might be on an interface that the parent type implements, but the field might be from that interface. Then we want the auth from the interface.
Actually, the field might be defined in the interface and the object type might not define it. Then the field's parentType is the interface? Or the object type?
In GraphQL, when you have an interface, the fields of the interface are available on the object type. The field's parentType is the object type? Or the interface?
According to the GraphQL spec, the field is defined in the parent type (the object type or the interface). But in the schema, the field might be defined in the interface and then the object type inherits it.
In graphql-js, when you have an interface, the fields of the interface are added to the object type. So the field's parentType is the object type? Actually, I think it's the object type.
Let me check: if we have:
interface Node { id: ID! }
type User implements Node { id: ID!, name: String }
Then the field id in User has parentType User, not Node.
So we won't get the directive from Node by checking only the parent type.
Therefore, we must check the interfaces of the parent type.
We can do:
const parentType = field.parentType;
let authDirective = getDirective(schema, field, 'auth') || getDirective(schema, parentType, 'auth');
if (!authDirective) {
for (const iface of parentType.interfaces) {
authDirective = getDirective(schema, iface, 'auth');
if (authDirective) break;
}
}
Then, if authDirective exists, we wrap.
But note: the directive might be on the field and also on the interface? Then we use the field's? That's the order we are checking.
This is getting complex. We might want to use a library that already handles this? Or we can simplify the requirement: only field and object type.
Given the complexity, let's assume we are only going to support field and object type for the auth directive.
So we'll do:
const authDirective = getDirective(schema, field, 'auth') || getDirective(schema, field.parentType, 'auth');
And if we find it, we wrap.
But note: the directive might be on the object type and the field might be from an interface. Then the field's parentType is the object type, so we get the object type's directive.
However, if the field is defined in the interface and the object type does not define it, then the field's parentType is the interface? Actually, no, the field is on the object type because the object type implements the interface.
I think we are safe with just checking the field and the object type (the parentType of the field).
But what if the object type does not have the directive but one of its interfaces does? Then we miss it.
Since this is a security feature, we might want to be safe and check all interfaces.
Let's do:
const authDirective = getDirective(schema, field, 'auth') ||
getDirective(schema, field.parentType, 'auth') ||
(field.parentType.interfaces || []).some(iface => getDirective(schema, iface, 'auth'));
But then we don't know which interface's directive to use? We can use the first one we find? But the requires might be different.
Alternatively, we can require that the directive is only on the field or the object type, and not on interfaces.
Given the time, let's stick to field and object type.
We'll change the requirement: the directive can be placed on a field or an object type (that defines the field). We won't support interfaces.
So:
const authDirective = getDirective(schema, field, 'auth') || getDirective(schema, field.parentType, 'auth');
If found, we use the requires from that directive.
Implementation:
We'll create a function that takes the schema and returns a new schema with the auth checks.
However, note that the directive might have an argument requires which is an enum (UserRole). We'll assume the enum is defined.
We'll have to import the enum or get it from the schema? We can get the enum from the directive's definition.
But for simplicity, we'll assume the context has a user with a roles array.
Code:
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
const authDirectiveTransformer = (schema) => {
return mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const authDirective = getDirective(schema, fieldConfig, 'auth') || getDirective(schema, fieldConfig.parentType, 'auth');
if (authDirective) {
const { resolve = fieldConfig.resolve } = fieldConfig;
const requires = authDirective[0].requires; // This is the enum value, e.g., 'ADMIN'
fieldConfig.resolve = async function (...args) {
const { context } = args[2];
if (!context.user || !context.user.roles.includes(requires)) {
throw new Error('Not authorized');
}
return resolve.apply(this, args);
};
}
return fieldConfig;
}
});
};
Then, when building the schema:
const schema = makeExecutableSchema({ typeDefs, resolvers });
const schemaWithAuth = authDirectiveTransformer(schema);
But note: the directive might be on an object type that doesn't have any fields? Actually, every object type has fields. So we are covered.
- Depth Limit:
We can write a validation rule that calculates the depth of the query.
We'll create a rule that visits each field and tracks the depth.
We can use the validate function from GraphQL and add our rule.
Example:
import { ValidationContext, visit } from 'graphql';
const depthLimitRule = (maxDepth) => {
return {
ValidationContext: (context) => {
return new DepthLimitValidator(context, maxDepth);
}
};
};
But we can write a simple rule:
class DepthLimitValidator {
constructor(context, maxDepth) {
this.context = context;
this.maxDepth = maxDepth;
this.currentDepth = 0;
}
enterField(node, key, parent, path, ancestors) {
this.currentDepth++;
if (this.currentDepth > this.maxDepth) {
this.context.reportError(new GraphQLError(`Query is too nested: maximum depth of ${this.maxDepth} exceeded`, [node]));
}
}
leaveField(node, key, parent, path, ancestors) {
this.currentDepth--;
}
}
But note: the enterField and leaveField are called for every field in the query.
We have to be careful: the same field might appear multiple times in different branches? We are using a stack (currentDepth) so it should be okay.
However, what about fragments? The validator should also handle fragments.
Actually, the visit function will traverse the entire query, including fragments, and we are using a simple counter that goes up and down.
But fragments are inlined, so the depth calculation should be correct.
We can use the validate function from graphql and add our rule.
Then, when validating the query, we use:
const errors = validate(schema, document, [depthLimitRule(5)]);
But note: we are already using Apollo Server, which does validation by default. We want to add our rule to the existing validation rules.
In Apollo Server, we can set validationRules in the server configuration.
Example:
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [depthLimitRule(5)],
});
But note: the auth directive transformation is at the schema level, not at validation.
So we have two separate mechanisms:
- Auth: schema transformation (resolver wrapping)
- Depth: validation rule
However, the depth rule must be added to the validation rules of the server.
- Query Cost Analytics:
We want to assign a cost to each field and then calculate the total cost of the query, and reject if it exceeds a threshold.
We can do this in two ways:
a) As a validation rule that calculates the cost during validation and rejects if too high.
b) As a server plugin that runs after validation and before execution, and then rejects if too high.
However, the cost might depend on the arguments? For example, a field that takes a list of IDs might cost more if the list is long.
But in the validation phase, we don't have the variables. So we cannot calculate the exact cost.
Therefore, we might want to do it in a plugin that runs with the query and variables.
Alternatively, we can assign a base cost to each field and then multiply by the number of items in a list? But we don't know the list length until we have the variables.
So let's assume:
- Each field has a base cost (default 1).
- For fields that return a list, we multiply the base cost by the maximum possible list size? But that's not safe.
Alternatively, we can use a heuristic: for list fields, we assume a fixed size (or the length of the variable if provided) but that requires parsing the variables.
This is complex.
Alternatively, we can do:
- Assign a cost to each field (including lists) and then when calculating the total cost, we multiply the cost of a list field by the length of the list (if known) or by 1 (if not known) and then set a maximum cost.
But without the variables, we don't know the list length.
So maybe we do:
- In the validation rule, we calculate the cost without considering the list lengths (so we assume each list field returns 1 item). Then we have a base cost.
- Then, in a plugin, after we have the variables, we can adjust the cost by multiplying the list fields by the actual list length (if the variable is provided and is a list).
However, the query cost might be used to limit the query before execution, so we want to reject expensive queries early.
We can do:
Step 1: During validation, calculate the base cost (without list multipliers) and if that base cost exceeds a threshold (say 1000), reject.
Step 2: After we have the variables, recalculate the cost with the actual list lengths and if it exceeds a higher threshold (say 5000), reject.
But then we have two thresholds.
Alternatively, we can do the entire cost calculation in the plugin with the variables, but then we are executing the query partially? We want to reject before execution.
Actually, we can do:
- In the validation rule, we calculate the cost without list multipliers and set a threshold for that (say 1000). This is to prevent very deep and wide queries.
- Then, in the plugin, we recalculate the cost with the actual list lengths and set a higher threshold (say 5000). If the cost with actual list lengths exceeds 5000, we reject.
But note: the validation rule runs first, and if it fails, we don't run the plugin.
So we can have two separate checks.
However, the user might set the same threshold? We can make it configurable.
Alternatively, we can do the entire cost calculation in the plugin and set a threshold, but then we are not protecting against queries that are expensive even without the list multipliers (like very deep queries).
So let's do:
- Validation rule: base cost (each field cost 1, list fields cost 1 per item? but we don't know the items, so we assume 1) and a max depth? Actually, the depth limit is separate.
We are already doing depth limit separately.
So for the cost, we can do:
cost = sum( field_cost for each field in the query )
where field_cost is 1 by default, but can be overridden by a directive, e.g., `@cost(amount: Int!)`.
Then, we can also have a multiplier for list fields? But without the variables, we don't know the list length.
So we can ignore list length in the validation rule and just use 1 for every field, regardless of list.
Then in the plugin, we adjust the cost for list fields by multiplying by the actual list length (if the variable is a list) or by 1 if not.
But note: the list field might be at any level, and we have to multiply the cost of the list field and all its children?
Actually, if a field returns a list, then each item in the list will have the same subfields. So the total cost for that list field and its children would be:
cost = base_cost_of_list_field + (number_of_items * (cost of the subfields))
So we need to traverse the query and for each list field, multiply the cost of the subtree by the number of items.
How do we get the number of items? From the variables.
Steps for the plugin:
- We have the query and the variables.
- We traverse the query and for each field, we calculate the cost.
- If the field is a list, we look at the variable (if any) that corresponds to the argument that controls the list (like `first`, `last`, or the list itself) and get the length.
But note: the list might be controlled by an argument that is a variable, or a literal.
We can do:
For each field that returns a list:
- Look at the arguments that are of type list? Or the argument that is known to control the pagination? This is complex.
Alternatively, we can assign a cost to each field and then when we have the variables, we multiply the cost of the list field and all its children by the length of the list variable (if present).
But how do we know which argument is the list? We can look at the field's arguments and see which one is of type [Type] and then get the value from the variables.
However, the field might have multiple list arguments? Then we have to decide which one to use? Or multiply by all?
This is getting too complex for a simple example.
Given the complexity, let's simplify:
We'll assign a cost to each field (by default 1) and then in the validation rule, we calculate the total cost as the number of fields (including nested ones) but without considering list multipliers.
Then, we set a max cost (say 100) and reject if the number of fields exceeds 100.
This is a simple way to limit the query complexity.
But note: the user might want to set different costs for different fields. We can support a @cost directive.
So:
Step 1: Define a `@cost(amount: Int!)` directive that can be placed on fields.
Step 2: In the validation rule, we traverse the query and for each field, we get the cost from the directive (if present) or use 1.
Step 3: Sum the costs of all fields (including nested ones) and if the sum exceeds a threshold, reject.
We don't consider list multipliers because we don't have the variables.
Then, in the plugin, we can do a more accurate cost calculation with the variables, but if the base cost already exceeds a threshold, we reject.
Alternatively, we can do the entire cost calculation in the plugin and set a threshold, and skip the validation rule for cost.
But then we are executing the query (at least partially) to calculate the cost? We want to reject before execution.
Actually, the plugin runs after validation and before execution. So we can calculate the cost in the plugin and reject.
So we can skip the validation rule for cost and do it in the plugin.
Let's do:
- We'll create a plugin that runs in the `willResolveField` or `executionWillStart`? We want to calculate the total cost of the query.
But note: the query might have multiple root fields. We want the total cost.
We can calculate the cost by traversing the query AST and summing the costs of each field, and for list fields, multiply by the list length (from variables).
But we need the variables to get the list length.
We can do:
In the plugin's `requestDidStart` we have the request object, which contains the query and the variables.
Then we can traverse the query and calculate the cost.
If the cost exceeds the threshold, we throw an error and stop the execution.
Steps:
1. Parse the query AST (we have it in the request).
2. Traverse the AST and for each field, get the cost (from the directive or default 1).
3. For list fields, get the argument that is a list (or the argument that controls the list) and get the length from the variables (if the variable is provided and is a list, otherwise assume 1).
4. Multiply the cost of the list field and all its children by the list length? Actually, we have to multiply the entire subtree.
But note: the subtree might have multiple list fields? Then we multiply by each list's length? That would be exponential.
Example:
query {
users { # list of 10
posts { # list of 5 for each user
comments { # list of 3 for each post
...
}
}
}
}
The cost for the inner most field would be multiplied by 10 * 5 * 3.
So we need to traverse the tree and at each list field, multiply the current cost multiplier by the list length.
We can do:
function calculateCost(node, variables, currentMultiplier = 1) {
let cost = 0;
if (node.kind === 'Field') {
const fieldCost = getFieldCost(node, variables); // base cost for this field (without multiplier)
cost += fieldCost * currentMultiplier;
// Now, for each argument that is a list, we adjust the multiplier for the child fields?
// Actually, the list is in the selection set of this field? No, the list is at this field if the field returns a list.
// But note: the field might have an argument that is a list, but that argument might not control the list of the field's return type? Actually, the argument is an input to the field.
// The list that we care about is the return type of the field? Or the argument?
// In GraphQL, the cost of a field that returns a list is multiplied by the number of items in the list.
// So we need to know the return type of the field. We can get it from the schema.
// But we are traversing the AST, we don't have the schema? We can pass the schema.
}
// Then, for each selection (child field) of this node (if it's a field with a selection set), we recurse.
}
This is very complex.
Given the time, let's do a simpler version:
We'll assign a cost to each field (default 1) and then in the plugin, we traverse the query and for each field, we add the cost. We ignore list multipliers.
Then we set a threshold (say 100) and reject if the total cost (sum of all field costs) exceeds 100.
This is a simple way to limit the query complexity without considering the list lengths.
But note: a query that selects 100 fields will cost 100, and a query that selects 1 field but with 100 nested fields (depth 100) will also cost 100? Actually, the nested fields are counted individually.
So:
query {
user {
id
name
friends { # list, but we ignore the list length, so we add 1 for the field 'friends' and then 1 for each field in the friends sub-selection?
id
name
}
}
}
The fields: user, id, name, friends, (friends subfields) id, name -> total 6.
So we are counting each field once, regardless of how many times it appears in the list? Actually, the list field 'friends' is counted once, and then its subfields are counted once.
But in reality, if 'friends' returns a list of 10, then we are actually fetching 10 * (cost of friends subfields). So we are underestimating.
But without the list length, we cannot do better.
So we'll do:
- Validation rule: depth limit (to prevent very deep queries).
- Cost rule: count the number of fields (including nested) and set a threshold.
And then we can add a @cost directive to override the cost of a field.
Steps for cost:
a. Define the `@cost` directive in the schema.
b. In the plugin, traverse the query and for each field, get the cost from the directive (if present) or use 1.
c. Sum the costs.
d. If the sum exceeds the threshold, throw an error.
We can do this in the requestDidStart hook of the plugin.
Code for the cost plugin:
import { GraphQLSchema, GraphQLFieldResolver, visit, print } from 'graphql';
const costPlugin = {
requestDidStart: (requestContext) => {
const { request, schema } = requestContext;
const document = request.document;
const variables = request.variables;
let totalCost = 0;
const visitOptions = {
[VisitKind.ENTER]: (node, key, parent, path, ancestors) => {
if (node.kind === 'Field') {
// Get the field definition from the schema
const fieldNode = node;
const fieldName = fieldNode.name.value;
const parentType = getParentType(ancestors, schema); // We need a function to get the parent type from the ancestors
// Actually, the ancestors array contains the nodes from root to the current node. The parent type is the type of the parent node (which is an ObjectType or InterfaceType).
// We can get the parent type from the parent node (which is an ObjectType or InterfaceType) by looking at the schema.
// But note: the parent node might be an OperationDefinition (for root fields) or a Field node (for nested fields).
// For root fields, the parent is the operation definition, and we get the root type (Query, Mutation, Subscription) from the operation.
// We can get the parent type by:
// const parentNode = ancestors[ancestors.length - 1];
// let parentType;
// if (parentNode.kind === 'OperationDefinition') {
// parentType = schema.getQueryType(); // or mutation or subscription based on operation
// } else if (parentNode.kind === 'Field') {
// const parentFieldDef = schema.getType(parentNode.name.value).getFields()[parentNode.name.value];
// parentType = parentFieldDef.type; // but this is the return type, not the parent type? Actually, the parent type is the type of the parent node.
// }
// Actually, the parent type of a field is the type of the object that the field belongs to.
// We can get the field definition by:
// const fieldDef = parentType.getFields()[fieldName];
// But we don't have parentType.
// Alternatively, we can use the `GraphQLSchema` to get the field by the path.
// There is a utility: `getFieldDef` from `graphql/utilities`? Actually, `graphql/utilities` has `getFieldDef` but it's not exported.
// We can use:
// import { getFieldDef } from 'graphql/utilities/schema/operationType';
// But it's not recommended.
// Alternatively, we can traverse the schema to get the field.
// Given the complexity, let's assume we have a function that given the field name and the parent type (as a string) returns the field definition.
// But we don't have the parent type name? We can get it from the parent node.
// Actually, the parent node (if it's a Field) has a name, and that name is the field name of the parent, and we can get the parent's return type from the schema.
// This is getting too complex for a simple example.
// Given the time, let's assume we have a way to get the field definition.
// Alternatively, we can store a map of field costs in a separate data structure and look up by the field's full path (like "User.name")?
// But the same field can appear in different types? Actually, no, the field is defined in a specific type.
// So we can use the field's name and the parent type name.
// We can get the parent type name from the parent node:
// const parentNode = ancestors[ancestors.length - 1];
// let parentTypeName;
// if (parentNode.kind === 'OperationDefinition') {
// parentTypeName = parentNode.operation; // 'query', 'mutation', etc.
// // But we need the root type name? Actually, the root type is 'Query', 'Mutation', etc.
// // We can get the root type from the schema:
// // if (parentNode.operation === 'query') parentTypeName = 'Query';
// // else if (parentNode.operation === 'mutation') parentTypeName = 'Mutation';
// // else if (parentNode.operation === 'subscription') parentTypeName = 'Subscription';
// } else if (parentNode.kind === 'Field') {
// parentTypeName = parentNode.name.value;
// }
// Then we have the field name and the parent type name.
// But note: the field might be from an interface? Then the parent type is the interface? But the field's parentType in the AST is the object type that defines the field? Actually, the field in the query is on an object type (concrete) or an interface?
// In the query, we can query on an interface? Only if we are using fragments on interfaces.
// This is getting too complex.
// Given the time, let's do a simpler approach:
// We'll not use the schema to get the field definition. Instead, we'll rely on a separate map that we build from the schema at startup.
// We can build a map: key = `${parentTypeName}.${fieldName}`, value = cost (from the directive or default 1).
// Then in the plugin, we get the parent type name (as above) and the field name, and look up the cost.
// But we have to build that map from the schema.
// Steps:
// function buildCostMap(schema) {
// const costMap = {};
// const typeMap = schema.getTypeMap();
// for (const typeName in typeMap) {
// const type = typeMap[typeName];
// if (type.astNode) {
// const fields = type.getFields();
// for (const fieldName in fields) {
// const field = fields[fieldName];
// const costDirective = getDirective(schema, field.astNode, 'cost');
// const cost = costDirective ? costDirective[0].amount : 1;
// costMap[`${typeName}.${fieldName}`] = cost;
// }
// }
// }
// return costMap;
// }
// Then in the plugin, we use that map.
// But note: the field in the query might be from an interface? Then the parent type name is the concrete type? Actually, the query field is on a concrete type.
// So we are safe.
// However, what about root fields? The parent type for root fields is the root type (Query, Mutation, Subscription). So the key would be `Query.fieldName`.
// So we need to get the parent type name for root fields correctly.
// For a root field, the parent node is the operation definition. We can get the operation type:
// if (parentNode.kind === 'OperationDefinition') {
// const operation = parentNode.operation;
// if (operation === 'query') parentTypeName = 'Query';
// else if (operation === 'mutation') parentTypeName = 'Mutation';
// else if (operation === 'subscription') parentTypeName = 'Subscription';
// }
// Then the field name is `fieldNode.name.value`.
// So the key is `${parentTypeName}.${fieldNode.name.value}`.
// Then we look up in the costMap.
// If not found, we use 1.
// Then we add the cost to totalCost.
// But note: the same field might appear multiple times in the query (in different branches). We are counting each occurrence.
// That's what we want.
}
}
};
visit(document, visitOptions);
const maxCost = 100; // threshold
if (totalCost > maxCost) {
throw new Error(`Query cost too high: ${totalCost} (max ${maxCost})`);
}
}
};
But note: the visit function we are using is from graphql/language/visitor? Actually, we can use visit from graphql.
However, we need the ancestors array to get the parent node.
The visit function from graphql provides the ancestors as an array of nodes.
So we can do:
import { visit, VisitInfo } from 'graphql';
Then in the visitor:
[VisitKind.ENTER]: (node, key, parent, path, ancestors) => {
// ancestors is an array of nodes, from root to the parent of the current node.
// So the parent of the current node is ancestors[ancestors.length - 1].
}
But note: the ancestors array does not include the current node.
So for a field node, the parent node is the last element in ancestors.
We'll get the parent node and then get its name (if it's a field) or operation (if it's an operation).
Code for getting parent type name:
function getParentTypeName(ancestors) {
if (ancestors.length === 0) {
return null;
}
const parentNode = ancestors[ancestors.length - 1];
if (parentNode.kind === 'OperationDefinition') {
const operation = parentNode.operation;
if (operation === 'query') return 'Query';
if (operation === 'mutation') return 'Mutation';
if (operation === 'subscription') return 'Subscription';
throw new Error(`Unknown operation: ${operation}`);
}
if (parentNode.kind === 'Field') {
return parentNode.name.value;
}
// For other node kinds? We might have FragmentSpread, InlineFragment, etc.
// We can ignore and return null? Then we won't find the cost for that field? But the field's parent is a field or operation.
// Actually, the field's parent can be a SelectionSet, which is not a type. So we have to go up until we find an operation or field.
// But the ancestors array includes the parent node, which for a field is usually a SelectionSet? Actually, the parent of a Field node is a SelectionSet.
// Wait, the ancestors array in the `visit` function includes the nodes that are parents in the AST, not the parent type.
// So the parent of a Field node is a SelectionSet? Actually, in the AST, the Field node is inside a SelectionSet. So the parent node is a SelectionSet.
// This is not what we want.
// We want the parent type (the type that the field belongs to). That information is not in the AST. We have to get it from the schema.
// So we have to use the schema to resolve the parent type.
// Given the complexity, let's change the plan:
// Instead of trying to get the parent type from the AST, we can traverse the query and for each field, we get the field definition from the schema by resolving the field path.
// We can use `execute` to get the field definitions? That's heavy.
// Alternatively, we can build a map of field costs by the field's full name (including the parent type) and then in the query, we have to know the parent type.
// How to get the parent type from the query? We have to rely on the schema.
// We can use the `GraphQLSchema` to get the field definition by the field name and the parent type? But we don't have the parent type.
// Given the time, let's do:
// We'll assume that the cost map is built with keys that are the field name only? But then fields with the same name in different types would conflict.
// So we must include the parent type.
// How to get the parent type in the query? We have to traverse the query and keep track of the current type.
// We can do:
// Start at the root operation. The root type is known (Query, Mutation, Subscription).
// Then, for each field, the parent type is the previous field's return type (or the root type for the first level).
// We can simulate the type resolution as we traverse.
// Steps:
// let currentType = rootType; // from the operation
// When we enter a field:
// 1. Get the field definition from the currentType.
// 2. The cost for this field is from the field definition's directive or default.
// 3. Then, the currentType becomes the return type of the field (if it's an object, interface, union) for the next nested fields.
// But note: the field might return a scalar, so we don't go deeper.
// Also, the field might return a list, then the currentType becomes the type of the list items? Or we stay at the same type? Actually, for a list, the next field is on the list item type.
// So we have to handle list.
// This is a type resolver for the query.
// Given the complexity, and since this is an example, let's do:
// We'll ignore the parent type and just use the field name. We'll assume that the same field name in different types has the same cost? Or we can define the cost by field name globally.
// But that's not correct.
// Alternatively, we can require that the `@cost` directive is placed on the field in the schema, and then we can build a map by the field's name and the parent type name (as defined in the schema).
// Then in the query, we have to figure out the parent type.
// We can do:
// We'll traverse the query and keep a stack of types.
// At the root, the type is the root type (from the operation).
// For each field, we get the field definition from the current type (on the stack) by the field name.
// Then, we push the return type of the field (if it's an object, interface, union) onto the stack for the nested fields.
// When we leave the field, we pop the stack.
// This is a simple type resolver for the query.
// We can do this in the visitor.
// We'll maintain a stack of types (GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType) in the visitor's context.
// We'll use the `context` object of the visitor to store the stack.
// Steps:
// enterOperation(node) {
// const operation = node.operation;
// let rootType;
// if (operation === 'query') rootType = schema.getQueryType();
// else if (operation === 'mutation') rootType = schema.getMutationType();
// else if (operation === 'subscription') rootType = schema.getSubscriptionType();
// context.stack = [rootType];
// }
// enterField(node) {
const currentType = context.stack[context.stack.length - 1];
const fieldName = node.name.value;
const fieldDef = currentType.getFields()[fieldName];
if (!fieldDef) {
// This should not happen if the query is valid, but just in case.
return;
}
const costDirective = getDirective(schema, fieldDef.astNode, 'cost');
const cost = costDirective ? costDirective[0].amount : 1;
totalCost += cost;
// Now, if the field returns an object, interface, or union, we push the return type onto the stack.
const returnType = fieldDef.type;
if (returnType instanceof GraphQLObjectType ||
returnType instanceof GraphQLInterfaceType ||
returnType instanceof GraphQLUnionType) {
context.stack.push(returnType);
} else if (returnType instanceof GraphQLList) {
// For a list, the item type is returnType.ofType.
// We push the item type? Because the nested fields are on the item type.
const itemType = returnType.ofType;
if (itemType instanceof GraphQLObjectType ||
itemType instanceof GraphQLInterfaceType ||
itemType instanceof GraphQLUnionType) {
context.stack.push(itemType);
}
}
}
leaveField(node) {
// Pop the stack if we pushed something for this field.
// But we only push if the field returns an object/interface/union or a list of such.
// We have to pop exactly once for each push we did in enterField.
// However, we might have pushed in enterField, but what if the field returns a scalar? We didn't push.
// So we need to track whether we pushed.
// Alternatively, we can pop only if the field's return type is object/interface/union or list of such.
// But note: we pushed the item type for a list, so we have to pop that.
// We can store the type we pushed in the node? Or we can just pop the last element if we pushed.
// Since we are doing a depth-first traversal, and we push only when we enter a field that returns an object-like type, then when we leave that field, we pop.
// But what if the field returns a list of objects? We pushed the item type, so we pop the item type.
// However, what if the list is empty? We still pushed.
// So we do:
// In enterField, if we pushed, we set a flag on the node? Or we just pop unconditionally?
// Actually, we only push in enterField if the return type is object-like or list of object-like.
// Then in leaveField, we pop if we had pushed.
// But we don't know if we pushed.
// We can store the length of the stack when we entered the field, and then when leaving, we pop until we get back to that length.
// Alternatively, we can do:
// enterField(node) {
// const currentType = context.stack[context.stack.length - 1];
// ...
// if (shouldPush) {
// context.stack.push(returnTypeOrItemType);
// node.__pushed = true; // mark the node
// }
// }
// leaveField(node) {
// if (node.__pushed) {
// context.stack.pop();
// }
// }
// But we are modifying the node, which might be used elsewhere? It's safe in the visitor.
// Let's do that.
}
This is a simplified type resolver that only handles object, interface, union, and list of these.
It doesn't handle non-null or other wrappers.
But for cost calculation, we care about the fields that are on object types. Scalar fields don't have nested fields.
So we only push if the return type is an object, interface, union, or a list of such.
We'll adjust:
enterField(node) {
const currentType = context.stack[context.stack.length - 1];
const fieldName = node.name.value;
const fieldDef = currentType.getFields()[fieldName];
if (!fieldDef) {
// This might happen if the field is on an interface and the currentType is an object that doesn't have that field?
// But the query should be valid, so we can skip.
return;
}
const costDirective = getDirective(schema, fieldDef.astNode, 'cost');
const cost = costDirective ? costDirective[0].amount : 1;
totalCost += cost;
const returnType = fieldDef.type;
let shouldPush = false;
let pushType = null;
if (returnType instanceof GraphQLObjectType ||
returnType instanceof GraphQLInterfaceType ||
returnType instanceof GraphQLUnionType) {
shouldPush = true;
pushType = returnType;
} else if (returnType instanceof GraphQLList) {
const itemType = returnType.ofType;
if (itemType instanceof GraphQLObjectType ||
itemType instanceof GraphQLInterfaceType ||
itemType instanceof GraphQLUnionType) {
shouldPush = true;
pushType = itemType;
}
}
if (shouldPush) {
context.stack.push(pushType);
node.__pushed = true;
}
}
leaveField(node) {
if (node.__pushed) {
context.stack.pop();
delete node.__pushed;
}
}
But note: the node in the visitor is the AST node, and we are adding a property __pushed. This is acceptable because we are only using it in the same visitor.
Now, we have to handle the operation node:
enterOperation(node) {
const operation = node.operation;
let rootType;
if (operation === 'query') rootType = schema.getQueryType();
else if (operation === 'mutation') rootType = schema.getMutationType();
else if (operation === 'subscription') rootType = schema.getSubscriptionType();
else {
throw new Error(`Unknown operation: ${operation}`);
}
context.stack = [rootType];
}
And we have to handle leaving the operation? We don't need to because the stack will be empty after.
But note: there might be multiple operations? Actually, the document can have multiple operations, but in a request we only execute one. The request.document is the AST of the query that will be executed, which has one operation.
So we are safe.
Now, we have the totalCost.
Then we compare with the threshold.
But note: we are not considering list multipliers because we don't have the variables.
So we set a threshold for the base cost.
We can make the threshold configurable.
Now, we have:
- Auth directive: schema transformation.
- Depth limit: validation rule.
- Cost: plugin that runs after validation and before execution.
We have to combine them.
Let's write the code accordingly.
However, note: the auth directive transformation must be done before we start the server, and the cost plugin and depth rule are added to the server.
Steps for the server:
const schema = makeExecutableSchema({ typeDefs, resolvers });
const schemaWithAuth = authDirectiveTransformer(schema);
const server = new ApolloServer({
schema: schemaWithAuth,
validationRules: [depthLimitRule(10)], // depth limit of 10
plugins: [costPlugin],
});
But note: the cost plugin uses the schema, so we have to pass the schema to the plugin? Or we can get the schema from the requestContext?
In requestDidStart, we have requestContext which has schema.
So we can do:
const costPlugin = {
requestDidStart: (requestContext) => {
const { request, schema } = requestContext;
// ... use schema to build the cost map? But we don't want to build the cost map on every request.
// We can build the cost map once and then use it.
// We can create a function that returns the plugin and takes the schema and the cost threshold.
// But the plugin is an object, and we want to pass the schema and threshold.
// We can do:
// function createCostPlugin(schema, maxCost) {
// const costMap = buildCostMap(schema);
// return {
// requestDidStart: (requestContext) => {
// // use costMap and maxCost
// }
// };
// }
// Then:
// plugins: [createCostPlugin(schemaWithAuth, 100)]
}
};
But note: the schema in the requestContext is the same as schemaWithAuth.
Alternatively, we can build the costMap outside and then use it in the plugin.
Let's do:
const costMap = buildCostMap(schemaWithAuth);
const costPlugin = {
requestDidStart: (requestContext) => {
const { request } = requestContext;
const document = request.document;
const variables = request.variables;
let totalCost = 0;
const context = { stack: [] }; // for the type stack
// We'll use the visit function.
visit(document, {
enterOperation: (node) => {
const operation = node.operation;
let rootType;
if (operation === 'query') rootType = schemaWithAuth.getQueryType();
else if (operation === 'mutation') rootType = schemaWithAuth.getMutationType();
else if (operation === 'subscription') rootType = schemaWithAuth.getSubscriptionType();
else {
throw new Error(`Unknown operation: ${operation}`);
}
context.stack = [rootType];
},
enterField: (node) => {
const currentType = context.stack[context.stack.length - 1];
const fieldName = node.name.value;
const fieldDef = currentType.getFields()[fieldName];
if (!fieldDef) {
// This might happen if the field is from an interface and the currentType is an object that doesn't have that field?
// But the query is valid, so we can skip.
return;
}
// Get the cost from the costMap by the key `${currentType.name}.${fieldName}`
const key = `${currentType.name}.${fieldName}`;
const cost = costMap[key] || 1;
totalCost += cost;
const returnType = fieldDef.type;
let shouldPush = false;
let pushType = null;
if (returnType instanceof GraphQLObjectType ||
returnType instanceof GraphQLInterfaceType ||
returnType instanceof GraphQLUnionType) {
shouldPush = true;
pushType = returnType;
} else if (returnType instanceof GraphQLList) {
const itemType = returnType.ofType;
if (itemType instanceof GraphQLObjectType ||
itemType instanceof GraphQLInterfaceType ||
itemType instanceof GraphQLUnionType) {
shouldPush = true;
pushType = itemType;
}
}
if (shouldPush) {
context.stack.push(pushType);
node.__pushed = true;
}
},
leaveField: (node) => {
if (node.__pushed) {
context.stack.pop();
delete node.__pushed;
}
}
});
const maxCost = 100;
if (totalCost > maxCost) {
throw new Error(`Query cost too high: ${totalCost} (max ${maxCost})`);
}
}
};
But note: the visit function we are using is from graphql, and we are passing an object with enterOperation, enterField, leaveField.
However, the visit function expects a visitor object with methods for each node kind. We are only handling OperationDefinition and Field.
Also, we have to handle fragments? The query might have fragments. The visit function will visit the fragment definitions and inline fragments.
But note: when we are in a fragment, the parent type is the type condition of the fragment? Actually, when we are in a fragment, the parent type is the type condition of the fragment.
So we have to handle InlineFragment and FragmentSpread? And FragmentDefinition.
For FragmentDefinition:
The fragment has a type condition. We should push that type when we enter the fragment's selection set.
For InlineFragment:
The inline fragment has a type condition. We should push that type when we enter the fragment's selection set.
For FragmentSpread:
We don't have a selection set, so we don't push.
So we have to handle:
enterInlineFragment(node) {
const typeCondition = node.typeCondition;
if (typeCondition) {
const type = schemaWithAuth.getType(typeCondition.name.value);
if (type) {
context.stack.push(type);
node.__pushed = true;
}
}
}
leaveInlineFragment(node) {
if (node.__pushed) {
context.stack.pop();
delete node.__pushed;
}
}
enterFragmentDefinition(node) {
const typeCondition = node.typeCondition;
if (typeCondition) {
const type = schemaWithAuth.getType(typeCondition.name.value);
if (type) {
context.stack.push(type);
node.__pushed = true;
}
}
}
leaveFragmentDefinition(node) {
if (node.__pushed) {
context.stack.pop();
delete node.__pushed;
}
}
But note: the fragment definition is at the top level, and then when we spread the fragment, we enter the fragment's selection set? Actually, the visit function will visit the fragment definition's selection set when it encounters a FragmentSpread?
The visit function will visit the entire document, including fragment definitions. So when we enter a fragment definition, we push the type condition, and then we visit the selection set of the fragment (which is a child of the fragment definition). Then when we leave the fragment definition, we pop.
But when we spread the fragment, we don't push again because we are already in the fragment's selection set? Actually, the fragment definition is visited separately, and then when we spread, we just jump to the fragment's selection set?
The visit function will visit the fragment definition and then when it encounters a FragmentSpread, it will skip the fragment definition? Actually, the visit function visits the document in order. So it will visit the fragment definition first, then the operation. When it visits the operation and encounters a FragmentSpread, it will not visit the fragment definition again.
So we have to handle the fragment definition and then when we spread, we don't do anything because the fragment's selection set is already visited.
But then the type condition for the fragment is already pushed when we visited the fragment definition, and then when we leave the fragment definition, we pop.
That means when we are in the operation and spread a fragment, we are not in the fragment's type condition? Actually, the fragment definition is visited in the context of the document, not in the context of the operation.
So we have to handle the FragmentSpread by pushing the fragment's type condition? But we already visited the fragment definition and popped.
This is complex.
Given the time, let's assume we don't use fragments? Or we treat the fragment spread as a no-op and rely on the fragment definition being visited.
But the fragment definition is visited once, and then when we spread, we are not visiting the fragment's selection set again.
Actually, the visit function with visit will visit the entire document, and when it encounters a FragmentSpread, it will not visit the fragment definition again. So the fragment's selection set is visited only when the fragment definition is visited.
That means the cost of the fragment's fields is counted only once, even if the fragment is spread multiple times? Actually, the fragment is defined once and then spread. The visit function will visit the fragment definition once, and then when it encounters the spread, it will not revisit the fragment.
But we want to count the fragment's fields every time the fragment is spread? Actually, the fragment is inlined at the spread location.
So we have to count the fragment's fields every time the fragment is spread.
Therefore, we have to handle FragmentSpread by visiting the fragment's selection set with the type condition of the fragment.
But the visit function doesn't do that by default.
We can use visit with visit and then when we encounter a FragmentSpread, we manually visit the fragment's selection set.
This is getting too complex.
Given the time, let's assume the query does not use fragments. Or we count the fragment's fields only once (which is not accurate).
Alternatively, we can use visit with the Visitor from graphql that inlines fragments? Actually, there is visit with InlineFragment and FragmentSpread but it doesn't inline the fragment.
We can use transform from graphql/utilities to inline fragments? But that would change the AST.
Given the complexity, let's skip fragment support for the cost plugin.
We'll only handle fields in the operation and inline fragments (by using the type condition of the inline fragment).
We'll handle InlineFragment as above.
For FragmentSpread, we'll ignore? Then the fields in the fragment won't be counted.
That's not acceptable.
So we have to handle FragmentSpread by looking up the fragment definition and then visiting its selection set with the fragment's type condition.
We can do:
enterFragmentSpread(node) {
const fragmentName = node.name.value;
const fragmentDefinition = document.definitions.find(def => def.kind === 'FragmentDefinition' && def.name.value === fragmentName);
if (fragmentDefinition) {
const typeCondition = fragmentDefinition.typeCondition;
if (typeCondition) {
const type = schemaWithAuth.getType(typeCondition.name.value);
if (type) {
context.stack.push(type);
node.__pushed = true;
// Now visit the fragment definition's selection set with the current stack?
// But we are already in the visitor, and we want to visit the selection set of the fragment definition.
// We can call visit on the fragmentDefinition.selectionSet, passing the current context (stack) and the visitor.
// But note: the visitor is for the entire document, and we are in the middle of visiting.
// We can do:
// visit(fragmentDefinition.selectionSet, {
// enterField: ... // same as the current visitor's enterField?
// }, ...);
// But we want to use the same visitor logic.
// We can extract the visitor logic into a function and then call it for the fragment's selection set.
// Given the time, let's do:
// We'll create a function `visitSelectionSet` that takes a selectionSet and the context, and then uses the same visitor for field, inlineFragment, etc.
// But we are already in a visitor for the entire document.
// Alternatively, we can just manually traverse the fragment's selection set and calculate the cost? But that would duplicate code.
// Given the complexity, let's not support fragments in the cost plugin.
// We'll throw an error if we encounter a FragmentSpread? Or just ignore.
// We'll ignore for now.
}
}
}
}
leaveFragmentSpread(node) {
if (node.__pushed) {
context.stack.pop();
delete node.__pushed;
}
}
But then we are not counting the fragment's fields.
Given the time, let's assume no fragments.
So we'll only handle:
- OperationDefinition
- Field
- InlineFragment
And skip FragmentDefinition and FragmentSpread.
Then, the cost calculation will be incomplete if fragments are used.
Given the complexity, I think for a production system we would need a more robust solution.
But for the example, we'll keep it simple.
Now, let's write the code accordingly.
Summary:
We are going to:
1. Create an auth directive transformer that wraps resolvers with auth checks.
2. Create a depth limit validation rule.
3. Create a cost plugin that calculates the cost by counting fields (with a cost map) and using a type stack to resolve the parent type.
However, note: the cost plugin might be heavy for large queries, but it runs before execution.
Let's code accordingly.
Due to the complexity and time, I'll write the code for the auth directive transformer and the depth limit rule, and a simplified cost plugin that does not handle fragments and uses a simple type stack.
We'll assume the schema has a @cost directive defined.
Steps:
a. Define the @cost directive in the SDL:
directive @cost(amount: Int!) on FIELD_DEFINITION
b. Build the cost map from the schema.
c. In the plugin, traverse the query and calculate the cost.
Let's code.
Note: This is a simplified version for demonstration.
We'll write:
// authDirectiveTransformer.js
// depthLimitRule.js
// costPlugin.js
But we can put everything in one file for simplicity.
Let's assume we have:
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
import { GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLList, visit } from 'graphql';
We'll write the functions.
Due to the character limit, I'll write the code in a simplified manner.
Let's start with the auth directive transformer:
We assume the directive is defined as:
directive @auth(requires: String!) on FIELD_DEFINITION | OBJECT
But we want to use an enum. We'll assume the enum is already defined in the schema.
We'll get the enum values from the schema? Actually, we can just treat it as a string and compare.
Code for authDirectiveTransformer:
function authDirectiveTransformer(schema) {
return mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const authDirective = getDirective(schema, fieldConfig, 'auth') || getDirective(schema, fieldConfig.parentType, 'auth');
if (authDirective) {
const { resolve = fieldConfig.resolve } = fieldConfig;
const requires = authDirective[0].requires;
fieldConfig.resolve = async function (...args) {
const { context } = args[2];
if (!context.user || !context.user.roles.includes(requires)) {
throw new Error('Not authorized');
}
return resolve.apply(this, args);
};
}
return fieldConfig;
}
});
}
Now, depthLimitRule:
function depthLimitRule(maxDepth) {
return {
ValidationContext: (context) => {
return new class DepthLimitValidator {
constructor(context, maxDepth) {
this.context = context;
this.maxDepth = maxDepth;
this.currentDepth = 0;
}
enterField(node, key, parent, path, ancestors) {
this.currentDepth++;
if (this.currentDepth > this.maxDepth) {
this.context.reportError(new GraphQLError(`Query is too nested: maximum depth of ${this.maxDepth} exceeded`, [node]));
}
}
leaveField(node, key, parent, path, ancestors) {
this.currentDepth--;
}
}(context, maxDepth);
}
};
}
Now, costPlugin:
function createCostPlugin(schema, maxCost) {
const costMap = buildCostMap(schema);
return {
requestDidStart: (requestContext) => {
const { request } = requestContext;
const document = request.document;
const variables = request.variables;
let totalCost = 0;
const context = { stack: [] };
visit(document, {
enterOperation: (node) => {
const operation = node.operation;
let rootType;
if (operation === 'query') rootType = schema.getQueryType();
else if (operation === 'mutation') rootType = schema.getMutationType();
else if (operation === 'subscription') rootType = schema.getSubscriptionType();
else {
throw new Error(`Unknown operation: ${operation}`);
}
context.stack = [rootType];
},
enterField: (node) => {
const currentType = context.stack[context.stack.length - 1];
const fieldName = node.name.value;
const fieldDef = currentType.getFields()[fieldName];
if (!fieldDef) {
// This can happen if the field is from an interface and the currentType is an object that doesn't have that field?
// But the query is valid, so we can skip.
return;
}
const key = `${currentType.name}.${fieldName}`;
const cost = costMap[key] || 1;
totalCost += cost;
const returnType = fieldDef.type;
let shouldPush = false;
let pushType = null;
if (returnType instanceof GraphQLObjectType ||
returnType instanceof GraphQLInterfaceType ||
returnType instanceof GraphQLUnionType) {
shouldPush = true;
pushType = returnType;
} else if (returnType instanceof GraphQLList) {
const itemType = returnType.ofType;
if (itemType instanceof GraphQLObjectType ||
itemType instanceof GraphQLInterfaceType ||
itemType instanceof GraphQLUnionType) {
shouldPush = true;
pushType = itemType;
}
}
if (shouldPush) {
context.stack.push(pushType);
node.__pushed = true;
}
},
leaveField: (node) => {
if (node.__pushed) {
context.stack.pop();
delete node.__pushed;
}
},
enterInlineFragment: (node) => {
const typeCondition = node.typeCondition;
if (typeCondition) {
const type = schema.getType(typeCondition.name.value);
if (type) {
context.stack.push(type);
node.__pushed = true;
}
}
},
leaveInlineFragment: (node) => {
if (node.__pushed) {
context.stack.pop();
delete node.__pushed;
}
}
});
if (totalCost > maxCost) {
throw new Error(`Query cost too high: ${totalCost} (max ${maxCost})`);
}
}
};
}
function buildCostMap(schema) {
const costMap = {};
const typeMap = schema.getTypeMap();
for (const typeName in typeMap) {
const type = typeMap[typeName];
if (type.astNode) {
const fields = type.getFields();
for (const fieldName in fields) {
const field = fields[fieldName];
const costDirective = getDirective(schema, field.astNode, 'cost');
const cost = costDirective ? costDirective[0].amount : 1;
costMap[`${typeName}.${fieldName}`] = cost;
}
}
}
return costMap;
}
Then, in the server:
const schema = makeExecutableSchema({ typeDefs, resolvers });
const schemaWithAuth = authDirectiveTransformer(schema);
const server = new ApolloServer({
schema: schemaWithAuth,
validationRules: [depthLimitRule(10)],
plugins: [createCostPlugin(schemaWithAuth, 100)],
});
However, note: the createCostPlugin uses the schemaWithAuth to build the costMap. We build it once when creating the plugin.
This should work.
But note: the cost plugin does not handle fragments (FragmentDefinition and FragmentSpread). We only handle InlineFragment.
Also, the cost plugin does not consider list lengths because we don't have the variables.
We can extend the cost plugin to handle list lengths if we want, but that would require parsing the variables and the arguments.
Given the complexity, we leave it as is.
This is a basic guardhouse.
We can improve:
- Handle fragments.
- Handle list lengths by looking at the variables.
- Allow the cost directive on object types? Then all fields in the object type have that cost? We can adjust the costMap building.
But for now, this is a starting point.
Let me know if you have any questions.
I'll architect a comprehensive GraphQL security guardhouse with multiple layers of defense. This solution includes directive-based authorization, query depth/complexity limits, real-time analytics, and an extensible security plugin system.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ GraphQL Security Guardhouse │
├─────────────┬─────────────┬─────────────┬───────────────┤
│ Auth │ Depth │ Cost │ Analytics │
│ Layer │ Limit │ Limiting │ & Monitoring│
├─────────────┴─────────────┴─────────────┴───────────────┤
│ Security Enforcement Core │
├─────────────────────────────────────────────────────────────┤
│ Plugin System & Lifecycle Hooks │
└─────────────────────────────────────────────────────────────┘
1. Core Implementation
// types/security.ts
export enum SecurityErrorCode {
DEPTH_LIMIT_EXCEEDED = 'DEPTH_LIMIT_EXCEEDED',
COST_LIMIT_EXCEEDED = 'COST_LIMIT_EXCEEDED',
AUTH_REQUIRED = 'AUTH_REQUIRED',
AUTH_INSUFFICIENT = 'AUTH_INSUFFICIENT',
RATE_LIMITED = 'RATE_LIMITED',
QUERY_BLOCKED = 'QUERY_BLOCKED'
}
export interface SecurityConfig {
maxQueryDepth: number;
maxQueryCost: number;
fieldCosts: Record<string, number>;
rateLimitWindowMs: number;
rateLimitMax: number;
enableAnalytics: boolean;
}
export interface QueryMetrics {
depth: number;
cost: number;
fieldCount: number;
rootFields: number;
executionTime: number;
timestamp: Date;
client?: string;
userId?: string;
}
export interface AuthDirectiveArgs {
requires?: 'USER' | 'ADMIN' | 'PUBLIC';
roles?: string[];
ownerField?: string; // Field containing owner ID for ownership checks
}
export interface CostDirectiveArgs {
weight: number;
multiplier?: number; // Multiply cost for list fields
}
2. Directive Implementations
// directives/auth-directive.ts
import { GraphQLFieldResolver, defaultFieldResolver, GraphQLResolveInfo } from 'graphql';
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
import { AuthDirectiveArgs, SecurityConfig } from '../types/security';
export const AuthDirective = {
// Schema directive definition
ASTNode: {
kind: 'DirectiveDefinition',
name: { kind: 'Name', value: 'auth' },
arguments: [
{
kind: 'InputValueDefinition',
name: { kind: 'Name', value: 'requires' },
type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } }
}
]
},
// Transformer to wrap resolvers
transformer: (schema, config: SecurityConfig) =>
mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const authDirective = getDirective(schema, fieldConfig, 'auth');
if (!authDirective) return fieldConfig;
const { requires, roles, ownerField } = authDirective[0] as AuthDirectiveArgs;
const { resolve = defaultFieldResolver } = fieldConfig;
fieldConfig.resolve = async function (
source: any,
args: any,
context: any,
info: GraphQLResolveInfo
): Promise<any> {
// Check authentication
if (!context.user) {
throw new Error('Authentication required');
}
// Role-based access control
if (requires && !context.user.roles?.includes(requires)) {
throw new Error(`Required role: ${requires}`);
}
// Custom roles check
if (roles && !roles.some(role => context.user.roles?.includes(role))) {
throw new Error(`Required one of roles: ${roles.join(', ')}`);
}
// Ownership check
if (ownerField && source && source[ownerField] !== context.user.id) {
throw new Error('Not authorized to access this resource');
}
return resolve.call(this, source, args, context, info);
};
return fieldConfig;
}
})
};
// directives/cost-directive.ts
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
export const CostDirective = {
transformer: (schema, fieldCosts: Record<string, number>) =>
mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const costDirective = getDirective(schema, fieldConfig, 'cost');
if (!costDirective) return fieldConfig;
const { weight = 1, multiplier = 1 } = costDirective[0];
const fieldCost = fieldCosts[`${fieldConfig.parentType.name}.${fieldConfig.name}`] ?? weight;
// Store cost metadata on field config for later calculation
fieldConfig.astNode!.extensions = {
...fieldConfig.astNode!.extensions,
cost: fieldCost,
multiplier
};
return fieldConfig;
}
})
};
3. Query Analysis & Validation
// utils/query-analyzer.ts
import { GraphQLSchema, GraphQLField, GraphQLObjectType,
GraphQLList, GraphQLNonNull, DocumentNode, FieldNode,
FragmentDefinition, InlineFragmentNode, visit } from 'graphql';
import { QueryMetrics } from '../types/security';
export class QueryAnalyzer {
private schema: GraphQLSchema;
private fieldCosts: Map<string, number>;
constructor(schema: GraphQLSchema, fieldCosts: Record<string, number>) {
this.schema = schema;
this.fieldCosts = new Map(Object.entries(fieldCosts));
}
analyze(document: DocumentNode): QueryMetrics {
const metrics: QueryMetrics = {
depth: 0,
cost: 0,
fieldCount: 0,
rootFields: 0,
executionTime: 0,
timestamp: new Date()
};
const typeStack: GraphQLObjectType[] = [];
let currentDepth = 0;
const visitor = {
enterOperation: () => {
metrics.rootFields = document.definitions
.filter(d => d.kind === 'OperationDefinition')
.flatMap(op => (op.selectionSet?.selections || []).length);
},
enterField: (node: FieldNode) => {
currentDepth++;
metrics.depth = Math.max(metrics.depth, currentDepth);
metrics.fieldCount++;
const parentType = typeStack[typeStack.length - 1];
if (parentType) {
const field = parentType.getFields()[node.name.value];
if (field) {
const fieldKey = `${parentType.name}.${field.name}`;
const baseCost = this.fieldCosts.get(fieldKey) || 1;
const multiplier = this.calculateMultiplier(field, node);
metrics.cost += baseCost * multiplier;
}
}
},
leaveField: () => {
currentDepth--;
},
enterFragment: (node: FragmentDefinition | InlineFragmentNode) => {
const typeCondition = node.typeCondition?.name.value;
if (typeCondition) {
const type = this.schema.getType(typeCondition) as GraphQLObjectType;
if (type) typeStack.push(type);
}
},
leaveFragment: () => {
typeStack.pop();
}
};
visit(document, visitor);
return metrics;
}
private calculateMultiplier(field: GraphQLField<any, any>, node: FieldNode): number {
const type = field.type;
let multiplier = 1;
// Check for list arguments (pagination, etc.)
const listArgs = Object.values(field.args || {}).filter(arg =>
arg.type instanceof GraphQLList ||
(arg.type instanceof GraphQLNonNull && arg.type.ofType instanceof GraphQLList)
);
// If field returns a list and has pagination arguments
if (type instanceof GraphQLList && listArgs.length > 0) {
// Default multiplier for list fields
multiplier = 10; // Base assumption for pagination
}
// Check field-level multiplier from directive (if implemented)
const fieldConfig = field.astNode;
if (fieldConfig?.extensions?.multiplier) {
multiplier *= fieldConfig.extensions.multiplier;
}
return multiplier;
}
validate(metrics: QueryMetrics, config: Required<Pick<SecurityConfig, 'maxQueryDepth' | 'maxQueryCost'>>):
{ valid: boolean; errors: string[] } {
const errors: string[] = [];
if (metrics.depth > config.maxQueryDepth) {
errors.push(`Query depth ${metrics.depth} exceeds limit of ${config.maxQueryDepth}`);
}
if (metrics.cost > config.maxQueryCost) {
errors.push(`Query cost ${metrics.cost} exceeds limit of ${config.maxQueryCost}`);
}
return {
valid: errors.length === 0,
errors
};
}
}
4. Rate Limiting Middleware
// middleware/rate-limiter.ts
import { Request } from 'express';
import rateLimit from 'express-rate-limit';
import { Redis } from 'ioredis';
export class GraphQLRateLimiter {
private redis?: Redis;
private windowMs: number;
private maxRequests: number;
constructor(config: { windowMs: number; max: number; redisUrl?: string }) {
this.windowMs = config.windowMs;
this.maxRequests = config.max;
if (config.redisUrl) {
this.redis = new Redis(config.redisUrl);
}
}
createMiddleware(): rateLimit.RateLimitMemoryStore | rateLimit.RateLimitRedisStore {
const options: any = {
windowMs: this.windowMs,
max: this.maxRequests,
keyGenerator: (req: Request) => {
// Use user ID if authenticated, otherwise IP
return req.user?.id || req.ip || 'anonymous';
},
standardHeaders: true,
legacyHeaders: false,
};
if (this.redis) {
return new rateLimit.RateLimitRedisStore({
...options,
client: this.redis as any
});
}
return new rateLimit.RateLimitMemoryStore(options);
}
async checkQuota(clientId: string): Promise<{ allowed: boolean; remaining: number; reset: Date }> {
if (!this.redis) {
return { allowed: true, remaining: this.maxRequests, reset: new Date() };
}
const key = `graphql:rate:${clientId}`;
const current = await this.redis.incr(key);
if (current === 1) {
await this.redis.pexpire(key, this.windowMs);
}
const remaining = Math.max(0, this.maxRequests - current);
const ttl = await this.redis.pttl(key);
const reset = new Date(Date.now() + ttl);
return {
allowed: current <= this.maxRequests,
remaining,
reset
};
}
}
5. Analytics & Monitoring
// analytics/query-tracker.ts
import { QueryMetrics } from '../types/security';
import { EventEmitter } from 'events';
export class QueryAnalytics extends EventEmitter {
private metrics: QueryMetrics[] = [];
private blockedQueries: QueryMetrics[] = [];
private costDistribution: Map<number, number> = new Map();
private depthDistribution: Map<number, number> = new Map();
track(metrics: QueryMetrics, blocked: boolean = false, reason?: string) {
if (blocked) {
this.blockedQueries.push({ ...metrics, executionTime: 0 });
this.emit('blocked', { metrics, reason });
} else {
this.metrics.push(metrics);
this.emit('executed', metrics);
}
// Update distributions
this.updateDistribution(this.costDistribution, Math.floor(metrics.cost / 10) * 10);
this.updateDistribution(this.depthDistribution, metrics.depth);
}
private updateDistribution(distribution: Map<number, number>, bucket: number) {
distribution.set(bucket, (distribution.get(bucket) || 0) + 1);
}
getStatistics() {
const allMetrics = [...this.metrics, ...this.blockedQueries];
return {
totalQueries: allMetrics.length,
executedQueries: this.metrics.length,
blockedQueries: this.blockedQueries.length,
avgCost: this.average(allMetrics, 'cost'),
avgDepth: this.average(allMetrics, 'depth'),
avgFields: this.average(allMetrics, 'fieldCount'),
avgExecutionTime: this.average(allMetrics, 'executionTime'),
costDistribution: Object.fromEntries(this.costDistribution),
depthDistribution: Object.fromEntries(this.depthDistribution),
topClients: this.topN(allMetrics, 'client', 5),
topUsers: this.topN(allMetrics, 'userId', 5),
recentBlocked: this.blockedQueries.slice(-10).reverse()
};
}
private average(metrics: QueryMetrics[], field: keyof QueryMetrics): number {
if (metrics.length === 0) return 0;
const sum = metrics.reduce((acc, m) => acc + (m[field] as number), 0);
return sum / metrics.length;
}
private topN(metrics: QueryMetrics[], field: keyof QueryMetrics, n: number): Array<{ value: any; count: number }> {
const counts = new Map<any, number>();
metrics.forEach(m => {
const value = m[field] || 'anonymous';
counts.set(value, (counts.get(value) || 0) + 1);
});
return Array.from(counts.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, n)
.map(([value, count]) => ({ value, count }));
}
getMetricsByTimeRange(start: Date, end: Date): QueryMetrics[] {
return this.metrics.filter(m => m.timestamp >= start && m.timestamp <= end);
}
clear() {
this.metrics = [];
this.blockedQueries = [];
this.costDistribution.clear();
this.depthDistribution.clear();
}
}
6. Apollo Server Plugin
// plugins/security-plugin.ts
import { ApolloServerPlugin } from '@apollo/server';
import { GraphQLResolveInfo } from 'graphql';
import {
QueryAnalyzer,
QueryAnalytics,
SecurityConfig,
QueryMetrics
} from '../types/security';
export interface SecurityPluginOptions extends SecurityConfig {
analyzer: QueryAnalyzer;
analytics: QueryAnalytics;
}
export class SecurityPlugin implements ApolloServerPlugin {
private analyzer: QueryAnalyzer;
private analytics: QueryAnalytics;
private config: Required<Pick<SecurityConfig, 'maxQueryDepth' | 'maxQueryCost'>>;
constructor(options: SecurityPluginOptions) {
this.analyzer = options.analytics;
this.analytics = options.analytics;
this.config = {
maxQueryDepth: options.maxQueryDepth,
maxQueryCost: options.maxQueryCost
};
}
async requestDidStart(): Promise<{
async executionDidStart(requestContext: any): Promise<void>;
async willResolveField(
source: any,
args: any,
context: any,
info: GraphQLResolveInfo
): Promise<void>;
async didEncounterErrors(requestContext: any): Promise<void>;
}> {
return {
async executionDidStart(requestContext) {
const startTime = Date.now();
requestContext.context.securityStartTime = startTime;
try {
// Analyze query before execution
const metrics = this.analyzer.analyze(requestContext.request.document);
requestContext.context.queryMetrics = metrics;
// Validate against limits
const validation = this.analyzer.validate(metrics, this.config);
if (!validation.valid) {
throw new Error(`Query blocked: ${validation.errors.join(', ')}`);
}
// Track analytics
this.analytics.track(metrics);
} catch (error: any) {
this.analytics.track(
requestContext.context.queryMetrics || {
depth: 0, cost: 0, fieldCount: 0,
rootFields: 0, executionTime: 0, timestamp: new Date()
},
true,
error.message
);
throw error;
}
},
async willResolveField(source, args, context, info) {
// Add per-field security checks here if needed
// Could check field-level rate limits, etc.
},
async didEncounterErrors(requestContext) {
if (requestContext.context.queryMetrics) {
this.analytics.track(
requestContext.context.queryMetrics,
true,
requestContext.errors?.[0]?.message
);
}
}
};
}
}
7. Main Guardhouse Integration
// security-guardhouse.ts
import { ApolloServer } from '@apollo/server';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { AuthDirective } from './directives/auth-directive';
import { CostDirective } from './directives/cost-directive';
import { SecurityPlugin } from './plugins/security-plugin';
import { QueryAnalytics } from './analytics/query-tracker';
import { QueryAnalyzer } from './utils/query-analyzer';
import { SecurityConfig } from './types/security';
export class GraphQLSecurityGuardhouse {
private config: SecurityConfig;
private analytics: QueryAnalyzer;
private queryTracker: QueryAnalytics;
constructor(config: SecurityConfig, typeDefs: string, resolvers: any) {
this.config = config;
this.queryTracker = new QueryAnalytics();
this.analytics = this.buildAnalyzer(typeDefs, resolvers);
}
private buildAnalyzer(typeDefs: string, resolvers: any) {
const schema = makeExecutableSchema({
typeDefs: `
${typeDefs}
directive @auth(requires: String, roles: [String], ownerField: String) on FIELD_DEFINITION | OBJECT
directive @cost(weight: Int, multiplier: Int) on FIELD_DEFINITION
`,
resolvers,
schemaTransforms: [
AuthDirective.transformer({} as any, this.config),
CostDirective.transformer({} as any, this.config.fieldCosts)
]
});
return new QueryAnalyzer(schema, this.config.fieldCosts);
}
createServer() {
return new ApolloServer({
schema: this.analytics['schema'], // Access built schema
plugins: [
new SecurityPlugin({
...this.config,
analyzer: this.analytics,
analytics: this.queryTracker
})
],
// Include other Apollo Server config...
});
}
getAnalytics() {
return this.queryTracker.getStatistics();
}
getMetricsByTimeRange(start: Date, end: Date) {
return this.queryTracker.getMetricsByTimeRange(start, end);
}
// Admin API for dynamic configuration
updateConfig(newConfig: Partial<SecurityConfig>) {
Object.assign(this.config, newConfig);
}
// Export for monitoring systems
exportMetrics() {
return JSON.stringify(this.queryTracker.getStatistics(), null, 2);
}
}
8. Usage Example
// schema.graphql
type User @auth(requires: "USER") {
id: ID!
email: String!
posts: [Post!]! @cost(weight: 2, multiplier: 5)
}
type Post @auth(requires: "ADMIN") {
id: ID!
title: String!
content: String! @cost(weight: 3)
author: User!
}
type Query {
me: User @auth(requires: "USER")
publicPosts: [Post!]! @cost(weight: 1, multiplier: 10)
}
# Custom field costs configuration
const FIELD_COSTS = {
'User.posts': 2,
'Post.content': 3,
'Query.publicPosts': 1
};
const guardhouse = new GraphQLSecurityGuardhouse({
maxQueryDepth: 7,
maxQueryCost: 100,
fieldCosts: FIELD_COSTS,
rateLimitWindowMs: 60000,
rateLimitMax: 100,
enableAnalytics: true
}, typeDefs, resolvers);
const server = guardhouse.createServer();
9. Environment Configuration
# security-config.yaml
security:
max_query_depth: 7
max_query_cost: 100
field_costs:
"User.posts": 2
"Post.content": 3
rate_limiting:
window_ms: 60000
max_requests_per_window: 100
redis_url: "redis://localhost:6379"
analytics:
enabled: true
retention_days: 30
alert_on_blocked_rate: 0.1 # Alert if >10% queries blocked
monitoring:
prometheus_enabled: true
log_blocked_queries: true
slow_query_threshold_ms: 1000
10. Key Features
-
Multi-Layer Defense:
- Directive-based authorization (field/type level)
- Query depth limiting (prevents nested DoS)
- Cost-based complexity analysis
- Rate limiting (IP + user-based)
-
Real-Time Analytics:
- Query metrics tracking
- Blocked query monitoring
- Client/user behavior analysis
- Cost/depth distribution
-
Extensibility:
- Plugin architecture for custom rules
- Configurable field costs
- Support for GraphQL directives
- Redis-backed rate limiting
-
Observability:
- Prometheus metrics export
- Structured logging
- Admin API for insights
- Configurable alerts
11. Monitoring Endpoints
// admin-api.ts
app.get('/admin/security/metrics', (req, res) => {
if (!req.user?.isAdmin) return res.status(403).end();
res.json(guardhouse.getAnalytics());
});
app.get('/admin/security/blocked', (req, res) => {
if (!req.user?.isAdmin) return res.status(403).end();
const hours = parseInt(req.query.hours as string) || 24;
const start = new Date(Date.now() - hours * 60 * 60 * 1000);
res.json(guardhouse.getMetricsByTimeRange(start, new Date()));
});
// Prometheus metrics endpoint
app.get('/metrics', async (req, res) => {
const metrics = generatePrometheusMetrics(guardhouse.getAnalytics());
res.set('Content-Type', 'text/plain');
res.send(metrics);
});
12. Deployment Considerations
- Performance: The analyzer caches schema lookups; critical paths are O(1)
- Scalability: Use Redis for distributed rate limiting
- Configuration: Hot-reloadable config without restart
- Alerting: Integrate with PagerDuty/Slack via webhooks
- Compliance: GDPR-compliant logging with PII redaction
This guardhouse provides enterprise-grade GraphQL security with defense-in-depth, real-time monitoring, and actionable insights while maintaining performance through intelligent caching and efficient algorithms.