# Deployment Checklist - Advanced Rate Limiting & Security Fixes

## ✅ Completed (Ready for Deployment)

### 1. Security Vulnerabilities Fixed
- [x] **Mass Assignment Protection**
  - User model: Protected `role_id`, `created_at`, `updated_at`
  - Wallets model: Protected `ngn_balance`, `cad_balance`
  
- [x] **Email Validation**
  - Added unique email validation in registration
  
- [x] **OTP Security**
  - Reduced OTP expiration from 1 day to 10 minutes
  
- [x] **Wallet Transaction Security**
  - Fixed `check_wallet_balance()` to only check, not debit
  - Added proper wallet debit in `ngn_transfer()` with DB transactions
  - Added replay attack prevention (duplicate `customers_reference` check)
  
- [x] **Webhook Security**
  - Moved Fincra webhook secret to environment variable

### 2. Rate Limiting Infrastructure Created
- [x] **Database Models**
  - `app/Models/IPBlacklist.php` - Blacklist management
  - `app/Models/RateLimitViolation.php` - Violation tracking
  
- [x] **Database Migrations**
  - `2026_02_28_000001_create_ip_blacklist_table.php`
  - `2026_02_28_000002_create_rate_limit_violations_table.php`
  
- [x] **Middleware**
  - `app/Http/Middleware/AdvancedRateLimitMiddleware.php` - Core rate limiting logic
  - Registered as `rate.limit.advanced` in `app/Http/Kernel.php`
  
- [x] **Admin Controller**
  - `app/Http/Controllers/IPBlacklistController.php` - Blacklist CRUD operations
  - Admin routes in `routes/allapiroutes/ip-blacklist.php`
  
- [x] **Console Command**
  - `app/Console/Commands/CleanRateLimitViolations.php` - Cleanup old violations
  - Scheduled to run daily in `app/Console/Kernel.php`

### 3. Rate Limits Applied to Routes

#### Authentication (Very Strict)
- [x] Login: 5 requests/minute → blacklist after 5 violations
- [x] Registration: 3 requests/minute → blacklist after 3 violations
- [x] Password Reset: 3 requests/5 minutes → blacklist after 5 violations

#### Financial Transfers (Strict)
- [x] NGN Transfer: 10 requests/minute → blacklist after 10 violations
- [x] International Transfer: 5 requests/minute → blacklist after 8 violations
- [x] Bulk Transfer: 2 requests/minute → blacklist after 5 violations

#### Bill Payments (Moderate)
- [x] Airtime: 20 requests/minute → blacklist after 15 violations
- [x] Data: 20 requests/minute → blacklist after 15 violations
- [x] Electricity: 15 requests/minute → blacklist after 12 violations
- [x] Cable TV: 15 requests/minute → blacklist after 12 violations
- [x] Betting: 15 requests/minute → blacklist after 12 violations
- [x] VTU Billers: 30 requests/minute → blacklist after 20 violations

### 4. Documentation Created
- [x] `RATE_LIMITING_IMPLEMENTATION.md` - Complete implementation guide
- [x] `DEPLOYMENT_CHECKLIST.md` - This file
- [x] Previous docs: `CRITICAL_SECURITY_FIXES.md`, `SECURITY_FIXES_APPLIED.md`, `TRANSFER_SECURITY_FIXES.md`

---

## 🚀 Deployment Steps (DO THESE IN ORDER)

### Step 1: Backup Database
```bash
# Create a backup before making any changes
cd /Applications/Projects/Payonline/backend-v2
php artisan backup:database
```

### Step 2: Run Migrations
```bash
# Create the new tables
php artisan migrate

# You should see:
# - 2026_02_28_000001_create_ip_blacklist_table.php
# - 2026_02_28_000002_create_rate_limit_violations_table.php
```

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

### Step 4: Update Environment Variables
Add to `.env` file:
```env
# Webhook Security
FINCRA_WEBHOOK_SECRET=your_generated_secret_here
```

Generate a new secret:
```bash
openssl rand -hex 32
```

### Step 5: Test Rate Limiting

