407 lines
12 KiB
Markdown
407 lines
12 KiB
Markdown
# Security Checklist
|
|
|
|
## Frontend Security (✅ Implemented)
|
|
|
|
### Authentication & Authorization
|
|
- ✅ **Protected Routes**: All admin routes require authentication
|
|
- ✅ **Role-Based Access**: Checks for ADMIN role before granting access
|
|
- ✅ **Cookie Support**: `withCredentials: true` for httpOnly cookies
|
|
- ✅ **Token Refresh**: Automatic token refresh on 401 errors
|
|
- ✅ **Centralized Logout**: Calls backend to clear cookies
|
|
- ✅ **Secure Redirects**: Prevents redirect loops on login page
|
|
- ✅ **localStorage Fallback**: Works with backends without cookie support
|
|
|
|
### API Security
|
|
- ✅ **Separate API Instances**: Public vs authenticated endpoints
|
|
- ✅ **Bearer Token**: Proper Authorization header format
|
|
- ✅ **Error Handling**: Consistent error responses with user feedback
|
|
- ✅ **Request Retry**: Automatic retry after token refresh
|
|
- ✅ **CORS Credentials**: Enabled for cross-origin cookie sharing
|
|
|
|
### Code Security
|
|
- ✅ **TypeScript**: Type safety throughout the application
|
|
- ✅ **Input Validation**: Form validation on login
|
|
- ✅ **Error Messages**: Generic error messages (no sensitive info leak)
|
|
- ✅ **No Hardcoded Secrets**: Uses environment variables
|
|
|
|
## Backend Security (⚠️ Must Implement)
|
|
|
|
### Critical Requirements
|
|
|
|
#### 1. httpOnly Cookies (Recommended)
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
res.cookie('access_token', token, {
|
|
httpOnly: true, // ✅ Prevents XSS attacks
|
|
secure: true, // ✅ HTTPS only (production)
|
|
sameSite: 'strict', // ✅ CSRF protection
|
|
maxAge: 900000, // ✅ 15 minutes
|
|
path: '/'
|
|
})
|
|
```
|
|
|
|
**Why httpOnly?**
|
|
- Prevents JavaScript access to tokens
|
|
- Protects against XSS (Cross-Site Scripting) attacks
|
|
- Industry standard for authentication
|
|
|
|
#### 2. Token Management
|
|
- ⚠️ **Short-lived Access Tokens**: 15 minutes max
|
|
- ⚠️ **Long-lived Refresh Tokens**: 7 days max
|
|
- ⚠️ **Token Rotation**: Generate new refresh token on each refresh
|
|
- ⚠️ **Token Revocation**: Invalidate tokens on logout
|
|
- ⚠️ **Token Blacklist**: Store revoked tokens (Redis recommended)
|
|
|
|
#### 3. Password Security
|
|
- ⚠️ **Hashing**: Use bcrypt/argon2 (NOT MD5/SHA1)
|
|
- ⚠️ **Salt**: Unique salt per password
|
|
- ⚠️ **Cost Factor**: bcrypt rounds >= 12
|
|
- ⚠️ **Password Policy**: Min 8 chars, complexity requirements
|
|
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
const bcrypt = require('bcrypt')
|
|
const saltRounds = 12
|
|
const hashedPassword = await bcrypt.hash(password, saltRounds)
|
|
```
|
|
|
|
#### 4. Rate Limiting
|
|
- ⚠️ **Login Endpoint**: 5 attempts per 15 minutes per IP
|
|
- ⚠️ **API Endpoints**: 100 requests per minute per user
|
|
- ⚠️ **Account Lockout**: Lock after 5 failed login attempts
|
|
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
const rateLimit = require('express-rate-limit')
|
|
|
|
const loginLimiter = rateLimit({
|
|
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
max: 5, // 5 requests per window
|
|
message: 'Too many login attempts, please try again later'
|
|
})
|
|
|
|
app.post('/auth/login', loginLimiter, loginHandler)
|
|
```
|
|
|
|
#### 5. CORS Configuration
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
app.use(cors({
|
|
origin: process.env.FRONTEND_URL, // Specific origin, not '*'
|
|
credentials: true, // Allow cookies
|
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
|
|
allowedHeaders: ['Content-Type', 'Authorization']
|
|
}))
|
|
```
|
|
|
|
#### 6. Input Validation
|
|
- ⚠️ **Sanitize Inputs**: Prevent SQL injection, XSS
|
|
- ⚠️ **Validate Email**: Proper email format
|
|
- ⚠️ **Validate Types**: Check data types
|
|
- ⚠️ **Limit Payload Size**: Prevent DoS attacks
|
|
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
const { body, validationResult } = require('express-validator')
|
|
|
|
app.post('/auth/login', [
|
|
body('email').isEmail().normalizeEmail(),
|
|
body('password').isLength({ min: 8 })
|
|
], (req, res) => {
|
|
const errors = validationResult(req)
|
|
if (!errors.isEmpty()) {
|
|
return res.status(400).json({ errors: errors.array() })
|
|
}
|
|
// Process login
|
|
})
|
|
```
|
|
|
|
#### 7. SQL Injection Prevention
|
|
- ⚠️ **Parameterized Queries**: Use prepared statements
|
|
- ⚠️ **ORM**: Use Prisma, TypeORM, Sequelize
|
|
- ⚠️ **Never**: Concatenate user input into SQL
|
|
|
|
```javascript
|
|
// ❌ VULNERABLE
|
|
const query = `SELECT * FROM users WHERE email = '${email}'`
|
|
|
|
// ✅ SAFE
|
|
const query = 'SELECT * FROM users WHERE email = ?'
|
|
db.query(query, [email])
|
|
```
|
|
|
|
#### 8. XSS Prevention
|
|
- ⚠️ **Escape Output**: Sanitize data before rendering
|
|
- ⚠️ **Content Security Policy**: Set CSP headers
|
|
- ⚠️ **httpOnly Cookies**: Prevent JavaScript access to tokens
|
|
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
const helmet = require('helmet')
|
|
app.use(helmet.contentSecurityPolicy({
|
|
directives: {
|
|
defaultSrc: ["'self'"],
|
|
scriptSrc: ["'self'"],
|
|
styleSrc: ["'self'", "'unsafe-inline'"],
|
|
imgSrc: ["'self'", "data:", "https:"],
|
|
}
|
|
}))
|
|
```
|
|
|
|
#### 9. HTTPS/TLS
|
|
- ⚠️ **Production**: HTTPS only (no HTTP)
|
|
- ⚠️ **TLS 1.2+**: Disable older versions
|
|
- ⚠️ **HSTS Header**: Force HTTPS
|
|
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
app.use(helmet.hsts({
|
|
maxAge: 31536000, // 1 year
|
|
includeSubDomains: true,
|
|
preload: true
|
|
}))
|
|
```
|
|
|
|
#### 10. Security Headers
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
const helmet = require('helmet')
|
|
app.use(helmet()) // Sets multiple security headers
|
|
|
|
// Or manually:
|
|
app.use((req, res, next) => {
|
|
res.setHeader('X-Content-Type-Options', 'nosniff')
|
|
res.setHeader('X-Frame-Options', 'DENY')
|
|
res.setHeader('X-XSS-Protection', '1; mode=block')
|
|
res.setHeader('Strict-Transport-Security', 'max-age=31536000')
|
|
next()
|
|
})
|
|
```
|
|
|
|
#### 11. Audit Logging
|
|
- ⚠️ **Log All Admin Actions**: Who, what, when, where
|
|
- ⚠️ **Log Failed Logins**: Track suspicious activity
|
|
- ⚠️ **Log Sensitive Operations**: User deletion, role changes
|
|
- ⚠️ **Secure Logs**: Store in separate database/service
|
|
|
|
```javascript
|
|
// ⚠️ BACKEND MUST IMPLEMENT
|
|
const auditLog = async (userId, action, resource, details) => {
|
|
await db.auditLogs.create({
|
|
userId,
|
|
action,
|
|
resource,
|
|
details,
|
|
ipAddress: req.ip,
|
|
userAgent: req.headers['user-agent'],
|
|
timestamp: new Date()
|
|
})
|
|
}
|
|
```
|
|
|
|
#### 12. Database Security
|
|
- ⚠️ **Least Privilege**: Database user with minimal permissions
|
|
- ⚠️ **Encrypted Connections**: Use SSL/TLS for database
|
|
- ⚠️ **Backup Encryption**: Encrypt database backups
|
|
- ⚠️ **Sensitive Data**: Encrypt PII at rest
|
|
|
|
#### 13. Environment Variables
|
|
- ⚠️ **Never Commit**: .env files in .gitignore
|
|
- ⚠️ **Secrets Management**: Use vault (AWS Secrets Manager, etc.)
|
|
- ⚠️ **Rotate Secrets**: Regular rotation of API keys, tokens
|
|
|
|
```bash
|
|
# ⚠️ BACKEND MUST CONFIGURE
|
|
JWT_SECRET=<strong-random-secret-256-bits>
|
|
JWT_REFRESH_SECRET=<different-strong-secret>
|
|
DATABASE_URL=<encrypted-connection-string>
|
|
FRONTEND_URL=https://admin.yourdomain.com
|
|
NODE_ENV=production
|
|
```
|
|
|
|
#### 14. Session Management
|
|
- ⚠️ **Session Timeout**: Auto-logout after inactivity
|
|
- ⚠️ **Concurrent Sessions**: Limit or track multiple sessions
|
|
- ⚠️ **Session Invalidation**: Clear on logout, password change
|
|
|
|
## Additional Security Measures
|
|
|
|
### Frontend (Optional Improvements)
|
|
|
|
#### 1. Content Security Policy (CSP)
|
|
```html
|
|
<!-- Add to index.html -->
|
|
<meta http-equiv="Content-Security-Policy"
|
|
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
|
|
```
|
|
|
|
#### 2. Subresource Integrity (SRI)
|
|
```html
|
|
<!-- For CDN resources -->
|
|
<script src="https://cdn.example.com/lib.js"
|
|
integrity="sha384-..."
|
|
crossorigin="anonymous"></script>
|
|
```
|
|
|
|
#### 3. Input Sanitization
|
|
```typescript
|
|
// Install DOMPurify
|
|
import DOMPurify from 'dompurify'
|
|
|
|
const sanitizedInput = DOMPurify.sanitize(userInput)
|
|
```
|
|
|
|
#### 4. Two-Factor Authentication (2FA)
|
|
- Add TOTP support (Google Authenticator)
|
|
- SMS verification
|
|
- Backup codes
|
|
|
|
#### 5. Password Strength Meter
|
|
```typescript
|
|
// Install zxcvbn
|
|
import zxcvbn from 'zxcvbn'
|
|
|
|
const strength = zxcvbn(password)
|
|
// Show strength indicator to user
|
|
```
|
|
|
|
### Backend (Additional)
|
|
|
|
#### 1. API Versioning
|
|
```javascript
|
|
app.use('/api/v1', v1Routes)
|
|
app.use('/api/v2', v2Routes)
|
|
```
|
|
|
|
#### 2. Request Signing
|
|
- Sign requests with HMAC
|
|
- Verify signature on backend
|
|
- Prevents request tampering
|
|
|
|
#### 3. IP Whitelisting (Admin Panel)
|
|
```javascript
|
|
const adminIpWhitelist = ['192.168.1.1', '10.0.0.1']
|
|
|
|
const ipWhitelistMiddleware = (req, res, next) => {
|
|
if (!adminIpWhitelist.includes(req.ip)) {
|
|
return res.status(403).json({ message: 'Access denied' })
|
|
}
|
|
next()
|
|
}
|
|
|
|
app.use('/admin', ipWhitelistMiddleware)
|
|
```
|
|
|
|
#### 4. Geo-blocking
|
|
- Block requests from certain countries
|
|
- Use CloudFlare or similar service
|
|
|
|
#### 5. DDoS Protection
|
|
- Use CloudFlare, AWS Shield
|
|
- Rate limiting at infrastructure level
|
|
- CDN for static assets
|
|
|
|
## Security Testing
|
|
|
|
### Automated Testing
|
|
- ⚠️ **OWASP ZAP**: Automated security scanning
|
|
- ⚠️ **npm audit**: Check for vulnerable dependencies
|
|
- ⚠️ **Snyk**: Continuous security monitoring
|
|
- ⚠️ **SonarQube**: Code quality and security
|
|
|
|
```bash
|
|
# Run security audit
|
|
npm audit
|
|
npm audit fix
|
|
|
|
# Check for outdated packages
|
|
npm outdated
|
|
```
|
|
|
|
### Manual Testing
|
|
- ⚠️ **Penetration Testing**: Hire security experts
|
|
- ⚠️ **Code Review**: Security-focused code reviews
|
|
- ⚠️ **Vulnerability Scanning**: Regular scans
|
|
|
|
## Compliance
|
|
|
|
### GDPR (EU)
|
|
- ⚠️ **Data Minimization**: Collect only necessary data
|
|
- ⚠️ **Right to Erasure**: Allow users to delete their data
|
|
- ⚠️ **Data Portability**: Export user data
|
|
- ⚠️ **Consent**: Explicit consent for data processing
|
|
- ⚠️ **Privacy Policy**: Clear privacy policy
|
|
|
|
### HIPAA (Healthcare - US)
|
|
- ⚠️ **Encryption**: Encrypt PHI at rest and in transit
|
|
- ⚠️ **Access Controls**: Role-based access
|
|
- ⚠️ **Audit Logs**: Track all PHI access
|
|
- ⚠️ **Business Associate Agreement**: With third parties
|
|
|
|
### PCI DSS (Payment Cards)
|
|
- ⚠️ **Never Store**: CVV, full card numbers
|
|
- ⚠️ **Tokenization**: Use payment gateway tokens
|
|
- ⚠️ **Encryption**: Encrypt cardholder data
|
|
|
|
## Monitoring & Alerting
|
|
|
|
### What to Monitor
|
|
- ⚠️ **Failed Login Attempts**: Alert on threshold
|
|
- ⚠️ **Unusual Activity**: Large data exports, bulk deletions
|
|
- ⚠️ **API Errors**: Spike in 401/403/500 errors
|
|
- ⚠️ **Performance**: Slow queries, high CPU
|
|
- ⚠️ **Security Events**: Unauthorized access attempts
|
|
|
|
### Tools
|
|
- **Sentry**: Error tracking
|
|
- **DataDog**: Application monitoring
|
|
- **CloudWatch**: AWS monitoring
|
|
- **Prometheus + Grafana**: Metrics and dashboards
|
|
|
|
## Incident Response Plan
|
|
|
|
### Steps
|
|
1. **Detect**: Identify security incident
|
|
2. **Contain**: Isolate affected systems
|
|
3. **Investigate**: Determine scope and impact
|
|
4. **Remediate**: Fix vulnerability
|
|
5. **Recover**: Restore normal operations
|
|
6. **Review**: Post-incident analysis
|
|
|
|
### Contacts
|
|
- Security team email
|
|
- On-call engineer
|
|
- Legal team (for data breaches)
|
|
- PR team (for public disclosure)
|
|
|
|
## Summary
|
|
|
|
### Current Status
|
|
✅ **Frontend**: Implements industry-standard security patterns
|
|
⚠️ **Backend**: Must implement security measures listed above
|
|
|
|
### Priority Actions (Backend)
|
|
1. 🔴 **Critical**: Implement httpOnly cookies
|
|
2. 🔴 **Critical**: Hash passwords with bcrypt
|
|
3. 🔴 **Critical**: Add rate limiting
|
|
4. 🔴 **Critical**: Enable HTTPS in production
|
|
5. 🟡 **High**: Implement token refresh
|
|
6. 🟡 **High**: Add input validation
|
|
7. 🟡 **High**: Configure CORS properly
|
|
8. 🟡 **High**: Add security headers
|
|
9. 🟢 **Medium**: Implement audit logging
|
|
10. 🟢 **Medium**: Add 2FA support
|
|
|
|
### Security Score
|
|
- **Frontend**: 9/10 ✅
|
|
- **Backend**: Depends on implementation ⚠️
|
|
- **Overall**: Requires backend security implementation
|
|
|
|
### Next Steps
|
|
1. Review this checklist with backend team
|
|
2. Implement critical security measures
|
|
3. Conduct security audit
|
|
4. Set up monitoring and alerting
|
|
5. Create incident response plan
|
|
6. Regular security reviews and updates
|