# Authentication Security V2 Deployment Plan ## Overview This deployment adds remaining authentication security fixes identified in the security scan. ## New Security Features ### 1. Rate Limiting Bypass Fix ✅ - **File**: `src/utils/rateLimitSecurity.js` - **Fix**: Properly validates JWT before skipping rate limit - **Impact**: Prevents attackers from bypassing with invalid tokens ### 2. Password Complexity Requirements ✅ - **File**: `src/utils/passwordValidation.js` - **Features**: - Minimum 12 characters (up from 6) - Must contain: uppercase, lowercase, numbers, special chars - Password strength scoring (zxcvbn) - Context-aware validation (admin vs gallery) - Configurable bcrypt rounds ### 3. Token Revocation System ✅ - **Files**: `src/utils/tokenRevocation.js`, migration - **Features**: - Revoke individual tokens - Revoke all user tokens - Automatic cleanup of expired revocations - Check on every auth request ### 4. Enhanced Auth Routes ✅ - **File**: `src/routes/auth-enhanced-v2.js` - **Features**: - Password change endpoint with validation - Real-time password strength checking - Better error responses with feedback ## Dependencies to Install ```bash npm install zxcvbn@4.4.2 ``` ## Database Migrations ```sql -- Token revocation tables CREATE TABLE revoked_tokens ( id INTEGER PRIMARY KEY, token_id TEXT UNIQUE NOT NULL, user_id INTEGER, token_type TEXT, revoked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMP NOT NULL, reason TEXT, metadata TEXT ); CREATE TABLE user_token_revocations ( user_id INTEGER PRIMARY KEY, revoked_at TIMESTAMP NOT NULL, reason TEXT ); ``` ## Deployment Steps ### Phase 1: Preparation (Day 1) 1. **Install Dependencies** ```bash cd backend npm install zxcvbn@4.4.2 ``` 2. **Run Migrations** ```bash docker exec wedding-photo-sharing-backend-1 node scripts/add-token-revocation-tables.js ``` 3. **Deploy New Files** (No impact yet) - `rateLimitSecurity.js` - `passwordValidation.js` - `tokenRevocation.js` - `auth-enhanced-v2.js` ### Phase 2: Testing (Day 2) 1. **Test Rate Limiting Fix** ```bash # Try with invalid token curl -H "Authorization: Bearer invalid-token" \ http://localhost:3001/api/admin/events # Should apply rate limiting ``` 2. **Test Password Validation** ```bash node -e " const {validatePassword} = require('./src/utils/passwordValidation'); console.log(validatePassword('weak')); console.log(validatePassword('StrongP@ssw0rd123')); " ``` ### Phase 3: Gradual Activation (Day 3) #### Step 1: Update Server.js for Rate Limiting ```javascript // Replace in server.js const { createSecureSkipFunction, logRateLimitHit } = require('./src/utils/rateLimitSecurity'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: process.env.NODE_ENV === 'development' ? 1000 : 100, skip: createSecureSkipFunction(), // NEW: Secure skip function handler: (req, res) => { logRateLimitHit(req, res); // NEW: Logging res.status(429).json({ error: 'Too many requests from this IP, please try again later.' }); } }); ``` #### Step 2: Update Auth Routes ```javascript // In server.js, change to v2 const authRoutes = require('./src/routes/auth-enhanced-v2'); ``` #### Step 3: Update Middleware ```javascript // Update imports to use v2 const { adminAuth } = require('./src/middleware/auth-enhanced-v2'); ``` #### Step 4: Update Event Creation ```javascript // In adminEvents.js, add password validation const { validatePasswordInContext, getBcryptRounds } = require('../utils/passwordValidation'); // In the POST route, add validation before hashing ``` #### Step 5: Initialize Token Revocation ```javascript // In server.js, after initializeCleanupJob() const { initializeRevocationCleanup } = require('./src/utils/tokenRevocation'); initializeRevocationCleanup(); ``` ## Environment Variables Add to `.env`: ```bash # Bcrypt rounds (12-14 recommended) BCRYPT_ROUNDS=12 ``` ## Testing Checklist - [ ] Invalid tokens can't bypass rate limiting - [ ] Weak passwords are rejected - [ ] Password change requires strong password - [ ] Tokens can be revoked - [ ] Revoked tokens are rejected - [ ] Admin passwords require higher strength - [ ] Gallery passwords check for event name ## Rollback Plan ### Quick Rollback ```bash # Revert server.js changes git checkout HEAD -- server.js # Restart docker-compose restart backend ``` ### Rollback Specific Features 1. **Rate Limiting**: Revert to old skip function 2. **Password Validation**: Remove validation calls 3. **Token Revocation**: Skip revocation checks ## Monitoring ### Check Password Validation Failures ```bash docker-compose logs backend | grep "Password validation failed" ``` ### Check Rate Limiting ```bash docker-compose logs backend | grep "Rate limit" ``` ### Check Token Revocations ```bash docker exec wedding-photo-sharing-backend-1 node -e " const {db} = require('./src/database/db'); db('revoked_tokens').count().first() .then(r => console.log('Revoked tokens:', r['count(*)'] || 0)) .then(() => db.destroy()); " ``` ## Security Improvements | Feature | Before | After | |---------|---------|--------| | Rate Limiting | Can bypass with invalid token | Properly validated | | Password Length | 6 chars | 12 chars minimum | | Password Complexity | None | Upper+lower+number+special | | Password Strength | Not checked | zxcvbn scoring | | Token Revocation | Not possible | Full revocation system | | Bcrypt Rounds | Fixed (10) | Configurable (12) | ## Performance Considerations 1. **Password Validation**: ~50ms per check (zxcvbn) 2. **Token Revocation**: Adds 1 DB query per request 3. **Bcrypt Rounds**: 12 rounds = ~250ms (vs 100ms for 10) ## Success Criteria - ✅ No invalid tokens bypass rate limiting - ✅ All new passwords meet complexity requirements - ✅ Password change works with validation - ✅ Tokens can be revoked on logout - ✅ No performance degradation > 100ms