# Security Deployment Guide

## Immediate Actions to Block Attack

### 1. Block the Abusive IP Immediately (41.44.117.225)

```bash
# Option A: Using Laravel artisan command
php artisan security:block-ip 41.44.117.225 --minutes=1440

# Option B: Using nginx (faster, blocks before reaching PHP)
sudo nano /etc/nginx/conf.d/blocked-ips.conf
# Add this line:
deny 41.44.117.225;
# Save and reload:
sudo nginx -t && sudo systemctl reload nginx
```

### 2. Clear PHP-FPM to Free Workers

```bash
# Restart PHP-FPM to kill stuck processes
sudo systemctl restart php8.2-fpm  # or your PHP version

# Check worker status
sudo systemctl status php8.2-fpm
```

### 3. Deploy Laravel Security Updates

```bash
cd /var/www/html/sellzaki.com/production

# Pull latest code with security fixes
git pull origin main

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

# No need to rebuild frontend (backend-only changes)
```

## What Was Fixed

### 1. **Aggressive Rate Limiting Middleware** (`app/Http/Middleware/AggressiveRateLimiter.php`)
   - Detects single-character searches (very expensive)
   - Tracks suspicious patterns per IP
   - Auto-blocks IPs with abuse score > 20
   - Extended 30-minute block for repeat offenders

### 2. **Search Endpoint Protection** (`app/Http/Controllers/User/SalesController.php`)
   - **Minimum 2 characters required** for search (prevents "q=t" attacks)
   - Input sanitization to prevent injection
   - Returns friendly error for short queries

### 3. **Route-Level Rate Limiting** (`routes/api.php`)
   - `/api/products/search`: **10 requests/minute per IP**
   - Uses aggressive middleware with pattern detection

### 4. **Manual IP Management Commands**
   ```bash
   # Block an IP
   php artisan security:block-ip 1.2.3.4 --minutes=60
   
   # Unblock an IP
   php artisan security:unblock-ip 1.2.3.4
   ```

## Nginx Configuration (Recommended)

### Deploy Nginx Rate Limiting

```bash
# 1. Add rate limit zones to 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;

# 2. Update your site's server block
sudo nano /etc/nginx/sites-available/sellzaki.com

# Add these location blocks (see nginx-rate-limit.conf for full config):
location ~ ^/api/.*/search {
    limit_req zone=search_limit burst=5 nodelay;
    limit_req_status 429;
    # ... rest of config
}

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

### Create IP Blacklist File

```bash
# Create blacklist
sudo nano /etc/nginx/conf.d/blocked-ips.conf

# Add:
deny 41.44.117.225;
allow all;

# Include in your server block:
# include /etc/nginx/conf.d/blocked-ips.conf;

# Reload
sudo nginx -t && sudo systemctl reload nginx
```

## Monitoring

### Check for Abusive IPs

```bash
# See top IPs hitting your server
sudo tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -20

# See blocked search requests
sudo tail -f /var/log/nginx/search-rate-limit.log

# Check Laravel logs for suspicious activity
tail -f storage/logs/laravel.log | grep -i "suspicious\|blocked"
```

### Monitor PHP-FPM Workers

```bash
# Check worker status
sudo systemctl status php8.2-fpm

# See active processes
ps aux | grep php-fpm | wc -l

# Monitor pool status (if configured)
curl http://localhost/php-fpm-status
```

## Security Layers Summary

1. **Nginx Level** (First line of defense)
   - Rate limiting: 2 req/sec for search
   - Connection limiting: 10 concurrent per IP
   - IP blacklist
   - Bad user-agent blocking

2. **Laravel Middleware Level**
   - Aggressive rate limiter with pattern detection
   - Suspicious activity scoring
   - Auto-blocking for repeat offenders

3. **Application Level**
   - Minimum query length validation
   - Input sanitization
   - Result limiting

4. **API Level**
   - Global throttle: 1200 req/min
   - Per-route throttle: 10 req/min for search

## Testing

```bash
# Test rate limiting works
for i in {1..15}; do 
  curl -H "Authorization: Bearer YOUR_TOKEN" \
    "https://tyson.sellzaki.com/api/products/search?q=test" 
  sleep 0.5
done

# Should see 429 responses after 10 requests
```

## Rollback (if needed)

```bash
# Remove aggressive throttle from routes
# Edit routes/api.php and remove ->middleware('aggressive.throttle:10,1')

# Remove nginx rate limiting
# Comment out limit_req lines in nginx config

# Reload services
php artisan route:clear
sudo systemctl reload nginx
```

## Future Enhancements

1. **Cloudflare/CDN**: Add DDoS protection layer
2. **Fail2ban**: Auto-block IPs based on log patterns
3. **Redis**: Use Redis for faster rate limit checks
4. **Monitoring**: Set up alerts for high request rates
5. **CAPTCHA**: Add for repeated failed attempts