#### Test Login Rate Limit (Should block after 5 attempts)
```bash
for i in {1..10}; do
  echo "Request $i:"
  curl -X POST http://your-domain.com/api/login \
    -H "Content-Type: application/json" \
    -d '{"email":"test@test.com","password":"wrongpassword"}'
  echo "\n---"
  sleep 2
done
```

Expected behavior:
- Requests 1-5: Accept (200 or 401 with rate limit headers)
- Requests 6+: Reject with 429 Too Many Requests
- After 5 violations: 403 Forbidden (IP blacklisted)

#### Test Transfer Rate Limit
```bash
# Login first to get a token
TOKEN=$(curl -X POST http://your-domain.com/api/login \
  -H "Content-Type: application/json" \
  -d '{"email":"valid@user.com","password":"correctpassword"}' \
  | jq -r '.data.token')

# Try 15 transfers quickly
for i in {1..15}; do
  echo "Transfer $i:"
  curl -X POST http://your-domain.com/api/transfer/ngn \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"amount":100,"bank_code":"058","account_number":"0123456789","pin":"1234"}'
  echo "\n---"
  sleep 1
done
```

### Step 6: Verify Database Tables
```bash
# Check if tables were created
php artisan tinker

# In tinker:
DB::table('ip_blacklist')->count();
DB::table('rate_limit_violations')->count();
```

### Step 7: Test Admin Endpoints
```bash
# Login as admin
ADMIN_TOKEN=$(curl -X POST http://your-domain.com/api/admin/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@example.com","password":"adminpass"}' \
  | jq -r '.data.token')

# Get blacklist statistics
curl -X GET http://your-domain.com/api/admin/ip-blacklist/stats \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# List blacklisted IPs
curl -X GET http://your-domain.com/api/admin/ip-blacklist \
  -H "Authorization: Bearer $ADMIN_TOKEN"
```

---

## ⚠️ Post-Deployment Monitoring

### Day 1: Check Logs
```bash
# Monitor for rate limiting events
tail -f storage/logs/laravel.log | grep -i "rate limit"

# Watch for blacklist events
tail -f storage/logs/laravel.log | grep -i "blacklist"
```

### Week 1: Review Blacklisted IPs
```sql
-- Check automatic blacklists
SELECT ip_address, violation_count, reason, created_at
FROM ip_blacklist
WHERE blacklisted_by IS NULL
ORDER BY created_at DESC;

-- Check violation patterns
SELECT endpoint, COUNT(*) as total_violations
FROM rate_limit_violations
GROUP BY endpoint
ORDER BY total_violations DESC;
```

### Monthly: Adjust Rate Limits
Based on your traffic patterns, you may need to adjust limits in:
`app/Http/Middleware/AdvancedRateLimitMiddleware.php`

---

## 🔍 Forensic Analysis (Optional)

### Check for Compromised Accounts from February 27 Attack

```sql
-- Find users with duplicate wallets
SELECT user_id, COUNT(*) as wallet_count, GROUP_CONCAT(id) as wallet_ids
FROM wallets
GROUP BY user_id
HAVING wallet_count > 1;

-- Find transactions with duplicate reference numbers
SELECT customers_reference, COUNT(*) as count, GROUP_CONCAT(id) as transaction_ids
FROM transactions
WHERE customers_reference IS NOT NULL
GROUP BY customers_reference
HAVING count > 1;

-- Find users created during attack window
SELECT id, name, email, created_at
FROM users
WHERE created_at BETWEEN '2026-02-27 00:00:00' AND '2026-02-28 00:00:00'
ORDER BY created_at;

-- Check for unusual wallet balances
SELECT u.id, u.email, w.ngn_balance, w.cad_balance, w.created_at
FROM users u
JOIN wallets w ON u.id = w.user_id
WHERE w.ngn_balance > 0 OR w.cad_balance > 0
AND w.created_at BETWEEN '2026-02-27 00:00:00' AND '2026-02-28 00:00:00';
```

---

## ⚙️ Scheduled Tasks

The following scheduled tasks are now configured:

