anonsubmit/docs/csrf-protection.md
2025-04-02 06:46:59 +02:00

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:

  1. Including a unique token in each form (csrf_token)
  2. Validating this token on form submissions
  3. 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:

  1. Verifying that forms with valid CSRF tokens are processed successfully
  2. Confirming that forms without CSRF tokens are rejected
  3. Testing admin-specific CSRF protection behavior

Maintenance Guidelines

When adding new forms or routes to the application:

  1. For all HTML forms that use POST:

    • Include the CSRF token: <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
  2. 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)
  3. For file uploads or forms with large data:

    • CSRF protection still applies
    • No special handling is needed for these cases

Security Recommendations

  1. Keep your application's SECRET_KEY secure and unique
  2. Regularly rotate the SECRET_KEY in production environments
  3. Always use HTTPS in production to prevent token leakage
  4. 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