CSRF Protection Implementation
This document describes the Cross-Site Request Forgery (CSRF) protection implementation for the ERP-Unlocked web application.
Overview
Section titled “Overview”Following the security recommendations from GitHub Issue #161, we have implemented CSRF protection for admin API routes since Astro v5’s built-in CSRF protection does not apply to API routes.
Implementation Details
Section titled “Implementation Details”1. CSRF Validation Utility (apps/webapp/src/utils/csrf.ts)
Section titled “1. CSRF Validation Utility (apps/webapp/src/utils/csrf.ts)”The core CSRF protection is implemented in the csrf.ts utility which provides:
- Origin Header Validation: Ensures requests come from expected origins
- Referer Header Fallback: Falls back to referer validation if origin is missing
- Custom Header Requirement: Requires
X-Requested-With: XMLHttpRequestheader for admin endpoints - Extensible Configuration: Allows custom validation options per endpoint
2. BaseAPIHandler Integration
Section titled “2. BaseAPIHandler Integration”The BaseAPIHandler class has been enhanced with CSRF protection:
protected async requireAdmin(locals: any, request?: Request, csrfOptions?: CSRFValidationOptions)This method now automatically:
- Validates CSRF protection for admin endpoints
- Checks admin role authorization
- Logs security events for monitoring
3. Client-Side Implementation
Section titled “3. Client-Side Implementation”Frontend requests to admin endpoints must include the required header:
fetch('/api/admin/unblock-ip', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', // Required for CSRF protection }, body: JSON.stringify({ ip }),});Protection Mechanisms
Section titled “Protection Mechanisms”Origin Validation
Section titled “Origin Validation”- Validates
Originheader matches expected domain - Falls back to
Refererheader ifOriginis missing - Supports additional allowed origins via configuration
Custom Header Requirement
Section titled “Custom Header Requirement”- Requires
X-Requested-With: XMLHttpRequestheader - Prevents simple form-based CSRF attacks
- Can be disabled via configuration if needed
Method-Based Protection
Section titled “Method-Based Protection”- Only validates state-changing HTTP methods (POST, PUT, DELETE, PATCH)
- GET requests bypass CSRF checks (considered safe)
Configuration Options
Section titled “Configuration Options”interface CSRFValidationOptions { adminOnly?: boolean; // Require stricter checks for admin endpoints allowedOrigins?: string[]; // Additional allowed origins requireCustomHeader?: boolean; // Require X-Requested-With header}Usage Examples
Section titled “Usage Examples”Basic Admin Endpoint Protection
Section titled “Basic Admin Endpoint Protection”export const POST: APIRoute = async ({ request, locals }) => { const handler = new MyAdminHandler(); return handler.handleRequest(async () => { // This automatically includes CSRF protection await this.requireAdmin(locals, request);
// Your admin logic here });};Custom CSRF Configuration
Section titled “Custom CSRF Configuration”await this.requireAdmin(locals, request, { allowedOrigins: ['https://trusted-domain.com'], requireCustomHeader: false,});Security Benefits
Section titled “Security Benefits”- Prevents CSRF Attacks: Blocks malicious sites from triggering admin actions
- Origin Validation: Ensures requests come from legitimate sources
- Custom Header Protection: Prevents simple form-based attacks
- Comprehensive Logging: All validation attempts are logged for monitoring
- Configurable: Can be adjusted per endpoint as needed
Monitoring and Logging
Section titled “Monitoring and Logging”All CSRF validation events are logged with:
- Request details (method, origin, referer)
- Validation results (success/failure)
- Error details for failed validations
- Request correlation IDs for debugging
Future Enhancements
Section titled “Future Enhancements”The implementation is designed to be extensible and includes:
- Token-based CSRF protection utilities (for future use)
- Configurable validation options
- Support for additional security headers
Testing
Section titled “Testing”To test CSRF protection:
- Valid Request: Include
X-Requested-With: XMLHttpRequestheader - Invalid Origin: Try request from different origin (should fail)
- Missing Header: Omit custom header (should fail for admin endpoints)
- Invalid Method: Only POST/PUT/DELETE/PATCH are validated
Related Files
Section titled “Related Files”apps/webapp/src/utils/csrf.ts- Core CSRF validation logicapps/webapp/src/lib/api/base-handler.ts- API handler integrationapps/webapp/src/pages/admin/rate-limiting.astro- Example client implementationapps/webapp/src/pages/api/admin/unblock-ip.ts- Example protected endpoint