# Advanced Rate Limiting with IP Blacklisting

## Overview

This system implements advanced rate limiting with automatic IP blacklisting for enhanced security across all API endpoints including authentication, transfers, and bill payments.

---

## Features

✅ **Progressive Rate Limiting** - Different limits for different endpoint types
✅ **Automatic IP Blacklisting** - IPs are automatically blacklisted after threshold violations
✅ **Violation Tracking** - Complete audit trail of rate limit violations
✅ **Manual IP Management** - Admin interface for manual blacklist management
✅ **Per-IP and Per-User Tracking** - Prevents abuse from both anonymous and authenticated users
✅ **Configurable Thresholds** - Easy to adjust limits per endpoint type

---

## Rate Limit Configuration

### Authentication Endpoints
- **Login**: 5 requests/minute, blacklist after 5 violations
- **Registration**: 3 requests/minute, blacklist after 3 violations
- **Password Reset**: 3 requests/5 minutes, blacklist after 5 violations

### Transfer Endpoints
- **NGN Transfer**: 10 requests/minute, blacklist after 10 violations
- **International Transfer**: 5 requests/minute, blacklist after 8 violations
- **Bulk Transfer**: 2 requests/minute, blacklist after 5 violations

### Bill Payment Endpoints
- **Airtime**: 20 requests/minute, blacklist after 15 violations
- **Data**: 20 requests/minute, blacklist after 15 violations
- **Electricity**: 15 requests/minute, blacklist after 12 violations
- **Cable TV**: 15 requests/minute, blacklist after 12 violations
- **Internet**: 15 requests/minute, blacklist after 12 violations

### Default (Other Endpoints)
- **Default**: 60 requests/minute, blacklist after 20 violations

---

## How It Works

### 1. **Request Processing**
```
User makes request
    ↓
Check if IP is blacklisted → YES → Return 403 Forbidden
    ↓ NO
Check rate limit
    ↓
Within limit? → YES → Process request
    ↓ NO
Record violation
    ↓
Violations >= threshold? → YES → Blacklist IP
    ↓ NO
Return 429 Too Many Requests
```

### 2. **Violation Tracking**
- Each rate limit exceeded creates/updates a violation record
- Violations are tracked per IP + endpoint combination
- Violation count accumulates across time
- Old violations (30+ days) are automatically cleaned up

### 3. **Automatic Blacklisting**
When an IP reaches the violation threshold:
- IP is added to blacklist table
- All future requests from that IP are blocked
- Admin notification is sent
- Detailed logging for forensic analysis

---

## Database Tables

### `ip_blacklist`
Stores blacklisted IP addresses with full audit trail.

**Fields:**
- `ip_address` - IPv4 or IPv6 address
- `user_id` - Associated user (if logged in)
- `reason` - Reason for blacklisting
- `violation_count` - Number of violations before blacklist
- `endpoint` - Endpoint that triggered blacklist
- `blacklisted_by` - Admin who manually blacklisted (null for automatic)
- `notes` - Additional admin notes
- `is_active` - Active status (can be deactivated)

### `rate_limit_violations`
Tracks all rate limit violations before blacklisting.

**Fields:**
- `ip_address` - IPv4 or IPv6 address
- `user_id` - Associated user (if logged in)
- `endpoint` - API endpoint path
- `method` - HTTP method (GET, POST, etc.)
- `violation_count` - Number of times violated
- `requests_made` - Number of requests made when violated
- `rate_limit` - The rate limit that was exceeded
- `time_window` - Time window for the rate limit
- `user_agent` - Browser/client information
- `last_violation_at` - Timestamp of last violation

---

## Admin API Endpoints

All endpoints require `auth:sanctum` and `AdminMiddleware`.

### List Blacklisted IPs
```http
GET /api/admin/ip-blacklist
Query Parameters:
  - per_page: Number per page (default: 15)
  - status: active|inactive|all (default: active)
  - search: IP address to search
  - user_id: Filter by user ID
```

### Get Statistics
```http
GET /api/admin/ip-blacklist/stats

Response:
{
  "total_blacklisted": 150,
  "active_blacklisted": 120,
  "inactive_blacklisted": 30,
  "automatic_blacklists": 100,
  "manual_blacklists": 50,
  "today_blacklisted": 5,
  "this_week_blacklisted": 25,
  "this_month_blacklisted": 80
}
```

### Get IP Details
```http
GET /api/admin/ip-blacklist/ip/{ip_address}
```

### Manually Blacklist IP
```http
POST /api/admin/ip-blacklist
Body:
{
  "ip_address": "192.168.1.100",
  "reason": "Manual blacklist - suspicious activity",
  "notes": "Attempted multiple fraudulent transactions",
  "user_id": 123 (optional)
}
```

### Update Blacklist Record
```http
PUT /api/admin/ip-blacklist/{id}
Body:
{
  "reason": "Updated reason",
  "notes": "Additional notes",
  "is_active": true
}
```

### Remove from Blacklist
```http
DELETE /api/admin/ip-blacklist/{id}
```

### Reactivate Blacklist
```http
POST /api/admin/ip-blacklist/{id}/reactivate
```

### Force Delete (Superadmin Only)
```http
DELETE /api/admin/ip-blacklist/{id}/force
```

### Bulk Remove (Superadmin Only)
```http
POST /api/admin/ip-blacklist/bulk-remove
Body:
{
  "ids": [1, 2, 3, 4, 5]
}
```

