Query Cost Analytics: Analyzing query complexity to prevent resource exhaustion and provide metrics.
Target Audience/Context: Likely a backend developer or architect looking for a structured implementation, probably in a popular language like Node.js (Apollo Server) or Python (Ariadne/Strawberry), but Node.js with Apollo is the industry standard for this kind of middleware setup.
Architectural Components:
The Schema & Directives (The Gatekeeper's Rules):
Need a custom directive @auth (or similar).
This directive needs to check roles (e.g., ADMIN, USER) or specific permissions.
Implementation involves Schema Transformer (Apollo) or directive resolvers.
The Validation Layer (The Walls):
Depth Limiting: Need a plugin or middleware to check the AST depth before execution.
Cost Analysis: Need a library to calculate "cost" based on pagination fields or custom weights.
The Analytics Layer (The Logbook):
Need to record query complexity, depth, user ID, and latency.
This shouldn't block the request but should happen asynchronously or in an extension.
Tech Stack Selection:
Language: TypeScript (better for architecture demonstrations due to interfaces/types).
Framework: Apollo Server (v4 is current, but v3 is also common; I'll aim for modern Apollo Server concepts).
Libraries:
graphql-depth-limit (or custom logic).
graphql-cost-analysis (or similar).
Step-by-Step Implementation Plan:
Project Setup: Folder structure, dependencies.
Auth Directive:
Define the directive in SDL (Schema Definition Language).
Create the logic class (e.g., AuthDirective).
Apply it to the schema.
Security Middleware (Depth & Cost):
Depth limit plugin.
Cost analysis plugin (this is tricky because often involves looking ahead).
The "Guardhouse" Class: A wrapper that ties everything together.
Analytics/Metrics: How to expose or log this data.
Refining the "Auth Directive" part:
In modern Apollo Server (v4), ApolloServerPluginLandingPageDisabled isn't relevant, but schema transformation is. Actually, the standard way now is often using libraries like graphql-shield or custom directives via mapSchema. I will implement a classic SchemaDirectiveVisitor style approach (or its modern equivalent) because it demonstrates the architecture best, even if some specific libraries have shifted. Actually, @auth is often best done at the resolver level context, but the user specifically asked for directives. So I must implement a custom directive transformer.
Refining the "Depth Limit" part:
Parsing the GraphQL AST (Abstract Syntax Tree).
import { depthLimit } from 'graphql-depth-limit'; -> easy enough to hook into validationRules.
Refining the "Query Cost" part:
This usually requires defining "cost" on types/fields (e.g., a list connection costs more).
I will use a library approach simulation or a custom validation rule to show how the calculation works introspectively.
Structuring the Response:
I will present this as a "Project Blueprint".
Concept: The Guardhouse.
File Structure.
Core Logic (Code):
AuthDirective.ts: The enforcer.
SecurityPlugin.ts: The walls (Depth/Cost).
AnalyticsService.ts: The logbook.
Server.ts: Putting it together.
Explanation of mechanics.
Self-Correction during drafting:
Initial thought: Use graphql-shield.
Correction: No, the prompt specifically asks for "auth directives", which implies schema definition @auth(role: ADMIN), not just middleware permission mapping.
Initial thought: Build a complex cost calculator from scratch.
Correction: Too much boilerplate code. Better to show how to hook a library like graphql-cost-analysis into the validation rules.
Drafting the Code (Mental or Scratchpad):
Auth Directive:
Needs to wrap the field resolver. Check context.user. Throw error if missing/mismatched.
Depth Limit:
Add to validationRules in Apollo Server config.
Cost Analysis:
Also a validation rule. It needs to introspect the schema to find cost directives or arguments.
The "Guardhouse" Metaphor:
The Desk Sergeant (Context): Authenticates the user (JWT validation).
The Rulebook (Schema Directives): Defines who sees what.
The Fence (Depth/Cost Limits): Brute force protection.
The Security Camera (Analytics): Monitoring usage patterns.
Final Polish:
Make sure to emphasize Typescript for type safety. Ensure the code is modular. I will create a cohesive system, not just disparate snippets.
Let's write the actual implementation details.
Auth Directive: uses mapSchema and getDirective (Apollo utils).
Depth/Cost: uses validationRules.
Analytics: uses a custom plugin requestDidStart.
Okay, ready to generate.
This architectural blueprint defines a GraphQL Security Guardhouse: a structured middleware layer designed to sit between your network interface and your resolvers. It enforces security policies before expensive database operations begin.
We will use a TypeScript-based Apollo Server implementation, as it provides the most robust plugin and directive architecture for this task.
The Architecture
The Guardhouse consists of three primary stations:
The Gate (Schema Directives):@auth and @role directives that act as declarative gatekeepers on specific fields.
The Barrier (Validation Rules): Static analysis of the incoming query AST to enforce Depth Limits.
The Meter (Plugin Analytics): A calculator that estimates "Query Cost" based on pagination arguments (first, last, limit) to prevent resource exhaustion.
1. The Blueprint (Dependencies)
typescript
// npm install apollo-server graphql graphql-type-json reflect-metadata
// We assume a standard Apollo Server 4 setup
import { ApolloServer, Plugin } from '@apollo/server';
import { GraphQLSchema, separateOperations } from 'graphql';
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
import { defaultFieldResolver } from 'graphql';
2. Station 1: The Auth Gate (Directives)
We use Schema Directives to transform the schema at startup. This "guards" fields by wrapping them in authentication logic.
The Logic:
@auth(requires: ROLE): Checks if context.user exists and has the correct role.
typescript
// AuthDirective.ts
export function authDirectiveTransformer(schema: GraphQLSchema, directiveName: string) {
return mapSchema(schema, {
// Runs when we find a field with the @auth directive
[MapperKind.OBJECT_FIELD]: (fieldConfig, fieldName) => {
const authDirective = getDirective(schema, fieldConfig, directiveName)?.[0];
if (authDirective) {
const { requires } = authDirective;
const originalResolver = fieldConfig.resolve || defaultFieldResolver;
// Wrap the resolver
fieldConfig.resolve = async (source, args, context, info) => {
// 1. Check if user is logged in
if (!context.user) {
throw new Error('Unauthorized: You must be logged in.');
}
// 2. Check specific roles if required
if (requires && context.user.role !== requires) {
throw new Error(`Forbidden: Requires role '${requires}'.`);
}
// 3. Proceed to resolver
return originalResolver(source, args, context, info);
};
}
return fieldConfig;
},
});
}
3. Station 2: The Depth Barrier (Validation)
Complexity attacks often involve deeply nested queries (e.g., User -> Friends -> User -> Friends...). We use a standard validation rule to stop this at the parse phase.
typescript
// DepthLimit.ts
import { GraphQLError, ValidationContext, ASTNode } from 'graphql';
export function createDepthLimit(maxDepth: number) {
return (context: ValidationContext) => ({
Document: {
leave(node: ASTNode) {
// Helper to calculate depth recursively
const getDepth = (n: any, currentDepth: number): number => {
if (currentDepth > maxDepth) return currentDepth; // Early exit
let maxChildDepth = currentDepth;
// Look for selection sets (the fields requested)
if (n.selectionSet) {
for (const child of n.selectionSet.selections) {
// 'FragmentSpreads' need special handling, simplified here
if (child.kind === 'Field') {
const childDepth = getDepth(child, currentDepth + 1);
maxChildDepth = Math.max(maxChildDepth, childDepth);
}
}
}
return maxChildDepth;
};
// Check every operation in the document
for (const definition of (node as any).definitions) {
if (definition.kind === 'OperationDefinition') {
const depth = getDepth(definition, 0);
if (depth > maxDepth) {
context.reportError(
new GraphQLError(`Query depth limit exceeded. Max: ${maxDepth}, Found: ${depth}`)
);
}
}
}
},
},
});
}
4. Station 3: The Cost Meter (Plugin)
Depth isn't enough; a query can be shallow but request 1,000 items per page. We need a Plugin that inspects arguments (first, limit) and assigns a "Cost Score".
The Strategy:
Intercept the request.
Parse the query arguments.
Sum up the cost.
If Cost > Threshold, Reject.
If Accepted, log the cost for internal Analytics (Rate Limiting).
typescript
// CostAnalysisPlugin.ts
import { GraphQLRequestListener } from '@apollo/server';
import { separateOperations } from 'graphql';
export interface CostEstimate {
score: number;
operationName: string;
}
export class CostAnalysisPlugin implements Plugin {
private readonly maxCost: number;
constructor(maxCost: number) {
this.maxCost = maxCost;
}
async requestDidStart(): Promise<GraphQLRequestListener<any>> {
return {
// DidResolveOperation runs after parsing but before execution
didResolveOperation({ request, document }) {
// 1. Simple Cost Heuristic:
// Base Cost = 1
// Every field adds 1
// Arguments named 'first', 'last', 'limit' multiply the cost.
let totalCost = 0;
const operation = separateOperations(document)[request.operationName || ''];
if (!operation) return;
// Recursive walker (simplified for brevity)
const calculateCost = (node: any, multiplier: number = 1) => {
if (!node.selectionSet) return 1;
let cost = 1;
let localMultiplier = 1;
// Check for pagination arguments
if(node.arguments) {
for(const arg of node.arguments) {
if (['first', 'last', 'limit'].includes(arg.name.value)) {
localMultiplier = parseInt(arg.value.value, 10) || 10;
}
}
}
for (const selection of node.selectionSet.selections) {
if (selection.kind === 'Field') {
cost += calculateCost(selection, multiplier * localMultiplier);
}
}
return cost * multiplier;
};
totalCost = calculateCost(operation);
// 2. Enforcement
if (totalCost > this.maxCost) {
throw new Error(`Query is too expensive. Cost: ${totalCost}, Limit: ${this.maxCost}`);
}
// 3. Analytics Hook (Logging to console for demo)
console.log(`[Analytics] Op: ${request.operationName} | Cost: ${totalCost}`);
},
};
}
}
5. The Guardhouse Assembly
Now we wire everything together in the server initialization.
typescript
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { authDirectiveTransformer } from './AuthDirective';
import { createDepthLimit } from './DepthLimit';
import { CostAnalysisPlugin } from './CostAnalysisPlugin';
// 1. Define Schema with Directives
const typeDefs = `#graphql
directive @auth(requires: String) on FIELD_DEFINITION
type User {
id: ID
name: String
secrets: String @auth(requires: "ADMIN")
friends(first: Int): [User]
}
type Query {
me: User
allUsers(first: Int): [User] @auth(requires: "ADMIN")
}
`;
// 2. Resolvers
const resolvers = {
Query: {
me: () => ({ id: 1, name: "Alice", secrets: "The cake is a lie" }),
allUsers: (_, { first }) => Array(first || 5).fill({ id: 2, name: "Bob" })
}
};
// 3. Build Schema and Apply Directive Transformer
let schema = makeExecutableSchema({ typeDefs, resolvers });
schema = authDirectiveTransformer(schema, 'auth');
// 4. Initialize Server with The Guardhouse
const server = new ApolloServer({
schema,
// Barrier: Reject queries deeper than 7 levels
validationRules: [createDepthLimit(7)],
// Meter: Reject queries costing more than 1000 units
plugins: [new CostAnalysisPlugin(1000)],
});
// 5. Context Setup (Mock Auth)
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => {
// In real life, decode JWT here
const user = req.headers.authorization
? { role: 'USER', id: 1 }
: null;
return { user };
},
listen: { port: 4000 },
});
console.log(`🛡️ Guardhouse ready at ${url}`);
How to Test the Guardhouse
Test Auth Directive:
Query me { secrets } without a token -> 401 Unauthorized.
Query with token (role: USER) -> 403 Forbidden (requires ADMIN).