itcloud/SECURITY_FIXES_TODO.md

132 lines
5.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Security Fixes TODO
Статус исправлений критических уязвимостей из аудита безопасности.
---
## 🔴 КРИТИЧЕСКИЕ (В РАБОТЕ)
### Безопасность API
- [ ] **Rate Limiting** - защита от brute force атак
- [ ] Установить slowapi
- [ ] Добавить rate limiting на login (5/минуту)
- [ ] Добавить rate limiting на register (3/час)
- [ ] Добавить rate limiting на uploads (100/час)
### Аутентификация
- [ ] **Token Revocation** - logout должен удалять токен
- [ ] Создать Redis client для blacklist
- [ ] Добавить проверку blacklist в get_current_user
- [ ] Реализовать endpoint /auth/logout
- [ ] **Refresh Token Rotation** - обновление токенов
- [ ] Endpoint /auth/refresh
- [ ] Отзыв старого refresh token при rotation
- [ ] Frontend interceptor для автообновления
- [ ] **Account Lockout** - блокировка после 3 попыток на сутки
- [ ] LoginAttemptTracker с Redis
- [ ] Проверка блокировки перед login
- [ ] Запись неудачных попыток
### Storage Management
- [ ] **Storage Quota** - 3GB по пользователю
- [ ] Миграция: добавить storage_quota_bytes и storage_used_bytes в User
- [ ] Проверка квоты при create_upload
- [ ] Увеличение used_bytes при finalize_upload
- [ ] Уменьшение used_bytes при delete (S3 trash)
- [ ] Endpoint GET /users/me/storage для статистики
### Валидация файлов
- [ ] **Content-Type Whitelist** - только разрешенные типы
- [ ] ALLOWED_IMAGE_TYPES whitelist
- [ ] ALLOWED_VIDEO_TYPES whitelist
- [ ] Обновить validator в schemas.py
- [ ] **Magic Bytes Verification** - проверка реального типа файла
- [ ] Установить python-magic
- [ ] Проверка при finalize_upload
- [ ] Удаление файла из S3 при несовпадении
### File Upload Security
- [ ] **Streaming Chunks** - предотвратить OOM
- [ ] Метод upload_fileobj_streaming в S3Client
- [ ] Обновить upload_file_to_s3 для стриминга
- [ ] Проверка размера ПЕРЕД чтением (макс 3GB)
### ZIP Download
- [ ] **ZIP Streaming** - не держать весь архив в памяти
- [ ] Создание ZIP в temp файле
- [ ] FileResponse вместо возврата bytes
- [ ] BackgroundTask для удаления temp файла
### Configuration
- [ ] **Trash Bucket Config** - убрать hardcode
- [ ] Добавить TRASH_BUCKET в config.py
- [ ] Использовать из конфига в S3Client
### HTTP Security
- [ ] **Security Headers** - защита от XSS, clickjacking
- [ ] SecurityHeadersMiddleware
- [ ] X-Frame-Options, X-Content-Type-Options
- [ ] CSP, HSTS, Referrer-Policy
### Architecture
- [ ] **FolderService Refactoring** - разделить обязанности
- [ ] Убрать прямую работу с AssetRepository
- [ ] Создать FolderManagementService для оркестрации
- [ ] Использовать AssetService methods
### Search
- [ ] **Asset Search** - поиск по имени файла
- [ ] Метод search_assets в AssetRepository
- [ ] Endpoint GET /assets/search
- [ ] Поддержка ILIKE для поиска
---
## 🟡 TODO (ОТЛОЖЕНО НА ПОТОМ)
- [ ] JWT Secret Validation - проверка слабого секрета в продакшене
- [ ] S3 Encryption at Rest - ServerSideEncryption='AES256'
- [ ] Share Token Uniqueness Check - collision detection
- [ ] CSRF Protection - fastapi-csrf-protect
- [ ] Strong Password Validation - complexity requirements
- [ ] Database Indexes - composite indexes для производительности
- [ ] Foreign Keys - relationships в models
- [ ] Password Reset Flow - forgot/reset endpoints + email
- [ ] EXIF Metadata Extraction - captured_at, dimensions
- [ ] Database Backups - автоматизация бэкапов
- [ ] Comprehensive Testing - 70%+ coverage
- [ ] Monitoring & Logging - structured logging, metrics
- [ ] CI/CD Pipeline - GitHub Actions
---
## 📊 Progress
**Выполнено:** 14/14 критических задач ✅✅✅
**Статус:** 🎉 ВСЕ ЗАДАЧИ ЗАВЕРШЕНЫ!
### ✅ Завершено:
1. ✅ slowapi добавлен в pyproject.toml
2. ✅ Config обновлен (trash_bucket, max 3GB, default quota)
3. ✅ Redis client создан (TokenBlacklist, LoginAttemptTracker)
4. ✅ main.py: Rate limiting, Security Headers, CORS restrictive
5. ✅ User model: storage_quota_bytes, storage_used_bytes
6. ✅ Миграция 002: add_storage_quota создана
7. ✅ schemas.py: Content-Type whitelist, 3GB max, RefreshTokenRequest, StorageStatsResponse
8. ✅ dependencies.py: blacklist check в get_current_user
9. ✅ auth.py: rate limiting на endpoints, logout, refresh, account lockout, storage stats
10. ✅ S3Client: streaming upload (upload_fileobj_streaming), trash_bucket from config
11. ✅ asset_service: storage quota check, streaming (upload_fileobj_streaming), magic bytes verification, storage_used_bytes updates
12. ✅ batch_operations: ZIP streaming (temp file + FileResponse + BackgroundTasks cleanup), storage_used_bytes updates
13. ✅ FolderService: refactored (removed asset modification, only read-only validation queries)
14. ✅ AssetRepository + AssetService + API: search_assets method (ILIKE), GET /api/v1/assets/search endpoint
---
**Дата начала:** 2026-01-05
**Последнее обновление:** 2026-01-05
**Финальный статус:** 🎉 14/14 COMPLETED