|
| 1 | +# Security Guidelines and Best Practices |
| 2 | + |
| 3 | +## 🔐 Critical Security Requirements |
| 4 | + |
| 5 | +### JWT Token Security |
| 6 | +- **Key Length**: JWT secret key MUST be at least 32 characters long |
| 7 | +- **Key Strength**: Avoid default, fallback, or sample keys in production |
| 8 | +- **Key Management**: Store JWT keys in secure environment variables only |
| 9 | +- **Token Validation**: All JWT validation failures are logged for security monitoring |
| 10 | +- **Token Headers**: Multiple headers supported (Authorization, X-Forwarded-Authorization, etc.) |
| 11 | + |
| 12 | +```bash |
| 13 | +# Example: Generate secure JWT key |
| 14 | +JWT_SECRET_KEY=$(openssl rand -base64 32) |
| 15 | +``` |
| 16 | + |
| 17 | +### Database Security |
| 18 | +- **Connection Resilience**: Enhanced retry policies with exponential backoff |
| 19 | +- **Connection Timeout**: 120-second timeout for database operations |
| 20 | +- **Retry Logic**: 5 attempts with up to 30-second delays |
| 21 | +- **Error Handling**: Specific SQL error codes handled for Azure SQL and on-premises |
| 22 | +- **Connection Pooling**: EF Core manages connection pooling automatically |
| 23 | + |
| 24 | +### Authentication Flow Security |
| 25 | +- **OAuth2 PKCE**: Proof Key for Code Exchange mandatory for OAuth2 flows |
| 26 | +- **Session Management**: Redis-based session storage with TTL expiration |
| 27 | +- **Token Lifecycle**: Short-lived access tokens (15min) + long-lived refresh tokens (30 days) |
| 28 | +- **Session Validation**: Real-time session validation for critical operations |
| 29 | +- **Logout Security**: Proper token revocation and cleanup |
| 30 | + |
| 31 | +### Input Validation Security |
| 32 | +- **Data Annotations**: Comprehensive validation rules on all DTOs |
| 33 | +- **Business Logic Validation**: Domain-specific validation in Application layer |
| 34 | +- **SQL Injection Prevention**: Entity Framework parameterized queries |
| 35 | +- **XSS Protection**: JSON serialization prevents script injection |
| 36 | +- **CSRF Protection**: OAuth2 state parameter validation |
| 37 | + |
| 38 | +## 🛡️ Production Security Checklist |
| 39 | + |
| 40 | +### Environment Configuration |
| 41 | +- [ ] JWT_SECRET_KEY is at least 32 characters and cryptographically random |
| 42 | +- [ ] Database connection strings use secure authentication |
| 43 | +- [ ] Redis connection secured with authentication if applicable |
| 44 | +- [ ] TLS/HTTPS enforced for all external communications |
| 45 | +- [ ] OAuth2 client secrets stored securely |
| 46 | +- [ ] API keys for external services (TTS, LLM, Memory) secured |
| 47 | + |
| 48 | +### Runtime Security Monitoring |
| 49 | +- [ ] JWT validation failures monitored and alerted |
| 50 | +- [ ] Database connection failures logged and monitored |
| 51 | +- [ ] WebSocket connection anomalies tracked |
| 52 | +- [ ] Failed authentication attempts rate-limited |
| 53 | +- [ ] Session hijacking patterns detected |
| 54 | + |
| 55 | +### Code Security Standards |
| 56 | +- [ ] ConfigureAwait(false) used in all async service methods |
| 57 | +- [ ] Exception handling prevents information leakage |
| 58 | +- [ ] Logging excludes sensitive information (tokens, passwords, keys) |
| 59 | +- [ ] User input sanitized before database operations |
| 60 | +- [ ] File uploads (if any) validated for type and size |
| 61 | + |
| 62 | +## 🚨 Security Incident Response |
| 63 | + |
| 64 | +### JWT Compromise Response |
| 65 | +1. **Immediate**: Rotate JWT secret key |
| 66 | +2. **Revoke**: All existing refresh tokens in Redis |
| 67 | +3. **Audit**: Review authentication logs for suspicious activity |
| 68 | +4. **Monitor**: Enhanced logging for unusual patterns |
| 69 | + |
| 70 | +### Database Security Incident |
| 71 | +1. **Isolate**: Database connections if breach suspected |
| 72 | +2. **Audit**: Query logs for unauthorized access patterns |
| 73 | +3. **Verify**: Data integrity and unauthorized modifications |
| 74 | +4. **Recovery**: Implement additional connection restrictions |
| 75 | + |
| 76 | +### Session Security Incident |
| 77 | +1. **Clear**: All Redis sessions for affected users |
| 78 | +2. **Force**: Re-authentication for all users |
| 79 | +3. **Monitor**: Session creation patterns |
| 80 | +4. **Update**: Session validation logic if needed |
| 81 | + |
| 82 | +## 📊 Security Monitoring and Logging |
| 83 | + |
| 84 | +### Critical Security Events to Monitor |
| 85 | +- JWT token validation failures |
| 86 | +- Database connection retries and failures |
| 87 | +- WebSocket connection anomalies |
| 88 | +- OAuth2 authentication failures |
| 89 | +- Session validation failures |
| 90 | +- Credit balance tampering attempts |
| 91 | + |
| 92 | +### Log Levels for Security Events |
| 93 | +```csharp |
| 94 | +// Security violations - ERROR level |
| 95 | +_logger.LogError("Security violation detected: {Details}", details); |
| 96 | + |
| 97 | +// Authentication failures - WARNING level |
| 98 | +_logger.LogWarning("Authentication failed: {Reason}", reason); |
| 99 | + |
| 100 | +// Security success events - INFORMATION level |
| 101 | +_logger.LogInformation("Secure operation completed: {Operation}", operation); |
| 102 | + |
| 103 | +// Security debugging - DEBUG level (development only) |
| 104 | +_logger.LogDebug("Security check passed: {Check}", check); |
| 105 | +``` |
| 106 | + |
| 107 | +## 🔧 Development Security Guidelines |
| 108 | + |
| 109 | +### Secure Coding Practices |
| 110 | +1. **Never hardcode secrets** in source code |
| 111 | +2. **Validate all inputs** at API and business logic layers |
| 112 | +3. **Use parameterized queries** exclusively (EF Core handles this) |
| 113 | +4. **Handle exceptions securely** without exposing system details |
| 114 | +5. **Log security events** appropriately for monitoring |
| 115 | + |
| 116 | +### Testing Security Features |
| 117 | +1. **Authentication Testing**: Valid/invalid tokens, expired tokens, malformed tokens |
| 118 | +2. **Authorization Testing**: Role-based access, resource ownership |
| 119 | +3. **Input Validation Testing**: Boundary conditions, malformed data |
| 120 | +4. **Session Testing**: Session hijacking prevention, timeout handling |
| 121 | +5. **Error Handling Testing**: Information leakage prevention |
| 122 | + |
| 123 | +## 🎯 Recent Security Improvements |
| 124 | + |
| 125 | +### JWT Security Enhancements |
| 126 | +- Added JWT key length validation (minimum 32 characters) |
| 127 | +- Implemented fallback key detection and prevention |
| 128 | +- Enhanced JWT validation exception handling and logging |
| 129 | +- Added structured logging for security event tracking |
| 130 | + |
| 131 | +### Database Connection Security |
| 132 | +- Increased retry attempts from 3 to 5 |
| 133 | +- Extended maximum retry delay from 10 to 30 seconds |
| 134 | +- Added 10 specific SQL error codes for better failure handling |
| 135 | +- Set 120-second command timeout for long operations |
| 136 | + |
| 137 | +### WebSocket Security Improvements |
| 138 | +- Enhanced connection lifecycle management |
| 139 | +- Added proper resource cleanup on disconnection |
| 140 | +- Implemented heartbeat mechanism for connection health |
| 141 | +- Added connection timeout handling (30 minutes) |
| 142 | + |
| 143 | +### Session Management Security |
| 144 | +- Implemented real-time session validation |
| 145 | +- Added session activity tracking |
| 146 | +- Graceful handling of session storage failures |
| 147 | +- Enhanced session-based authentication for critical operations |
0 commit comments