Overview
Thegraphql middleware provides GraphQL query validation and security features including depth limiting, complexity analysis, introspection control, and field blocking.
Use it when you need:
- Query depth and complexity validation
- Introspection query control
- Field-level access control
- Operation allowlisting
- Protection against malicious queries
Installation
Quick Start
Configuration
Options
| Option | Type | Default | Description |
|---|---|---|---|
MaxDepth | int | 10 | Maximum query depth allowed |
MaxComplexity | int | 100 | Maximum query complexity allowed |
DisableIntrospection | bool | false | Disable introspection queries |
AllowedOperations | []string | nil | Whitelist of allowed operation names |
BlockedFields | []string | nil | List of fields to block |
ErrorHandler | func(*mizu.Ctx, error) error | nil | Custom error handler |
Examples
Basic Setup
Custom Depth and Complexity Limits
Production Configuration
Disable Introspection
Block Sensitive Fields
Allowlist Operations
Custom Error Handler
API Reference
Functions
Error Types
Technical Details
Query Validation Process
The middleware validates GraphQL queries through the following process:- Request Filtering: Only processes POST requests with
application/jsoncontent type - Query Parsing: Parses the request body into a
Querystructure containing:query: The GraphQL query stringoperationName: Named operation identifiervariables: Query variables map
- Validation Chain: Applies validations in order:
- Introspection check (if enabled)
- Operation allowlist check (if configured)
- Depth calculation and validation
- Complexity calculation and validation
- Blocked fields check (if configured)
- Body Restoration: Restores the request body for downstream handlers
Depth Calculation
Query depth is calculated by counting the maximum nesting level of braces{}:
- Tracks current depth using a counter
- Increments on
{, decrements on} - Records the maximum depth reached
Complexity Calculation
Query complexity is estimated using:- Count of field selections with braces:
\w+\s*(?:\([^)]*\))?\s*{ - Plus total count of opening braces
{
Introspection Detection
Introspection queries are detected using regex pattern matching for:__schema- Schema introspection__type- Type introspection
Implementation Notes
- The middleware preserves the request body after validation for downstream handlers
- Non-POST requests and non-JSON requests bypass validation
- Failed JSON parsing allows the request to pass through (handled by GraphQL server)
- Default limits provide reasonable protection for most applications
Best Practices
- Disable introspection in production
- Set appropriate depth limits based on your schema
- Use complexity limits to prevent resource exhaustion
- Block sensitive fields at the middleware level
- Implement custom error handlers for better user experience
- Combine with rate limiting for additional protection
Testing
Test Coverage
| Test Case | Description | Expected Behavior |
|---|---|---|
TestNew | Default middleware creation | Accepts valid queries with default limits |
TestWithOptions_MaxDepth | Query depth validation | Rejects queries exceeding max depth (4 > 2) |
TestWithOptions_MaxComplexity | Query complexity validation | Rejects queries exceeding max complexity |
TestWithOptions_DisableIntrospection | Introspection blocking | Blocks __schema and __type queries |
TestWithOptions_BlockedFields | Field blocking | Rejects queries containing blocked fields (password, secret) |
TestSkipNonPOST | GET request handling | Allows non-POST requests to pass through |
TestMaxDepth | MaxDepth helper function | Accepts queries within depth limit (2 β€ 3) |
TestMaxComplexity | MaxComplexity helper function | Accepts queries within complexity limit |
TestNoIntrospection | NoIntrospection helper | Blocks __type introspection queries |
TestProduction | Production configuration | Applies production settings (depth:10, complexity:100, no introspection) |
TestBlockFields | BlockFields helper | Blocks specified mutation fields (deleteMutation, adminAccess) |
TestCustomErrorHandler | Custom error handling | Uses custom error handler with HTTP 403 status |
Security Considerations
Query Depth Attacks
Deep nested queries can cause exponential computation:MaxDepth based on your schemaβs maximum legitimate nesting.
Query Complexity Attacks
Complex queries can exhaust server resources:MaxComplexity to limit total query cost.
Introspection Leaks
Introspection exposes your entire schema structure:NoIntrospection() or Production().
Sensitive Field Access
Prevent access to sensitive fields:BlockFields() to prevent access to sensitive data.