```php
// app/Console/Kernel.php
$schedule->command('rate-limit:clean --days=30')->daily();
```

Make sure your cron job is running:
```bash
# Add to crontab if not already there
* * * * * cd /Applications/Projects/Payonline/backend-v2 && php artisan schedule:run >> /dev/null 2>&1
```

---

## 🛡️ Additional Security Recommendations

### 1. Email Notifications
Consider adding email notifications when IPs are blacklisted:
```php
// In AdvancedRateLimitMiddleware::blacklistIP()
Mail::to('security@yourdomain.com')->send(new IPBlacklistedNotification($ipAddress, $endpoint));
```

### 2. Whitelist Trusted IPs
Add to `.env`:
```env
TRUSTED_IP_WHITELIST=127.0.0.1,your-office-ip,your-server-ip
```

Then in middleware:
```php
if (in_array($ipAddress, config('app.trusted_ips'))) {
    return $next($request);
}
```

### 3. Review Other Controllers
The following controllers should be reviewed to ensure they properly debit wallets:
- `app/Http/Controllers/PagaBillersController.php` (5 bill payment methods)
- `app/Http/Controllers/RechargeController.php` (airtime/data methods)
- `app/Http/Controllers/ElectricityController.php`
- `app/Http/Controllers/CableTvController.php`

**Pattern to follow** (from TransferController):
```php
DB::beginTransaction();
try {
    // 1. Check balance (using check_wallet_balance)
    $this->check_wallet_balance($user, $amount, 'ngn');
    
    // 2. Process transaction (external API call)
    $result = $this->processPayment(...);
    
    // 3. Debit wallet AFTER success
    $this->update_wallet($user, $amount, 'ngn', 'debit');
    
    DB::commit();
    return response()->json(['success' => true]);
} catch (\Exception $e) {
    DB::rollBack();
    return response()->json(['success' => false, 'message' => $e->getMessage()]);
}
```

### 4. Two-Factor Authentication
Consider adding 2FA for high-risk operations:
- Large transfers (> certain amount)
- PIN changes
- Email/phone number changes
- Withdrawal to new bank accounts

---

## 📊 Key Metrics to Monitor

1. **Blacklist Growth Rate**
   - Normal: 1-5 IPs per day
   - Alert: 10+ IPs per day

2. **Rate Limit Violations**
   - Normal: < 100 violations/day
   - Alert: 500+ violations/day

3. **Top Violating Endpoints**
   - Should be distributed across all endpoints
   - If one endpoint dominates, may need adjustment

4. **False Positives**
   - Legitimate users getting blacklisted
   - Review violation thresholds if this occurs

---

## ✅ Final Verification Checklist

Before going to production:

- [ ] Migrations run successfully
- [ ] Rate limiting tested on all endpoints
- [ ] Admin can view/manage blacklist
- [ ] Scheduled commands working
- [ ] Environment variables set
- [ ] Logs are being written
- [ ] Backup created
- [ ] Team briefed on new system
- [ ] Documentation reviewed
- [ ] Forensic queries run (optional)

---

## 🆘 Troubleshooting

### Legitimate User Blacklisted
```bash
# Via admin panel
curl -X DELETE http://your-domain.com/api/admin/ip-blacklist/{id} \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# Or directly in database
UPDATE ip_blacklist SET is_active = 0 WHERE ip_address = '123.45.67.89';
```

### Rate Limits Too Strict
Edit `app/Http/Middleware/AdvancedRateLimitMiddleware.php`:
```php
'auth:login' => [10, 1, 10],  // Increased from 5 to 10
```

### Clear All Rate Limit Data
```bash
php artisan rate-limit:clean --days=0
php artisan cache:clear
```

---

## 📞 Support & Documentation

- Main Documentation: `RATE_LIMITING_IMPLEMENTATION.md`
- Security Fixes: `SECURITY_FIXES_APPLIED.md`
- Transfer Security: `TRANSFER_SECURITY_FIXES.md`

---

**Last Updated:** February 28, 2026
**System Status:** ✅ Ready for Production Deployment
