# 📋 Security Deployment Checklist

## Pre-Deployment

### 1. Backup Current State
```bash
# Backup database
mysqldump -u root -p sellzaki_db > backup_$(date +%Y%m%d_%H%M%S).sql

# Backup nginx config
sudo cp /etc/nginx/sites-available/sellzaki.com /etc/nginx/sites-available/sellzaki.com.backup

# Note current git commit
cd /var/www/html/sellzaki.com/production
git log -1 --oneline
```

### 2. Verify Prerequisites
- [ ] SSH access to production server
- [ ] Sudo privileges
- [ ] Git repository access
- [ ] Backup completed
- [ ] Maintenance window scheduled (optional)

---

## Phase 1: Emergency Response (5 minutes)

### Block Attacker IP
```bash
# Method 1: Nginx (recommended)
echo "deny 41.44.117.225;" | sudo tee -a /etc/nginx/conf.d/blocked-ips.conf
sudo nginx -t
sudo systemctl reload nginx
```

**Verification:**
```bash
curl -I https://tyson.sellzaki.com --header "X-Forwarded-For: 41.44.117.225"
# Should return 403 Forbidden
```

- [ ] IP blocked via nginx
- [ ] Nginx reloaded successfully
- [ ] Block verified

### Restart PHP-FPM
```bash
# Check current status
sudo systemctl status php8.2-fpm

# Restart
sudo systemctl restart php8.2-fpm

# Verify
ps aux | grep php-fpm | wc -l
# Should show 5+ workers
```

- [ ] PHP-FPM restarted
- [ ] Workers available (5+)
- [ ] No errors in status

### Verify Site is Up
```bash
curl -I https://tyson.sellzaki.com
# Should return 200 OK
```

- [ ] Site accessible
- [ ] Response time < 1 second

---

## Phase 2: Deploy Laravel Security (10 minutes)

### Pull Latest Code
```bash
cd /var/www/html/sellzaki.com/production

# Check current branch
git branch

# Pull latest
git pull origin main

# Verify new files exist
ls -la app/Http/Middleware/AggressiveRateLimiter.php
ls -la app/Console/Commands/BlockAbusiveIP.php
```

- [ ] Code pulled successfully
- [ ] New middleware file exists
- [ ] New command files exist

### Clear Caches
```bash
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

# Verify routes loaded
php artisan route:list | grep "products/search"
# Should show aggressive.throttle middleware
```

- [ ] All caches cleared
- [ ] Routes reloaded
- [ ] Middleware visible on routes

### Test Laravel Security
```bash
# Test minimum length validation
curl -H "Authorization: Bearer $TOKEN" \
  "https://tyson.sellzaki.com/api/products/search?q=t"
# Should return error about 2 characters

# Test valid search
curl -H "Authorization: Bearer $TOKEN" \
  "https://tyson.sellzaki.com/api/products/search?q=test"
# Should return products
```

- [ ] Single-char search rejected
- [ ] Valid search works
- [ ] Response time < 500ms

---

## Phase 3: Configure Nginx (15 minutes)

### Add Rate Limit Zones
```bash
# Edit nginx.conf
sudo nano /etc/nginx/nginx.conf

# Add inside http { } block:
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=search_limit:10m rate=2r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

# Save and test
sudo nginx -t
```

- [ ] Rate limit zones added
- [ ] Nginx config valid
- [ ] No syntax errors

### Update Site Configuration
```bash
# Edit site config
sudo nano /etc/nginx/sites-available/sellzaki.com

# Add these location blocks:

# General API rate limiting
location /api/ {
    limit_req zone=api_limit burst=20 nodelay;
    limit_req_status 429;
    try_files $uri $uri/ /index.php?$query_string;
}

# Search endpoints (more restrictive)
location ~ ^/api/.*/search {
    limit_req zone=search_limit burst=5 nodelay;
    limit_req_status 429;
    access_log /var/log/nginx/search-rate-limit.log combined;
    try_files $uri $uri/ /index.php?$query_string;
}

# Login endpoint
location ~ ^/api/auth/login$ {
    limit_req zone=login_limit burst=3 nodelay;
    limit_req_status 429;
    access_log /var/log/nginx/login-rate-limit.log combined;
    try_files $uri $uri/ /index.php?$query_string;
}

# Connection limit
limit_conn conn_limit 10;

# Save and test
sudo nginx -t
```

- [ ] Location blocks added
- [ ] Nginx config valid
- [ ] Log files will be created

### Reload Nginx
```bash
sudo systemctl reload nginx

# Verify
sudo systemctl status nginx
```

- [ ] Nginx reloaded
- [ ] No errors
- [ ] Service active

### Test Nginx Rate Limiting
```bash
# Send 15 requests rapidly
for i in {1..15}; do 
  curl -s -o /dev/null -w "%{http_code}\n" \
    "https://tyson.sellzaki.com/api/products/search?q=test" \
    -H "Authorization: Bearer $TOKEN"
  sleep 0.3
done

# Should see some 429 responses
```

- [ ] Rate limiting active
- [ ] 429 responses after threshold
- [ ] Legitimate requests still work

---

## Phase 4: Verification (10 minutes)

### Run Security Test Script
```bash
cd /var/www/html/sellzaki.com/production

# Set token
export SELLZAKI_TOKEN="your-actual-token"

# Run tests
./test-security.sh
```

- [ ] Test 1 passed (minimum length)
- [ ] Test 2 passed (valid search)
- [ ] Test 3 passed (rate limiting)
- [ ] Test 4 passed (pattern detection)
- [ ] Test 5 passed (site accessible)

