apollo-graphql-v3-enable-csrf-prevention
Automatically enable CSRF prevention in Apollo GraphQL Server v3 configurations to prevent Cross-Site Request Forgery attacks.
Security Issue
Apollo GraphQL Server v3 has CSRF prevention disabled by default (csrfPrevention: false), which can expose GraphQL endpoints to Cross-Site Request Forgery (CSRF) attacks. This codemod automatically enables CSRF prevention by setting csrfPrevention: true in all Apollo Server configurations.
Security References
- CWE-352: Cross-Site Request Forgery (CSRF) - https://cwe.mitre.org/data/definitions/352.html
- OWASP: Cross-Site Request Forgery Prevention - https://owasp.org/www-community/attacks/csrf
- Apollo Docs: CSRF Prevention - https://www.apollographql.com/docs/apollo-server/security/cors/#csrf-prevention
Installation
bash
What it does
This codemod identifies Apollo Server v3 configurations and automatically enables CSRF prevention by:
- Adding missing csrfPrevention: true to ApolloServer constructor configurations
- Changing csrfPrevention: false to csrfPrevention: true when explicitly disabled
- Handling configuration objects passed as variables by wrapping them with spread syntax
- Supporting all Apollo Server variants (apollo-server, apollo-server-express, apollo-server-fastify, etc.)
Transformations
Basic Object Configuration
Before:
javascript
After:
javascript
Changing false to true
Before:
javascript
After:
javascript
Configuration Variable
Before:
javascript
After:
javascript
Empty Configuration
Before:
javascript
After:
javascript
Supported Apollo Server Packages
- apollo-server
- apollo-server-express
- apollo-server-fastify
- apollo-server-koa
- apollo-server-lambda
- apollo-server-azure-functions
- apollo-server-cloud-functions
File Coverage
The codemod processes:
- JavaScript files: .js
- TypeScript files: .ts
- JSX files: .jsx
- TSX files: .tsx
Excludes:
- node_modules directories
- Test files (*.test.*, *.spec.*, /test/, /tests/, /__tests__/)
- Build output directories (/dist/, /build/)
Edge Cases Handled
- ✅ Configurations with existing csrfPrevention: true (unchanged)
- ✅ Complex configurations with plugins, context, and other options
- ✅ Multiple ApolloServer instances in the same file
- ✅ Files without Apollo Server imports (skipped)
- ✅ Different import styles (named, default, destructured)
Limitations
- The codemod cannot distinguish between Apollo Server versions from imports alone
- Assumes all apollo-server imports are v3 (appropriate for security-focused transformation)
- Does not modify configurations in external config files imported dynamically
Development
bash
Contributing
When adding test cases:
- Create a new directory in tests/ with descriptive name
- Add input.js and expected.js files
- Run tests to verify transformation
- Update documentation if needed
License
MIT