Files
picpeak/backend/AUTH_SECURITY_MIGRATION.md
T
paul e35ac6a41c
Test Gitea Actions / test (push) Successful in 20s
continuous-integration/drone/push Build is passing
feat: implement critical security fixes for SQL injection and authentication vulnerabilities
Security Enhancements:
- Fix SQL injection vulnerabilities by replacing whereRaw queries with parameterized queries
- Add LIKE pattern escaping to prevent SQL injection in search functionality
- Implement account lockout protection (5 failed attempts = 30 min lockout)
- Add comprehensive login attempt tracking and audit trail
- Enhance JWT tokens with issuer validation, IP tracking, and password change detection
- Add logout endpoint and session management
- Prevent user enumeration with generic error messages

Database Changes:
- Add login_attempts table for authentication tracking
- Add security columns to admin_users (password_changed_at, last_login_ip, two_factor_enabled)

New Security Features:
- Brute force protection with configurable lockout duration
- Automatic cleanup of old login attempts
- Enhanced authentication middleware with stricter validation
- Monitoring scripts for security health checks

All fixes are backward compatible and production-ready with rollback plans included.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-13 00:40:05 +02:00

5.5 KiB

Authentication Security Enhancement Migration Guide

Overview

This guide provides a safe migration path to enhance authentication security without disrupting the production system.

Security Enhancements Implemented

1. Account Lockout Protection

  • Locks accounts after 5 failed login attempts within 15 minutes
  • 30-minute lockout duration
  • Prevents brute force attacks

2. Login Attempt Tracking

  • Records all login attempts (success/failure)
  • Tracks IP addresses and user agents
  • Enables security monitoring and alerting

3. Enhanced Token Security

  • Added issuer validation
  • IP address tracking in tokens
  • Login time tracking
  • Password change detection

4. Generic Error Messages

  • Prevents user enumeration attacks
  • Returns "Invalid credentials" for all auth failures

5. Logout Endpoint

  • Properly invalidates sessions
  • Clears server-side session tracking

Migration Steps

Step 1: Database Migrations (Low Risk)

First, run the new migrations to add required tables/columns:

cd backend

# Run new migrations
npx knex migrate:latest

# Verify migrations
npx knex migrate:status

This adds:

  • login_attempts table
  • password_changed_at column to admin_users
  • last_login_ip column to admin_users

Step 2: Deploy Enhanced Auth Utilities (Low Risk)

The new files don't affect existing functionality:

  • src/utils/authSecurity.js - New security utilities
  • src/middleware/auth-enhanced.js - Enhanced auth middleware
  • src/routes/auth-enhanced.js - Enhanced auth routes

Step 3: Gradual Rollout Plan

Phase 1: Testing (Day 1)

  1. Deploy code but keep using existing auth routes
  2. Test enhanced routes in parallel:
    # Test existing endpoint
    curl -X POST http://localhost:3001/api/auth/admin/login
    
    # Test enhanced endpoint (if added to routes)
    curl -X POST http://localhost:3001/api/auth-enhanced/admin/login
    

Phase 2: Monitoring (Days 2-3)

  1. Add the auth security initialization to server.js:

    // In server.js, after database initialization
    const { initializeCleanupJob } = require('./src/utils/authSecurity');
    initializeCleanupJob();
    
  2. Monitor logs for any issues

  3. Check login_attempts table is populating

Phase 3: Switch Routes (Day 4)

  1. Update route imports in server.js:

    // Change from:
    const authRoutes = require('./src/routes/auth');
    
    // To:
    const authRoutes = require('./src/routes/auth-enhanced');
    
  2. Update middleware imports where needed:

    // Change from:
    const { adminAuth } = require('./src/middleware/auth');
    
    // To:
    const { adminAuth } = require('./src/middleware/auth-enhanced');
    

Step 4: Rollback Plan

If issues occur at any phase:

# Quick rollback - revert route imports
# In server.js, change back to:
const authRoutes = require('./src/routes/auth');
const { adminAuth } = require('./src/middleware/auth');

# Restart application
docker-compose restart backend
# or
pm2 restart picpeak-backend

Testing Checklist

Before Production Deployment:

  1. Test Normal Login Flow:

    # Should work normally
    curl -X POST http://localhost:3001/api/auth/admin/login \
      -H "Content-Type: application/json" \
      -d '{"username":"admin","password":"correct-password"}'
    
  2. Test Account Lockout:

    # Make 5 failed attempts
    for i in {1..5}; do
      curl -X POST http://localhost:3001/api/auth/admin/login \
        -H "Content-Type: application/json" \
        -d '{"username":"admin","password":"wrong-password"}'
    done
    
    # 6th attempt should return lockout error
    
  3. Test Logout:

    curl -X POST http://localhost:3001/api/auth/logout \
      -H "Authorization: Bearer YOUR_TOKEN"
    
  4. Test Session Info:

    curl http://localhost:3001/api/auth/session \
      -H "Authorization: Bearer YOUR_TOKEN"
    

Configuration Options

Adjusting Security Settings

In src/utils/authSecurity.js, you can adjust:

const MAX_LOGIN_ATTEMPTS = 5;  // Number of attempts before lockout
const LOCKOUT_DURATION = 30 * 60 * 1000;  // Lockout time in ms
const ATTEMPT_WINDOW = 15 * 60 * 1000;  // Time window for counting attempts

Monitoring

Check Login Attempts:

-- Recent failed attempts
SELECT * FROM login_attempts 
WHERE success = false 
ORDER BY attempt_time DESC 
LIMIT 20;

-- Accounts with multiple failures
SELECT identifier, COUNT(*) as failed_attempts
FROM login_attempts
WHERE success = false
AND attempt_time > datetime('now', '-1 hour')
GROUP BY identifier
HAVING COUNT(*) > 3;

Monitor Locked Accounts:

-- Check currently locked accounts
SELECT identifier, COUNT(*) as attempts,
       MAX(attempt_time) as last_attempt
FROM login_attempts
WHERE success = false
AND attempt_time > datetime('now', '-15 minutes')
GROUP BY identifier
HAVING COUNT(*) >= 5;

Security Benefits

  1. Prevents Brute Force: Account lockout after failed attempts
  2. Audit Trail: Complete login history for security analysis
  3. Session Security: Tokens invalidated on password change
  4. IP Monitoring: Detect suspicious login patterns
  5. User Privacy: Generic errors prevent user enumeration

Notes

  • Old tokens remain valid until expiration
  • No immediate user impact
  • Gradual rollout minimizes risk
  • Full rollback possible at any stage

Support

Monitor logs after deployment:

# Docker
docker-compose logs -f backend | grep -E "(auth|login|security)"

# PM2
pm2 logs picpeak-backend | grep -E "(auth|login|security)"