Files
picpeak/backend/AUTH_V2_DEPLOYMENT_PLAN.md
T
paul f38014099e
Test and Lint / backend-test (push) Successful in 1m12s
continuous-integration/drone/push Build is passing
Test and Lint / frontend-test (push) Successful in 2m16s
Version and Release / version-bump (push) Successful in 35s
Version and Release / trigger-drone (push) Successful in 3s
fix: show hero image in thumbnail grid on hero gallery layout
2025-07-13 20:03:27 +02:00

5.9 KiB

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

npm install zxcvbn@4.4.2

Database Migrations

-- 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

    cd backend
    npm install zxcvbn@4.4.2
    
  2. Run Migrations

    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

    # Try with invalid token
    curl -H "Authorization: Bearer invalid-token" \
      http://localhost:3001/api/admin/events
    # Should apply rate limiting
    
  2. Test Password Validation

    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

// 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

// In server.js, change to v2
const authRoutes = require('./src/routes/auth-enhanced-v2');

Step 3: Update Middleware

// Update imports to use v2
const { adminAuth } = require('./src/middleware/auth-enhanced-v2');

Step 4: Update Event Creation

// 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

// In server.js, after initializeCleanupJob()
const { initializeRevocationCleanup } = require('./src/utils/tokenRevocation');
initializeRevocationCleanup();

Environment Variables

Add to .env:

# 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

# 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

docker-compose logs backend | grep "Password validation failed"

Check Rate Limiting

docker-compose logs backend | grep "Rate limit"

Check Token Revocations

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