# IP Management Feature Design

## Overview

The IP Management feature extends the RateLoader module to provide control over which IP addresses can access the HTTP server. This feature adds a new "IP Management" tab to the GUI that displays all connecting IP addresses with their access status.

## Data Structure

### IP Storage Format

IP addresses will be stored in a separate JSON file (`ip_access.json`) with the following structure:

```json
{
	"global_access": "allowed", // "allowed" or "restricted"
	"ips": {
		"192.168.1.100": {
			"status": "allowed", // "allowed" or "restricted"
			"first_seen": "2025-10-28T11:15:00Z",
			"last_seen": "2025-10-28T11:45:30Z",
			"request_count": 15,
			"last_request_type": "POST"
		},
		"10.0.0.50": {
			"status": "restricted",
			"first_seen": "2025-10-28T10:30:00Z",
			"last_seen": "2025-10-28T11:00:15Z",
			"request_count": 3,
			"last_request_type": "GET"
		}
	}
}
```

### IP Management Module (`core/ip_manager.py`)

```python
class IPManager:
    """Manages IP address access control for RateLoader HTTP server."""

    def __init__(self, ip_file="ip_access.json"):
        """Initialize IP manager with storage file."""

    def is_ip_allowed(self, ip_address: str) -> bool:
        """Check if IP address is allowed to access the server."""

    def record_request(self, ip_address: str, request_type: str):
        """Record a request from an IP address."""

    def set_ip_status(self, ip_address: str, status: str):
        """Set the status of an IP address (allowed/restricted)."""

    def set_global_access(self, status: str):
        """Set global access mode (allowed/restricted)."""

    def get_all_ips(self) -> dict:
        """Get all tracked IP addresses with their metadata."""

    def remove_ip(self, ip_address: str):
        """Remove an IP address from tracking."""
```

## HTTP Server Integration

### Request Processing Flow

1. When a request comes in, extract the client IP address
2. Check if IP is allowed using `IPManager.is_ip_allowed()`
3. If not allowed, return 403 Forbidden response
4. If allowed, record the request using `IPManager.record_request()`
5. Process the request normally

### Modified HTTP Request Handler

The `RateLoaderRequestHandler` will be extended to:

- Extract client IP from `self.client_address[0]`
- Check access permissions before processing requests
- Log access attempts (both allowed and denied)
- Record request metadata

## GUI Implementation

### IP Management Tab Layout

```
┌─────────────────────────────────────────────────────────────┐
│ IP Management                                              │
├─────────────────────────────────────────────────────────────┤
│ Global Access: [○ Allowed ● Restricted]                     │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ IP Address      │ Status    │ Last Seen    │ Requests  │ │
│ │ 192.168.1.100   │ Allowed   │ 11:45:30     │ 15        │ │
│ │ 10.0.0.50       │ Restricted│ 11:00:15     │ 3         │ │
│ │ 172.16.0.25     │ Allowed   │ 10:30:00     │ 8         │ │
│ └─────────────────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ [Toggle Selected] [Remove Selected] [Refresh] [Export List] │
└─────────────────────────────────────────────────────────────┘
```

### GUI Components

- **Global Access Toggle**: Radio buttons or switch for master control
- **IP List**: Treeview or table with sortable columns
- **Action Buttons**: Toggle status, remove IP, refresh list, export to CSV
- **Status Bar**: Shows total IPs, allowed count, restricted count

## Configuration Integration

### Settings.ini Additions

```ini
[IPManagement]
ip_file = ip_access.json
auto_add_new_ips = 1
log_denied_requests = 1
max_tracked_ips = 1000
```

### Default Behavior

- New IPs are automatically added with "Allowed" status
- Global access defaults to "Allowed"
- Denied requests are logged with IP address and timestamp
- Maximum of 1000 tracked IPs (oldest removed when limit reached)

## Security Considerations

### IP Address Validation

- Validate IP address format before adding to tracking
- Handle IPv4 and IPv6 addresses
- Sanitize input to prevent injection attacks

### Access Control Logic

```
if global_access == "restricted":
    # Only explicitly allowed IPs can access
    return ip_status == "allowed"
else:  # global_access == "allowed"
    # All IPs can access unless explicitly restricted
    return ip_status != "restricted"
```

## Error Handling

### File Operations

- Handle missing or corrupted `ip_access.json` file
- Create default file if none exists
- Backup file before writes to prevent data loss

### GUI Errors

- Handle file permission errors gracefully
- Show user-friendly error messages
- Provide recovery options when possible

## Performance Considerations

### Memory Usage

- Limit number of tracked IPs
- Implement LRU eviction for old IPs
- Use efficient data structures for lookups

### File I/O

- Batch write operations to reduce disk I/O
- Use file locking to prevent corruption
- Implement lazy loading for large IP lists

## Testing Strategy

### Unit Tests

- Test IP address validation
- Test access control logic
- Test file read/write operations
- Test GUI component interactions

### Integration Tests

- Test HTTP server integration
- Test end-to-end request flow
- Test configuration persistence
- Test GUI refresh functionality

### Security Tests

- Test with malformed IP addresses
- Test with large numbers of requests
- Test file permission scenarios
- Test concurrent access scenarios