### Manual Verification
```bash
# 1. Check PHP-FPM workers
ps aux | grep php-fpm | wc -l
# Should be 5+

# 2. Check for errors
tail -100 storage/logs/laravel.log
# Should not have critical errors

# 3. Check nginx errors
sudo tail -100 /var/log/nginx/error.log
# Should not have critical errors

# 4. Test from browser
# Visit: https://tyson.sellzaki.com
# Should load normally
```

- [ ] PHP-FPM workers available
- [ ] No Laravel errors
- [ ] No nginx errors
- [ ] Site loads in browser

### Performance Check
```bash
# Test response time
time curl -s -o /dev/null "https://tyson.sellzaki.com"

# Should be < 1 second
```

- [ ] Response time acceptable
- [ ] No timeouts
- [ ] Site responsive

---

## Phase 5: Monitoring Setup (10 minutes)

### Create Monitoring Script
```bash
# Create monitoring script
cat > /usr/local/bin/check-abusive-ips.sh << 'EOF'
#!/bin/bash
echo "Top 20 IPs in last hour:"
sudo tail -10000 /var/log/nginx/access.log | \
  awk '{print $1}' | sort | uniq -c | sort -rn | head -20
EOF

chmod +x /usr/local/bin/check-abusive-ips.sh
```

- [ ] Monitoring script created
- [ ] Script executable
- [ ] Script tested

### Set Up Log Rotation
```bash
# Check if logrotate is configured
ls -la /etc/logrotate.d/nginx

# If not, create it
sudo nano /etc/logrotate.d/nginx-sellzaki

# Add:
/var/log/nginx/search-rate-limit.log {
    daily
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}
```

- [ ] Log rotation configured
- [ ] Logs will be retained for 14 days
- [ ] Old logs will be compressed

### Document Current State
```bash
# Save current configuration
date > /tmp/security-deployment-$(date +%Y%m%d).txt
git log -1 >> /tmp/security-deployment-$(date +%Y%m%d).txt
php artisan --version >> /tmp/security-deployment-$(date +%Y%m%d).txt
nginx -v 2>> /tmp/security-deployment-$(date +%Y%m%d).txt
```

- [ ] Deployment documented
- [ ] Versions recorded
- [ ] Git commit noted

---

## Phase 6: Post-Deployment (Ongoing)

### First Hour
- [ ] Monitor logs: `tail -f /var/log/nginx/access.log`
- [ ] Check for errors: `tail -f storage/logs/laravel.log`
- [ ] Watch PHP-FPM: `watch -n 5 'ps aux | grep php-fpm | wc -l'`
- [ ] No user complaints

### First Day
- [ ] Check blocked IPs: `grep "blocked" storage/logs/laravel.log | wc -l`
- [ ] Review rate limit hits: `grep "429" /var/log/nginx/access.log | wc -l`
- [ ] Verify no legitimate users blocked
- [ ] Performance acceptable

### First Week
- [ ] Daily log review
- [ ] Adjust rate limits if needed
- [ ] Document any issues
- [ ] Plan next improvements

---

## Rollback Plan (If Needed)

### If Laravel Issues
```bash
cd /var/www/html/sellzaki.com/production

# Revert to previous commit
git log --oneline -10  # Find previous commit
git checkout <previous-commit-hash>

# Clear caches
php artisan cache:clear
php artisan route:clear

# Verify
curl -I https://tyson.sellzaki.com
```

### If Nginx Issues
```bash
# Restore backup
sudo cp /etc/nginx/sites-available/sellzaki.com.backup \
       /etc/nginx/sites-available/sellzaki.com

# Test and reload
sudo nginx -t
sudo systemctl reload nginx
```

### If Complete Rollback Needed
```bash
# 1. Restore nginx
sudo cp /etc/nginx/sites-available/sellzaki.com.backup \
       /etc/nginx/sites-available/sellzaki.com

# 2. Revert code
cd /var/www/html/sellzaki.com/production
git checkout <previous-commit>

# 3. Clear caches
php artisan cache:clear
php artisan route:clear

# 4. Reload services
sudo systemctl reload nginx
sudo systemctl restart php8.2-fpm

# 5. Verify
curl -I https://tyson.sellzaki.com
```

---

## Success Criteria

### Technical
- [x] Attacker IP blocked
- [x] PHP-FPM workers available (5+)
- [x] Rate limiting active
- [x] Input validation working
- [x] Auto-blocking functional
- [x] Site accessible
- [x] Response time < 500ms
- [x] No critical errors

### Business
- [x] No downtime during deployment
- [x] No user complaints
- [x] Search functionality works
- [x] Performance maintained
- [x] Attack stopped

---

## Sign-Off

**Deployed By**: ___________________  
**Date**: ___________________  
**Time**: ___________________  
**Git Commit**: ___________________  
**Issues Encountered**: ___________________  
**Notes**: ___________________  

---

## Next Steps

1. **Monitor for 48 hours** - Watch logs and performance
2. **Review blocked IPs** - Check if legitimate users affected
3. **Adjust if needed** - Fine-tune rate limits
4. **Document lessons** - Update runbooks
5. **Plan improvements** - Cloudflare, fail2ban, etc.

---

**Status**: Ready for deployment ✅  
**Estimated Time**: 50 minutes  
**Risk Level**: Low (can be rolled back)  
**Impact**: High (stops current attack + prevents future)
