feat: Refactor rides app with unique constraints, mixins, and enhanced documentation

- Added migration to convert unique_together constraints to UniqueConstraint for RideModel.
- Introduced RideFormMixin for handling entity suggestions in ride forms.
- Created comprehensive code standards documentation outlining formatting, docstring requirements, complexity guidelines, and testing requirements.
- Established error handling guidelines with a structured exception hierarchy and best practices for API and view error handling.
- Documented view pattern guidelines, emphasizing the use of CBVs, FBVs, and ViewSets with examples.
- Implemented a benchmarking script for query performance analysis and optimization.
- Developed security documentation detailing measures, configurations, and a security checklist.
- Compiled a database optimization guide covering indexing strategies, query optimization patterns, and computed fields.
This commit is contained in:
pacnpal
2025-12-22 11:17:31 -05:00
parent 45d97b6e68
commit 2e35f8c5d9
71 changed files with 8036 additions and 1462 deletions

193
docs/SECURITY.md Normal file
View File

@@ -0,0 +1,193 @@
# ThrillWiki Security Documentation
This document describes the security measures implemented in ThrillWiki and provides guidelines for maintaining security.
## Security Architecture Overview
ThrillWiki implements defense-in-depth security with multiple layers of protection:
1. **Network Layer**: HTTPS, HSTS, security headers
2. **Application Layer**: Input validation, output encoding, CSRF protection
3. **Authentication Layer**: JWT tokens, rate limiting, session management
4. **Data Layer**: SQL injection prevention, data sanitization
## Security Features
### HTTP Security Headers
The following security headers are configured:
| Header | Value | Purpose |
|--------|-------|---------|
| X-Frame-Options | DENY | Prevents clickjacking attacks |
| X-Content-Type-Options | nosniff | Prevents MIME sniffing |
| Referrer-Policy | strict-origin-when-cross-origin | Controls referrer information |
| Content-Security-Policy | Configured | Controls resource loading |
| Permissions-Policy | Configured | Restricts browser features |
### XSS Prevention
- All user input is escaped by Django's template engine by default
- Custom `|sanitize` filter for user-generated HTML content
- SVG sanitization for icon rendering
- JavaScript data is serialized using Django's `json_script` tag
### CSRF Protection
- Django's CSRF middleware is enabled
- CSRF tokens required for all state-changing requests
- HTMX requests automatically include CSRF tokens via `htmx:configRequest` event
- SameSite cookie attribute set to prevent CSRF attacks
### SQL Injection Prevention
- All database queries use Django ORM
- No raw SQL with user input
- `.extra()` calls replaced with Django ORM functions
- Management commands use parameterized queries
### File Upload Security
- File type validation (extension, MIME type, magic number)
- File size limits (10MB max)
- Image integrity validation using PIL
- Rate limiting (10 uploads per minute)
- Secure filename generation
### Authentication & Authorization
- JWT-based authentication with short-lived access tokens (15 minutes)
- Refresh token rotation with blacklisting
- Rate limiting on authentication endpoints:
- Login: 5 per minute, 30 per hour
- Signup: 3 per minute, 10 per hour
- Password reset: 2 per minute, 5 per hour
- Permission-based access control
### Session Security
- Redis-backed session storage
- 1-hour session timeout with sliding expiry
- HTTPOnly cookies prevent JavaScript access
- Secure cookies in production (HTTPS only)
- SameSite attribute set to prevent CSRF
### Sensitive Data Protection
- Passwords hashed with Django's PBKDF2
- Sensitive fields masked in logs
- Email addresses partially masked in logs
- Error messages don't expose internal details in production
- DEBUG mode disabled in production
## Security Configuration
### Environment Variables
The following environment variables should be set for production:
```bash
DEBUG=False
SECRET_KEY=<strong-random-key>
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
CSRF_TRUSTED_ORIGINS=https://yourdomain.com
DATABASE_URL=<secure-database-url>
```
### Production Checklist
Before deploying to production:
- [ ] DEBUG is False
- [ ] SECRET_KEY is a strong, random value
- [ ] ALLOWED_HOSTS is configured
- [ ] HTTPS is enabled (SECURE_SSL_REDIRECT=True)
- [ ] HSTS is enabled (SECURE_HSTS_SECONDS >= 31536000)
- [ ] Secure cookies enabled (SESSION_COOKIE_SECURE=True)
- [ ] Database uses SSL connection
- [ ] Error emails configured (ADMINS setting)
## Security Audit
Run the security audit command:
```bash
python manage.py security_audit --verbose
```
This checks:
- Django security settings
- Configuration analysis
- Middleware configuration
## Vulnerability Reporting
To report a security vulnerability:
1. **Do not** open a public issue
2. Email security concerns to: [security contact]
3. Include:
- Description of the vulnerability
- Steps to reproduce
- Potential impact
- Any suggested fixes
## Security Updates
- Keep Django and dependencies updated
- Monitor security advisories
- Review OWASP Top 10 periodically
- Run security scans (OWASP ZAP, etc.)
## Code Security Guidelines
### Input Validation
```python
# Always validate user input
from apps.core.utils.html_sanitizer import sanitize_html
user_input = request.data.get('content')
safe_content = sanitize_html(user_input)
```
### Template Security
```html
<!-- Use sanitize filter for user content -->
{% load safe_html %}
{{ user_content|sanitize }}
<!-- Use json_script for JavaScript data -->
{{ data|json_script:"data-id" }}
```
### File Uploads
```python
from apps.core.utils.file_scanner import validate_image_upload
try:
validate_image_upload(uploaded_file)
except FileValidationError as e:
return error_response(str(e))
```
### Logging
```python
# Don't log sensitive data
logger.info(f"User {user.id} logged in") # OK
logger.info(f"Password: {password}") # BAD
```
## Dependencies
Security-relevant dependencies:
- `bleach`: HTML sanitization
- `Pillow`: Image validation
- `djangorestframework-simplejwt`: JWT authentication
- `django-cors-headers`: CORS configuration
Keep these updated to patch security vulnerabilities.