2.6 KiB
2.6 KiB
CSRF Protection in AnonChat
Overview
Cross-Site Request Forgery (CSRF) protection has been implemented in the AnonChat application to prevent attackers from tricking users into submitting requests they did not intend to make. This document outlines how CSRF protection is implemented and maintained.
Implementation
The application uses Flask-WTF's CSRFProtect extension to provide CSRF protection. This works by:
- Including a unique token in each form (csrf_token)
- Validating this token on form submissions
- Rejecting requests that don't include a valid token
Key Components
CSRFProtect
initialization in__init__.py
csrf_token
hidden field in all HTML forms- Custom error handler for CSRF errors (HTTP 400)
Testing
CSRF protection can be tested using the test cases in tests/test_csrf.py
. This includes:
- Testing forms with valid CSRF tokens
- Testing forms without CSRF tokens (should be rejected)
- Testing admin forms with valid CSRF tokens
- Testing admin forms without CSRF tokens (should be rejected)
To run the tests:
# Run the CSRF protection tests
python -m unittest tests/test_csrf.py
# Run all tests
python -m unittest discover tests
The tests ensure that CSRF protection is working correctly by:
- Verifying that forms with valid CSRF tokens are processed successfully
- Confirming that forms without CSRF tokens are rejected
- Testing admin-specific CSRF protection behavior
Maintenance Guidelines
When adding new forms or routes to the application:
-
For all HTML forms that use POST:
- Include the CSRF token:
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
- Include the CSRF token:
-
For API endpoints that need to be exempt from CSRF:
- Use the
@csrf.exempt
decorator on the route - Document the exemption and provide a security justification
- Consider alternative security measures (API keys, JWT tokens)
- Use the
-
For file uploads or forms with large data:
- CSRF protection still applies
- No special handling is needed for these cases
Security Recommendations
- Keep your application's
SECRET_KEY
secure and unique - Regularly rotate the
SECRET_KEY
in production environments - Always use HTTPS in production to prevent token leakage
- Set appropriate cookie security flags (
secure
,httpOnly
,SameSite
)
Troubleshooting
Common CSRF issues:
- Form submissions being rejected: Check that the csrf_token is correctly included in the form
- AJAX requests failing: Include the csrf_token in AJAX requests or exempt specific API endpoints
- Tests failing unexpectedly: Ensure test client is configured to handle CSRF correctly