---

## Response Examples

### Rate Limit Exceeded (Before Blacklist)
```json
{
  "success": false,
  "message": "Too many requests. Please try again in 1 minute(s).",
  "code": "RATE_LIMIT_EXCEEDED",
  "retry_after": 60,
  "attempts": 6,
  "max_attempts": 5,
  "violations": 3,
  "blacklist_threshold": 5
}
```

### IP Blacklisted
```json
{
  "success": false,
  "message": "Access denied. Your IP has been blacklisted due to suspicious activity.",
  "code": "IP_BLACKLISTED"
}
```

### Rate Limit Headers
All responses include these headers:
```
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 2
```

---

## Deployment Steps

### 1. Run Migrations
```bash
php artisan migrate
```

### 2. Schedule Violation Cleanup (Optional)
Add to `app/Console/Kernel.php`:
```php
protected function schedule(Schedule $schedule)
{
    // Clean up violations older than 30 days
    $schedule->command('rate-limit:clean --days=30')->daily();
}
```

### 3. Test Rate Limiting
```bash
# Test login rate limit (should block after 5 attempts)
for i in {1..10}; do
  curl -X POST http://localhost:8000/api/login \
    -H "Content-Type: application/json" \
    -d '{"email":"test@test.com","password":"wrong"}'
  sleep 1
done
```

### 4. Configure Rate Limits (Optional)
Edit `app/Http/Middleware/AdvancedRateLimitMiddleware.php` to adjust:
- Requests per minute
- Violation thresholds
- Time windows

---

## Monitoring & Alerts

### Log Files
All rate limiting events are logged:
```php
// Blocked blacklisted IP
Log::warning('Blocked request from blacklisted IP', [...]);

// Rate limit exceeded
Log::warning('Rate limit exceeded', [...]);

// IP automatically blacklisted
Log::alert('IP automatically blacklisted', [...]);
```

### Database Queries for Monitoring

**Top violating IPs:**
```sql
SELECT ip_address, SUM(violation_count) as total_violations
FROM rate_limit_violations
WHERE last_violation_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
GROUP BY ip_address
ORDER BY total_violations DESC
LIMIT 20;
```

**Recent blacklists:**
```sql
SELECT * FROM ip_blacklist
WHERE created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)
ORDER BY created_at DESC;
```

**Automatic vs manual blacklists:**
```sql
SELECT 
  CASE WHEN blacklisted_by IS NULL THEN 'Automatic' ELSE 'Manual' END as type,
  COUNT(*) as count
FROM ip_blacklist
WHERE is_active = 1
GROUP BY type;
```

---

## Troubleshooting

### Legitimate User Blacklisted?

1. Check violation records:
```sql
SELECT * FROM rate_limit_violations WHERE ip_address = '123.45.67.89';
```

2. Remove from blacklist via admin panel:
```http
DELETE /api/admin/ip-blacklist/{id}
```

3. Or update the record:
```sql
UPDATE ip_blacklist SET is_active = 0 WHERE ip_address = '123.45.67.89';
```

### Rate Limits Too Strict?

Edit `AdvancedRateLimitMiddleware.php` and adjust the `RATE_LIMITS` array:
```php
private const RATE_LIMITS = [
    'auth:login' => [10, 1, 10],  // Increased from 5 to 10
    // ... other limits
];
```

### Clear All Violations
```bash
php artisan rate-limit:clean --days=0
```

---

## Security Best Practices

1. **Monitor Logs** - Regularly check for patterns of attacks
2. **Review Blacklist** - Periodically review blacklisted IPs
3. **Adjust Thresholds** - Fine-tune based on your traffic patterns
4. **Backup Data** - Keep backups of blacklist and violation tables
5. **Test Regularly** - Ensure rate limiting works as expected

---

## Files Created/Modified

### New Files:
- `app/Models/IPBlacklist.php`
- `app/Models/RateLimitViolation.php`
- `app/Http/Middleware/AdvancedRateLimitMiddleware.php`
- `app/Http/Controllers/IPBlacklistController.php`
- `app/Console/Commands/CleanRateLimitViolations.php`
- `database/migrations/2026_02_28_000001_create_ip_blacklist_table.php`
- `database/migrations/2026_02_28_000002_create_rate_limit_violations_table.php`
- `routes/allapiroutes/ip-blacklist.php`

### Modified Files:
- `app/Http/Kernel.php` - Added middleware alias
- `routes/allapiroutes/auth.php` - Applied to auth routes
- `routes/allapiroutes/transfer.php` - Applied to transfer routes
- `routes/allapiroutes/airtime.php` - Applied to airtime/data routes
- `routes/allapiroutes/electricity.php` - Applied to electricity routes
- `routes/allapiroutes/cabletv.php` - Applied to cable TV routes

---

## Future Enhancements

- [ ] Email notifications when IP is blacklisted
- [ ] Slack/Discord webhook integration
- [ ] GeoIP analysis for suspicious locations
- [ ] Machine learning for pattern detection
- [ ] Whitelist feature for trusted IPs
- [ ] Temporary bans (auto-expire after X hours)
- [ ] User-level rate limits independent of IP
- [ ] CAPTCHA integration after X violations

---

## Support

For issues or questions:
1. Check logs: `storage/logs/laravel.log`
2. Review violation records in database
3. Test with curl commands shown above
4. Adjust thresholds if needed
