streamflow/docs/INPUT_VALIDATION_SECURITY.md

319 lines
10 KiB
Markdown
Raw Permalink Normal View History

# Input Validation & Security Implementation
## Overview
This document outlines the comprehensive input validation and security measures implemented across the StreamFlow application.
## Security Principles
### 1. **Defense in Depth**
- Multiple layers of security validation
- Client-side validation for UX
- Server-side validation as the ultimate security barrier
- Database-level constraints
### 2. **Whitelist Validation**
- Accept only explicitly allowed input patterns
- Reject everything else by default
- More secure than blacklist approaches
### 3. **Input Sanitization**
- All user input is sanitized before processing
- HTML tags and script content removed
- Special characters escaped
- URL validation prevents XSS attacks
## Backend Implementation
### Validation Utilities
#### `/backend/utils/inputValidator.js`
Comprehensive validation functions for all input types:
- **validateUsername()**: 3-50 alphanumeric characters, hyphens, underscores
- **validateEmail()**: Valid email format, max 255 characters
- **validateUrl()**: Validates URLs with allowed protocols (http, https, rtmp, rtsp, udp, rtp)
- **validatePlaylistName()**: 1-200 characters, safe characters only
- **validateChannelName()**: 1-200 characters, sanitized
- **validateDescription()**: Max 1000 characters, HTML stripped
- **validateFilename()**: Safe filenames, prevents path traversal
- **validateSettingKey()**: Alphanumeric with dots, dashes, underscores
- **validateInteger()**: Range validation for numbers
- **validateBoolean()**: Type coercion and validation
- **validateJSON()**: JSON parsing with size limits
- **sanitizeString()**: XSS prevention through HTML/script removal
### Validation Middleware
#### `/backend/middleware/inputValidation.js`
Reusable middleware for route validation:
- **createValidationMiddleware()**: Factory for custom validators
- **validatePlaylist**: Playlist creation/update validation
- **validateChannelUpdate**: Channel modification validation
- **validateSettings**: Settings key/value validation
- **validateIdParam**: Numeric ID parameter validation
- **validatePagination**: Limit/offset parameter validation
- **validateSearch**: Search query sanitization
- **validateUserCreation**: User registration validation
- **validateUserUpdate**: User profile update validation
- **validateEPGSource**: EPG source URL validation
- **validateFileOperation**: Filename validation for file ops
- **validateBulkDelete**: Array of IDs validation (max 1000)
### Protected Routes
All routes now include:
- **Rate limiting**: Prevents brute force attacks
- **Input validation**: Whitelist-based validation
- **Authentication checks**: JWT token validation
- **Authorization**: Role-based access control
- **Audit logging**: Security event logging
#### Updated Routes:
- `/api/playlists/*` - Full validation on create, update, delete
- `/api/settings/*` - Key/value validation, type checking
- `/api/channels/*` - ID and filter validation
- `/api/favorites/*` - Channel ID validation
- `/api/epg/*` - URL and ID validation
- `/api/users/*` - Comprehensive user data validation
- `/api/auth/*` - Already had validation via express-validator
## Frontend Implementation
### Validation Utilities
#### `/frontend/src/utils/inputValidator.js`
Client-side validation for improved UX:
- **sanitizeString()**: XSS prevention
- **validateUsername()**: Username format validation
- **validateEmail()**: Email format validation
- **validateUrl()**: URL format and protocol validation
- **validateTextField()**: Generic text field validation
- **validateInteger()**: Number validation with min/max
- **validateFile()**: File upload validation (type, size)
- **validatePassword()**: Password strength calculation
- **sanitizeFormData()**: Recursive object sanitization
- **escapeHtml()**: HTML entity encoding
**Note**: Client-side validation is for UX only. Server-side validation is the real security layer.
### React Components
#### SecurityNotificationProvider
Context-based notification system for security events:
- Account lockout notifications
- Password expiry warnings
- Invalid input alerts
- Security success messages
- Configurable duration and persistence
#### ValidatedTextField
Enhanced TextField with built-in validation:
- Real-time validation feedback
- Visual indicators (checkmarks/errors)
- Automatic sanitization
- Support for username, email, URL, integer, text types
- Configurable min/max length/value
#### SecuritySettingsPanel
Comprehensive security dashboard for users:
- Security status overview
- 2FA status display
- Active session management
- Session termination controls
- Input validation info display
## Security Features
### Input Validation
- ✅ Whitelist-based validation
- ✅ Type checking and coercion
- ✅ Length and range limits
- ✅ Pattern matching (regex)
- ✅ Special character filtering
- ✅ HTML/Script tag removal
- ✅ URL protocol validation
- ✅ Path traversal prevention
- ✅ SQL injection prevention
- ✅ XSS attack prevention
### Rate Limiting
Already implemented via `rateLimiter.js`:
- Authentication endpoints: 5 requests/15min
- Modification endpoints: 20 requests/15min
- Read endpoints: 100 requests/15min
- Heavy operations: 5 requests/hour
### Session Security
- JWT tokens with 7-day expiration
- Secure token storage
- Session invalidation support
- Multi-device session tracking
- Session termination controls
### Password Security
Already implemented:
- bcrypt hashing (10 rounds)
- Minimum 12 characters
- Complexity requirements (uppercase, lowercase, numbers, symbols)
- Password history (no reuse of last 5)
- Password expiry (90 days)
- Account lockout after failed attempts
### Audit Logging
Already implemented via `securityAudit.js`:
- Login attempts (success/failure)
- Password changes
- Account lockouts
- 2FA events
- Session creation
- Administrative actions
## Translation Support
Full i18n support added for:
- Input validation error messages (EN, RO)
- Security notifications (EN, RO)
- Security settings UI (EN, RO)
- All error and success messages (EN, RO)
Languages supported:
- English (`/frontend/src/locales/en.json`)
- Romanian (`/frontend/src/locales/ro.json`)
Translation keys added:
- `security.inputValidation`
- `security.invalidInput`
- `security.validationFailed`
- `security.invalidUsername`
- `security.invalidEmail`
- `security.invalidUrl`
- `security.fieldRequired`
- `security.fieldTooShort`
- `security.fieldTooLong`
- `security.invalidCharacters`
- `security.invalidFileType`
- `security.fileTooLarge`
- `security.securityAlert`
- `security.inputSanitized`
- `security.xssAttemptBlocked`
- `security.sqlInjectionBlocked`
- And many more...
## Docker Integration
All security features are included in the Docker build:
- Validation utilities automatically bundled
- Middleware included in backend
- Frontend components compiled into build
- No additional configuration needed
The Docker container includes:
- All backend validation middleware
- All frontend validation utilities
- Security notification system
- Validated components
- Translation files
## Testing & Verification
### Backend Testing
```bash
# Test input validation
curl -X POST http://localhost:12345/api/playlists/url \
-H "Authorization: Bearer TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"<script>alert(1)</script>","url":"javascript:alert(1)"}'
# Should return 400 with validation errors
```
### Frontend Testing
- Open browser console
- Check for XSS attempts in form fields
- Verify sanitization warnings appear
- Test invalid input formats
- Confirm real-time validation feedback
### Security Checklist
- ✅ SQL injection prevented (parameterized queries)
- ✅ XSS attacks blocked (input sanitization)
- ✅ CSRF protection (token-based API)
- ✅ Rate limiting active
- ✅ Authentication enforced
- ✅ Authorization checked (role-based)
- ✅ Input validation (whitelist)
- ✅ Output encoding (HTML escape)
- ✅ File upload restrictions
- ✅ Password security (hashing, policy)
- ✅ Session management (JWT)
- ✅ Audit logging enabled
- ✅ Error messages sanitized
- ✅ HTTPS recommended
- ✅ Security headers (helmet.js)
## Best Practices
### For Developers
1. **Always validate on server-side**: Client-side is for UX only
2. **Use whitelist validation**: Define what's allowed, not what's forbidden
3. **Sanitize all input**: Even if validated, sanitize before use
4. **Log security events**: Track suspicious activity
5. **Test with malicious input**: Use tools like OWASP ZAP
6. **Keep dependencies updated**: Run `npm audit` regularly
7. **Review audit logs**: Check for patterns of attacks
8. **Use validation middleware**: Don't repeat validation logic
9. **Document security decisions**: Explain why certain validations exist
10. **Follow principle of least privilege**: Grant minimal necessary permissions
### For Administrators
1. **Enable 2FA**: Enforce for admin accounts
2. **Review security dashboard**: Check for locked accounts, failed attempts
3. **Monitor audit logs**: Export and analyze regularly
4. **Update regularly**: Keep application and dependencies current
5. **Use strong JWT_SECRET**: Change default in production
6. **Enable HTTPS**: Use reverse proxy (nginx, caddy)
7. **Backup regularly**: Use built-in backup feature
8. **Limit admin accounts**: Create managed users when possible
9. **Review active sessions**: Terminate suspicious sessions
10. **Test security**: Run security scan scripts
## Maintenance
### Regular Tasks
- Review `logs/security-audit.log` weekly
- Check for outdated dependencies: `npm audit`
- Monitor failed login attempts
- Review and unlock legitimate locked accounts
- Update security documentation
- Test validation rules with new attack patterns
### Update Procedures
When updating validation rules:
1. Update backend validator in `/backend/utils/inputValidator.js`
2. Update middleware if needed in `/backend/middleware/inputValidation.js`
3. Update frontend validator in `/frontend/src/utils/inputValidator.js`
4. Update translations in `/frontend/src/locales/*.json`
5. Test thoroughly with valid and invalid inputs
6. Update this documentation
7. Commit with clear security-related message
## References
- OWASP Top 10: https://owasp.org/www-project-top-ten/
- Input Validation Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
- XSS Prevention: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
- SQL Injection Prevention: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
---
**Last Updated**: December 13, 2025
**Version**: 1.0.0
**Status**: ✅ Production Ready